Add a stock ledger, inter-branch transfers and a sync protocol that cannot jam

Stock (PRD 5.2): a branch's stock of a product is now the sum of its
StockMovement rows. Every movement names the document that caused it and
(type, refId) is unique, so replaying a sale, retrying a transfer or a
second M-Pesa callback never moves the same stock twice.

- Cash sales and confirmed M-Pesa payments deduct stock; purchases of a
  catalogue product add it.
- POST /api/stock/transfers moves stock between two branches (owner: any
  two; manager: out of their own) and refuses to send more than the
  sending branch holds. Double submits are applied once.
- POST /api/stock/adjustments records opening stock, breakage or a
  physical count (the ledger is corrected to the counted number).
- GET /api/stock returns every branch x product with LOW/OUT flags
  (per-product lowStockThreshold, default 10); GET /api/stock/movements
  is the history.

Sync (PRD 5.3/5.5): POST /api/transactions/cash now returns a result per
sale - saved, duplicate or rejected - instead of silently skipping
replays. The old client never learned a replayed sale had synced, so
rows piled up until the batch passed the 100-sale limit and every flush
failed with 400. Also:
- A sale can hold several products (one Transaction per line, grouped by
  saleId); the old single-product payload is still accepted.
- One bad sale is rejected on its own instead of failing the batch.
- A queued sale is only accepted from the cashier who recorded it, and
  stays with the branch where it happened.
- A product deactivated while offline is still recorded at its price; an
  invalid phone is dropped rather than losing the sale; the phone is now
  optional for cash sales.
- The price the device showed is kept and a difference is flagged
  (priceMismatch) instead of being silently overwritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 18:39:11 +03:00
parent d4808b3e46
commit 8817c0f52f
15 changed files with 982 additions and 69 deletions
+51
View File
@@ -0,0 +1,51 @@
import { Schema, model, models, Model, Types, Document } from "mongoose";
export const MOVEMENT_TYPES = ["SALE", "PURCHASE", "TRANSFER_OUT", "TRANSFER_IN", "ADJUSTMENT"] as const;
export type MovementType = (typeof MOVEMENT_TYPES)[number];
export interface IStockMovement extends Document {
_id: Types.ObjectId;
businessId: Types.ObjectId;
branchId: Types.ObjectId;
productId: Types.ObjectId;
type: MovementType;
quantity: number; // signed: + adds stock to the branch, - removes it
refId: string; // the document that caused it (transaction, purchase, transfer, adjustment)
note: string | null;
recordedBy: Types.ObjectId | null;
createdAt: Date; // authoritative — server clock
}
/**
* The stock ledger. A branch's stock of a product is the SUM of its
* movements — there is no separately stored balance that could drift out
* of step with history.
*
* Every movement names the document that caused it, and (type, refId) is
* unique. Writing a movement is therefore idempotent: replaying an offline
* sale, retrying a transfer, or a second M-Pesa callback can never deduct
* or add the same stock twice. A transfer writes two movements with the
* same refId but different types (TRANSFER_OUT, TRANSFER_IN).
*/
const stockMovementSchema = new Schema<IStockMovement>(
{
businessId: { type: Schema.Types.ObjectId, ref: "Business", required: true },
branchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
productId: { type: Schema.Types.ObjectId, ref: "Product", required: true },
type: { type: String, enum: MOVEMENT_TYPES, required: true },
quantity: { type: Number, required: true },
refId: { type: String, required: true },
note: { type: String, default: null, trim: true },
recordedBy: { type: Schema.Types.ObjectId, ref: "User", default: null },
},
{ timestamps: { createdAt: true, updatedAt: false } }
);
stockMovementSchema.index({ type: 1, refId: 1 }, { unique: true });
// Stock-level aggregation and the per-branch movement history.
stockMovementSchema.index({ businessId: 1, branchId: 1, productId: 1 });
stockMovementSchema.index({ businessId: 1, branchId: 1, createdAt: -1 });
export const StockMovement =
(models.StockMovement as Model<IStockMovement>) ||
model<IStockMovement>("StockMovement", stockMovementSchema);
+40
View File
@@ -0,0 +1,40 @@
import { Schema, model, models, Model, Types, Document } from "mongoose";
export interface IStockTransfer extends Document {
_id: Types.ObjectId;
businessId: Types.ObjectId;
fromBranchId: Types.ObjectId;
toBranchId: Types.ObjectId;
productId: Types.ObjectId;
quantity: number;
clientUuid: string; // idempotency key from the form, so a double-submit moves stock once
note: string | null;
recordedBy: Types.ObjectId;
createdAt: Date;
}
/**
* An inter-branch stock transfer. The stock itself moves through two
* StockMovement rows (TRANSFER_OUT at the source, TRANSFER_IN at the
* destination) whose refId is this transfer's id.
*/
const stockTransferSchema = new Schema<IStockTransfer>(
{
businessId: { type: Schema.Types.ObjectId, ref: "Business", required: true },
fromBranchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
toBranchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
productId: { type: Schema.Types.ObjectId, ref: "Product", required: true },
quantity: { type: Number, required: true, min: 1 },
clientUuid: { type: String, required: true },
note: { type: String, default: null, trim: true },
recordedBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
},
{ timestamps: { createdAt: true, updatedAt: false } }
);
stockTransferSchema.index({ businessId: 1, clientUuid: 1 }, { unique: true });
stockTransferSchema.index({ businessId: 1, createdAt: -1 });
export const StockTransfer =
(models.StockTransfer as Model<IStockTransfer>) ||
model<IStockTransfer>("StockTransfer", stockTransferSchema);
+15 -3
View File
@@ -9,7 +9,7 @@ export interface ITransaction extends Document {
branchId: Types.ObjectId;
staffId: Types.ObjectId;
customerName: string | null;
customerPhone: string;
customerPhone: string | null; // optional for cash sales; required for M-Pesa
productId: Types.ObjectId;
sizeLiters: number; // snapshotted at sale time
quantity: number;
@@ -26,8 +26,15 @@ export interface ITransaction extends Document {
resultDesc: string | null;
};
clientUuid: string; // idempotency key generated on-device
clientUuid: string; // idempotency key for this line: `${saleId}:${lineIndex}` for cash sales
saleId: string | null; // groups the lines of one multi-item sale (the device's sale UUID)
lineIndex: number;
syncedFromOffline: boolean;
// What the device showed and collected per unit. The server price stays
// authoritative; a difference (e.g. the price changed while the device
// was offline) is kept and flagged rather than silently overwritten.
clientUnitPrice: number | null;
priceMismatch: boolean;
// TAMPER PREVENTION: this is what the device *claimed* the time was when
// the sale happened — informational only, e.g. for offline-queue
@@ -50,7 +57,7 @@ const transactionSchema = new Schema<ITransaction>(
branchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
staffId: { type: Schema.Types.ObjectId, ref: "User", required: true },
customerName: { type: String, default: null, trim: true },
customerPhone: { type: String, required: true },
customerPhone: { type: String, default: null },
productId: { type: Schema.Types.ObjectId, ref: "Product", required: true },
sizeLiters: { type: Number, required: true },
quantity: { type: Number, required: true, min: 1 },
@@ -73,7 +80,11 @@ const transactionSchema = new Schema<ITransaction>(
},
clientUuid: { type: String, required: true },
saleId: { type: String, default: null },
lineIndex: { type: Number, default: 0 },
syncedFromOffline: { type: Boolean, default: false },
clientUnitPrice: { type: Number, default: null },
priceMismatch: { type: Boolean, default: false },
clientSubmittedAt: { type: Date, default: null },
},
{ timestamps: true } // createdAt/updatedAt set from the server's Date.now(), not client input
@@ -92,6 +103,7 @@ transactionSchema.index({ clientUuid: 1 }, { unique: true });
transactionSchema.index({ branchId: 1, createdAt: -1 });
transactionSchema.index({ businessId: 1, createdAt: -1 });
transactionSchema.index({ paymentStatus: 1 });
transactionSchema.index({ businessId: 1, saleId: 1 });
export const Transaction =
(models.Transaction as Model<ITransaction>) ||