Ingest counter sales from the POS terminals, over MQTT and HTTP

A till holds every bill in its own SQLite database and keeps it for
seven days after we acknowledge it, marking one synced only when its id
comes back in an ack. Everything here follows from that.

Silence is not acceptance, so a failing ingest publishes nothing at all
and the terminal simply sends again. A duplicate is a success, because
at-least-once delivery means a lost ack legitimately re-delivers bills
we already hold, and calling those failures would strand a day of
takings on the till. Deduplication is a unique index on the terminal's
UUID plus an advisory lock held for the transaction.

Bills land in pos_orders / pos_order_items rather than orders: a counter
bill carries a cashier, a terminal, a rounding adjustment, promos,
loyalty movement and a payment split that orders has nowhere to put, and
forcing one into the other loses whatever does not fit. Stock is *not*
split — a counter sale writes the same productstocks rows an app order
does, through helpers extracted from createOrderTx so the rule that
prevents overselling has one implementation rather than two.
GetRevenueSummary and GetSalesSummary were extended to union the new
table in; any new report has to remember the same.

Terminal health goes to Redis under a 90-second TTL, sharing the
instance the express backend uses. A heartbeat is a fact with an expiry
date: a till that loses power stops refreshing and ages off the board by
itself, where a Postgres row would need ~288k writes a day and a reaper.

Proven end to end against the live estate before commit: a bill over
HTTP and one over the real Mosquitto broker, the same bill three times
producing one row and one stock movement, and a heartbeat arriving on
the health endpoint. All probe data was removed afterwards.

Four things that only surfaced against real data. An unset jsonb column
failed the very first bill. Product SKUs are unusable as barcodes — 6,245
products share 93 SKUs and "1" covers 5,794 of them — against the till's
unique index, so barcodes fall back to the product id. A taxpercent of
-1 exists and would have put negative GST in a filed slab. And a product
with id 0 exists, which can never be billed and is now skipped.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Suriya
2026-08-03 17:48:00 +05:30
parent 583cd89063
commit e3459a0f1c
23 changed files with 3679 additions and 171 deletions

33
main.go
View File

@@ -5,6 +5,7 @@ import (
"log"
"nearle/db"
"nearle/facade"
"nearle/messaging"
"nearle/models"
"nearle/routes"
"os"
@@ -39,13 +40,36 @@ func main() {
db.Connect()
fmt.Println("✅ Database connections established!")
// Shared with the express backend. POS terminal presence lives here under a
// TTL; optional, because losing the health board is an inconvenience and
// losing a sale is not.
db.InitRedis()
// Ensure schema is updated
db.DB.AutoMigrate(&models.StockRequest{})
// Counter sales from the in-store terminals. Separate tables from `orders`
// because a bill carries a cashier, a terminal, rounding, promos, loyalty
// and a payment split that `orders` has nowhere to put.
if err := db.DB.AutoMigrate(&models.PosOrders{}, &models.PosOrderItems{}); err != nil {
log.Fatal("POS schema migration failed:", err)
}
f := facade.NewFacade(db.DB, db.CatalogueDB)
routes.RegisterRoutes(app, f)
// POS terminals reach the ingest over MQTT when MQTT_URL is set, and over
// HTTP otherwise. Both land on the same service, so a bill cannot behave
// differently depending on how it arrived.
//
// A broker that is configured but unreachable is fatal on purpose: coming
// up healthy while every till quietly queues is the worse failure.
posMqtt, err := messaging.StartPosMqttConsumer(f.PosService())
if err != nil {
log.Fatal("POS MQTT consumer failed to start:", err)
}
// Start server
go func() {
if err := app.Listen(":1122"); err != nil {
@@ -53,7 +77,7 @@ func main() {
}
}()
gracefulShutdown()
gracefulShutdown(posMqtt)
}
func selectDBMiddleware(c *fiber.Ctx) error {
@@ -78,13 +102,18 @@ func selectDBMiddleware(c *fiber.Ctx) error {
return c.Next()
}
func gracefulShutdown() {
func gracefulShutdown(posMqtt *messaging.PosMqttConsumer) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
fmt.Println("\nShutting down gracefully...")
// Drained before anything else: a bill mid-commit still gets its ack, and
// without one the terminal would hold it and send it again on restart.
posMqtt.Close()
db.CloseRedis()
// Normally: close db.DB_DEV and db.DB_LIVE
// Example:
// closeDB(db.DB_DEV)