Files
ERP/src/lib/server/models/Product.ts
T
denis_ireri 83ec5ecd36 Enforce tenant isolation in the data layer instead of per route
Every route had to remember to add the business filter to every query;
nothing stopped one that forgot. The audit for this change found several
that had: the M-Pesa status re-check, the stock ledger's duplicate checks,
the daily-inventory and branch-price upserts, a cash-sale replay lookup,
several load-by-id lookups, and every populate().

- tenantGuard: a Mongoose plugin on all ten business-scoped models. Any
  find/update/delete/count/distinct, or an aggregate whose first stage is
  not a $match, that does not pin exactly one businessId throws
  TenantScopeError before reaching the database ($in, $exists and other
  operators do not count).
- crossTenant("reason", fn): the explicit, documented exemption for the
  queries that must span businesses - login's email lookup, refresh and
  invite-token lookups, the M-Pesa callback, the platform console and the
  maintenance scripts. git grep crossTenant lists them all.
- scopedPopulate: populated branch, product and staff names are also
  restricted to the business.
- Every flagged query site now names the business (or is exempted with a
  reason).
- Tests: a check that every model with a businessId field carries the
  guard; the guard refusing unscoped queries of every kind; and a route
  sweep where business A sends business B's ids to every read route
  (nothing of B's comes back) and every write route (all refused, B's
  data unchanged). Test-side database inspections go through db(), an
  explicit test exemption. Removing one route's business filter makes the
  suite fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:52:35 +03:00

68 lines
2.6 KiB
TypeScript

import { tenantGuard } from "@/lib/server/tenantGuard";
import { Schema, model, models, Model, Types, Document } from "mongoose";
export interface IProduct extends Document {
_id: Types.ObjectId;
businessId: Types.ObjectId; // tenant this product belongs to
label: string;
// Size measured in `unit` (litres for water, a count for side items).
// The field keeps its historical name so existing data needs no migration.
sizeLiters: number;
unit: string; // see PRODUCT_UNITS in src/lib/units.ts: "L", "pcs", "tray"...
category: string; // e.g. "Water", "Eggs"
unitPrice: number;
sortOrder: number;
isActive: boolean;
lowStockThreshold: number; // a branch at or below this many units shows a low-stock warning
createdAt: Date;
updatedAt: Date;
}
const productSchema = new Schema<IProduct>(
{
businessId: { type: Schema.Types.ObjectId, ref: "Business", required: true, index: true },
label: { type: String, required: true, trim: true },
sizeLiters: { type: Number, required: true, min: 0.1 },
unit: { type: String, default: "L", trim: true },
category: { type: String, default: "Water", trim: true },
unitPrice: { type: Number, required: true, min: 0 },
sortOrder: { type: Number, default: 0 },
isActive: { type: Boolean, default: true, index: true },
lowStockThreshold: { type: Number, default: 10, min: 0 },
},
{ timestamps: true }
);
productSchema.plugin(tenantGuard);
export const Product =
(models.Product as Model<IProduct>) || model<IProduct>("Product", productSchema);
// Branch-specific price override — optional, falls back to Product.unitPrice.
export interface IBranchPricing extends Document {
businessId: Types.ObjectId;
branchId: Types.ObjectId;
productId: Types.ObjectId;
unitPrice: number;
updatedBy: Types.ObjectId | null;
updatedAt: Date;
}
const branchPricingSchema = new Schema<IBranchPricing>(
{
businessId: { type: Schema.Types.ObjectId, ref: "Business", required: true, index: true },
branchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
productId: { type: Schema.Types.ObjectId, ref: "Product", required: true },
unitPrice: { type: Number, required: true, min: 0 },
updatedBy: { type: Schema.Types.ObjectId, ref: "User", default: null },
},
{ timestamps: { createdAt: false, updatedAt: true } }
);
branchPricingSchema.index({ branchId: 1, productId: 1 }, { unique: true });
branchPricingSchema.plugin(tenantGuard);
export const BranchPricing =
(models.BranchPricing as Model<IBranchPricing>) ||
model<IBranchPricing>("BranchPricing", branchPricingSchema);