Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

15.4 KB
Raw Blame
-- Revenue recognition core: account defaults, seeded accounts, sequence,
-- close task, service dates on sales lines, schedule + run tables. Idempotent.
-- Spec: .ai/specs/2026-09-22-revenue-recognition-and-rentals.md §1

-- 1) Account defaults ----------------------------------------------------------
ALTER TABLE "accountDefault"
  ADD COLUMN IF NOT EXISTS "deferredRevenueAccount" TEXT,
  ADD COLUMN IF NOT EXISTS "contractAssetAccount" TEXT,
  ADD COLUMN IF NOT EXISTS "rentalIncomeAccount" TEXT,
  ADD COLUMN IF NOT EXISTS "leaseRevenueAccount" TEXT,
  ADD COLUMN IF NOT EXISTS "leaseInterestIncomeAccount" TEXT,
  ADD COLUMN IF NOT EXISTS "netInvestmentInLeasesAccount" TEXT;

DO $rrfk$
DECLARE
  col TEXT;
BEGIN
  FOREACH col IN ARRAY ARRAY[
    'deferredRevenueAccount', 'contractAssetAccount', 'rentalIncomeAccount',
    'leaseRevenueAccount', 'leaseInterestIncomeAccount', 'netInvestmentInLeasesAccount'
  ] LOOP
    IF NOT EXISTS (
      SELECT 1 FROM pg_constraint
      WHERE conrelid = '"accountDefault"'::regclass AND conname = 'accountDefault_' || col || '_fkey'
    ) THEN
      EXECUTE format(
        'ALTER TABLE "accountDefault" ADD CONSTRAINT %I FOREIGN KEY (%I) REFERENCES "account"(id) ON DELETE RESTRICT ON UPDATE CASCADE',
        'accountDefault_' || col || '_fkey', col
      );
    END IF;
  END LOOP;
END $rrfk$;

-- 2) Accounts, one per company group that has a chart ------------------------------
-- Re-runnable: a group that already holds the number OR the name keeps its account (the
-- name is unique per group, so inserting a second one would fail). The parent is the
-- seeded group by NAME (never number, which group headers do not carry); a chart that
-- renamed or dropped that group falls back to the group holding a seeded sibling, and
-- only then to the chart root, with a NOTICE naming the group so it can be re-parented.
DO $rraccounts$
DECLARE
  spec RECORD;
  grp TEXT;
  parent_id TEXT;
BEGIN
  FOR spec IN
    SELECT * FROM (VALUES
      ('2160', 'Deferred Revenue', 'Liability', 'Other Current Liability', 'Balance Sheet', 'Current', 'Current Liabilities', ARRAY['2110', '2125', '2140', '2150', '2170', '2180']),
      ('1145', 'Contract Assets', 'Asset', 'Other Current Asset', 'Balance Sheet', 'Current', 'Receivables', ARRAY['1110', '1130', '1150']),
      ('1160', 'Net Investment in Leases', 'Asset', 'Other Current Asset', 'Balance Sheet', 'Current', 'Receivables', ARRAY['1110', '1130', '1150']),
      ('4060', 'Rental Income', 'Revenue', 'Income', 'Income Statement', 'Average', 'Revenue', ARRAY['4010', '4020', '4030', '4040', '4050']),
      ('4070', 'Lease Revenue', 'Revenue', 'Income', 'Income Statement', 'Average', 'Revenue', ARRAY['4010', '4020', '4030', '4040', '4050']),
      ('4150', 'Interest Income – Leases', 'Revenue', 'Other Income', 'Income Statement', 'Average', 'Other Income', ARRAY['4110', '4120', '4130', '4140'])
    ) AS s(number, name, class, account_type, income_balance, consolidated_rate, parent_name, sibling_numbers)
  LOOP
    FOR grp IN SELECT DISTINCT a."companyGroupId" FROM "account" a LOOP
      CONTINUE WHEN EXISTS (
        SELECT 1 FROM "account" a
        WHERE a."companyGroupId" = grp AND (a.number = spec.number OR a.name = spec.name)
      );

      SELECT g.id INTO parent_id
      FROM "account" g
      WHERE g."companyGroupId" = grp AND g."isGroup" = TRUE AND g.name = spec.parent_name
      LIMIT 1;

      IF parent_id IS NULL THEN
        SELECT p.id INTO parent_id
        FROM "account" a
        JOIN "account" p ON p.id = a."parentId" AND p."isGroup" = TRUE
        WHERE a."companyGroupId" = grp AND a.number = ANY (spec.sibling_numbers)
        ORDER BY array_position(spec.sibling_numbers, a.number)
        LIMIT 1;
      END IF;

      IF parent_id IS NULL THEN
        RAISE NOTICE 'revenue-recognition-core: company group % has no "%" group; account % % is at the chart root',
          grp, spec.parent_name, spec.number, spec.name;
      END IF;

      INSERT INTO "account" ("id", "number", "name", "class", "accountType", "incomeBalance", "consolidatedRate", "parentId", "isGroup", "active", "isSystem", "companyGroupId", "createdBy")
      VALUES (
        id('acct'), spec.number, spec.name, spec.class::"glAccountClass", spec.account_type::"accountType",
        spec.income_balance::"glIncomeBalance", spec.consolidated_rate::"glConsolidatedRate",
        parent_id, false, true, false, grp, 'system'
      );
    END LOOP;
  END LOOP;
END $rraccounts$;

-- 3) Backfill the six defaults by id: by number, then by leaf name for a group that
--    renumbered the account (the loop above kept theirs rather than add a duplicate).
DO $rrdefaults$
DECLARE
  spec RECORD;
BEGIN
  FOR spec IN
    SELECT * FROM (VALUES
      ('deferredRevenueAccount', '2160', 'Deferred Revenue'),
      ('contractAssetAccount', '1145', 'Contract Assets'),
      ('rentalIncomeAccount', '4060', 'Rental Income'),
      ('leaseRevenueAccount', '4070', 'Lease Revenue'),
      ('leaseInterestIncomeAccount', '4150', 'Interest Income – Leases'),
      ('netInvestmentInLeasesAccount', '1160', 'Net Investment in Leases')
    ) AS s(col, number, name)
  LOOP
    EXECUTE format(
      'UPDATE "accountDefault" ad SET %1$I = a.id, "updatedBy" = ''system''
       FROM "company" c JOIN "account" a ON a."companyGroupId" = c."companyGroupId" AND a.number = %2$L
       WHERE ad."companyId" = c.id AND ad.%1$I IS NULL',
      spec.col, spec.number
    );
    EXECUTE format(
      'UPDATE "accountDefault" ad SET %1$I = a.id, "updatedBy" = ''system''
       FROM "company" c JOIN "account" a ON a."companyGroupId" = c."companyGroupId"
         AND a.name = %2$L AND a."isGroup" = FALSE
       WHERE ad."companyId" = c.id AND ad.%1$I IS NULL',
      spec.col, spec.name
    );
  END LOOP;
END $rrdefaults$;

-- Revenue recognition follows accountingEnabled, so every company must leave with a
-- usable Deferred Revenue default: an unmapped or non-Liability-leaf account would make
-- every dated invoice line refuse to post.
DO $rrdeferred$
BEGIN
  IF EXISTS (
    SELECT 1 FROM "accountDefault" ad
    LEFT JOIN "account" a ON a.id = ad."deferredRevenueAccount"
    WHERE a.id IS NULL OR a.class <> 'Liability' OR a."isGroup"
  ) THEN
    RAISE EXCEPTION 'revenue-recognition-core: a company has no Deferred Revenue default, or it is not a Liability leaf account';
  END IF;
END $rrdeferred$;

-- 4) Sequence per company ---------------------------------------------------------
INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")
SELECT 'revenueRecognitionRun', 'Revenue Recognition Run', 'RR', NULL, 0, 6, 1, c.id
FROM "company" c
WHERE NOT EXISTS (SELECT 1 FROM "sequence" s WHERE s."companyId" = c.id AND s."table" = 'revenueRecognitionRun');

-- 5) Close-checklist task (its evaluator ships in the same change set) --------------
INSERT INTO "periodCloseTaskDefinition"
  ("companyId", "name", "taskType", "autoCheckKey", "sortOrder", "required", "severity", "active", "isSystem", "createdBy")
SELECT c."id", 'Recognize revenue for the period', 'Auto', 'unposted-revenue-schedules', 5, true, 'Warning', true, true, 'system'
FROM "company" c
WHERE EXISTS (SELECT 1 FROM "user" u WHERE u."id" = 'system')
  AND NOT EXISTS (
    SELECT 1 FROM "periodCloseTaskDefinition" d
    WHERE d."companyId" = c.id AND d.name = 'Recognize revenue for the period'
  );

-- 6) Service dates on sales order + sales invoice lines -----------------------------
ALTER TABLE "salesOrderLine" ADD COLUMN IF NOT EXISTS "serviceStartDate" DATE, ADD COLUMN IF NOT EXISTS "serviceEndDate" DATE;
ALTER TABLE "salesInvoiceLine" ADD COLUMN IF NOT EXISTS "serviceStartDate" DATE, ADD COLUMN IF NOT EXISTS "serviceEndDate" DATE;

DO $svcdates$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = '"salesOrderLine"'::regclass AND conname = 'salesOrderLine_serviceDates_check') THEN
    ALTER TABLE "salesOrderLine" ADD CONSTRAINT "salesOrderLine_serviceDates_check"
      CHECK (("serviceStartDate" IS NULL) = ("serviceEndDate" IS NULL) AND ("serviceEndDate" IS NULL OR "serviceEndDate" >= "serviceStartDate"));
  END IF;
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = '"salesInvoiceLine"'::regclass AND conname = 'salesInvoiceLine_serviceDates_check') THEN
    ALTER TABLE "salesInvoiceLine" ADD CONSTRAINT "salesInvoiceLine_serviceDates_check"
      CHECK (("serviceStartDate" IS NULL) = ("serviceEndDate" IS NULL) AND ("serviceEndDate" IS NULL OR "serviceEndDate" >= "serviceStartDate"));
  END IF;
END $svcdates$;

-- 7) salesOrderLines selects sl.* before aliased columns, so the new columns need a
--    DROP + CREATE (never CREATE OR REPLACE). Body copied verbatim from
--    20260811123619_widen-sales-production-scale.sql. salesInvoiceLines is recreated
--    with every new line column by 20261006221401_sales-invoice-discount-and-ship-to.sql.
DROP VIEW IF EXISTS "salesOrderLines";
CREATE VIEW "salesOrderLines" WITH(SECURITY_INVOKER=true) AS (
  SELECT
    sl.*,
    i."readableIdWithRevision" as "itemReadableId",
    CASE
      WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
      WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
      ELSE i."thumbnailPath"
    END as "thumbnailPath",
    COALESCE(mu.id, imu.id) as "modelId",
    COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
    COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
    COALESCE(mu."name", imu."name") as "modelName",
    COALESCE(mu."size", imu."size") as "modelSize",
    ic."unitCost" as "unitCost",
    cp."customerPartId",
    cp."customerPartRevision",
    so."orderDate",
    so."customerId",
    so."salesOrderId" as "salesOrderReadableId",
    fa."fixedAssetId" as "assetReadableId",
    fa."name" as "assetName"
  FROM "salesOrderLine" sl
  INNER JOIN "salesOrder" so ON so.id = sl."salesOrderId"
  LEFT JOIN "modelUpload" mu ON sl."modelUploadId" = mu."id"
  LEFT JOIN "item" i ON i.id = sl."itemId"
  LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
  LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
  LEFT JOIN "customerPartToItem" cp ON cp."customerId" = so."customerId" AND cp."itemId" = i.id
  LEFT JOIN "fixedAsset" fa ON fa.id = sl."assetId"
);

-- 8) Schedule + run tables ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS "revenueRecognitionSchedule" (
  "id" TEXT NOT NULL DEFAULT id('rvsc'),
  "companyId" TEXT NOT NULL,
  "type" "revenueScheduleType" NOT NULL,
  "status" "revenueScheduleStatus" NOT NULL DEFAULT 'Planned',
  "salesInvoiceLineId" TEXT,
  "rentalAgreementLineId" TEXT,
  "rentalLeaseScheduleLineId" TEXT,
  "periodStart" DATE NOT NULL,
  "periodEnd" DATE NOT NULL,
  "scheduledDate" DATE NOT NULL,
  "accountingPeriodId" TEXT REFERENCES "accountingPeriod"("id"),
  "amount" NUMERIC NOT NULL,
  "debitAccountId" TEXT NOT NULL REFERENCES "account"("id"),
  "creditAccountId" TEXT NOT NULL REFERENCES "account"("id"),
  "runLineId" TEXT,
  "journalId" TEXT REFERENCES "journal"("id") ON DELETE SET NULL,
  "billedBySalesInvoiceLineId" TEXT,
  "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
  "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
  "updatedBy" TEXT REFERENCES "user"("id"),
  "updatedAt" TIMESTAMP WITH TIME ZONE,
  CONSTRAINT "revenueRecognitionSchedule_pkey" PRIMARY KEY ("id", "companyId"),
  CONSTRAINT "revenueRecognitionSchedule_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_companyId_idx" ON "revenueRecognitionSchedule" ("companyId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_due_idx" ON "revenueRecognitionSchedule" ("companyId", "status", "scheduledDate");
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_invoiceLine_idx" ON "revenueRecognitionSchedule" ("companyId", "salesInvoiceLineId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_rentalLine_idx" ON "revenueRecognitionSchedule" ("companyId", "rentalAgreementLineId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_accountingPeriodId_idx" ON "revenueRecognitionSchedule" ("accountingPeriodId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_debitAccountId_idx" ON "revenueRecognitionSchedule" ("debitAccountId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_creditAccountId_idx" ON "revenueRecognitionSchedule" ("creditAccountId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_journalId_idx" ON "revenueRecognitionSchedule" ("journalId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionSchedule_createdBy_idx" ON "revenueRecognitionSchedule" ("createdBy");

-- RLS: the policies are rendered from packages/database/src/authz/manifest.ts.

CREATE TABLE IF NOT EXISTS "revenueRecognitionRun" (
  "id" TEXT NOT NULL DEFAULT id('rvrn'),
  "companyId" TEXT NOT NULL,
  "runId" TEXT NOT NULL,
  "periodEnd" DATE NOT NULL,
  "status" TEXT NOT NULL DEFAULT 'Draft' CHECK ("status" IN ('Draft', 'Posted')),
  "journalId" TEXT REFERENCES "journal"("id") ON DELETE SET NULL,
  "postedAt" TIMESTAMP WITH TIME ZONE,
  "postedBy" TEXT REFERENCES "user"("id"),
  "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
  "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
  "updatedBy" TEXT REFERENCES "user"("id"),
  "updatedAt" TIMESTAMP WITH TIME ZONE,
  CONSTRAINT "revenueRecognitionRun_pkey" PRIMARY KEY ("id", "companyId"),
  CONSTRAINT "revenueRecognitionRun_runId_companyId_key" UNIQUE ("runId", "companyId"),
  CONSTRAINT "revenueRecognitionRun_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX IF NOT EXISTS "revenueRecognitionRun_companyId_idx" ON "revenueRecognitionRun" ("companyId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionRun_journalId_idx" ON "revenueRecognitionRun" ("journalId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionRun_postedBy_idx" ON "revenueRecognitionRun" ("postedBy");
CREATE INDEX IF NOT EXISTS "revenueRecognitionRun_createdBy_idx" ON "revenueRecognitionRun" ("createdBy");

-- RLS: the policies are rendered from packages/database/src/authz/manifest.ts.

CREATE TABLE IF NOT EXISTS "revenueRecognitionRunLine" (
  "id" TEXT NOT NULL DEFAULT id('rvrl'),
  "companyId" TEXT NOT NULL,
  "runId" TEXT NOT NULL,
  "scheduleId" TEXT NOT NULL,
  "amount" NUMERIC NOT NULL,
  "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
  "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
  "updatedBy" TEXT REFERENCES "user"("id"),
  "updatedAt" TIMESTAMP WITH TIME ZONE,
  CONSTRAINT "revenueRecognitionRunLine_pkey" PRIMARY KEY ("id", "companyId"),
  CONSTRAINT "revenueRecognitionRunLine_run_fkey" FOREIGN KEY ("runId", "companyId") REFERENCES "revenueRecognitionRun"("id", "companyId") ON DELETE CASCADE,
  CONSTRAINT "revenueRecognitionRunLine_schedule_fkey" FOREIGN KEY ("scheduleId", "companyId") REFERENCES "revenueRecognitionSchedule"("id", "companyId") ON DELETE RESTRICT,
  CONSTRAINT "revenueRecognitionRunLine_schedule_key" UNIQUE ("companyId", "scheduleId"),
  CONSTRAINT "revenueRecognitionRunLine_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX IF NOT EXISTS "revenueRecognitionRunLine_companyId_idx" ON "revenueRecognitionRunLine" ("companyId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionRunLine_runId_idx" ON "revenueRecognitionRunLine" ("runId");
CREATE INDEX IF NOT EXISTS "revenueRecognitionRunLine_createdBy_idx" ON "revenueRecognitionRunLine" ("createdBy");

-- RLS: the policies are rendered from packages/database/src/authz/manifest.ts.

NOTIFY pgrst, 'reload schema';