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.

5.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { postingOrThrow } from "@carbon/api/postings.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { getCompanyTimeZone } from "@carbon/database";
import type { KyselyDatabase } from "@carbon/database/client";
import { datetime } from "@carbon/utils";
import { parseDate } from "@internationalized/date";
import type { Kysely } from "kysely";
import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";

/**
 * The last day of the month before the one `today` (`YYYY-MM-DD`) falls in,
 * as `YYYY-MM-DD`. Calendar arithmetic only — never a JS Date — so a leap
 * February and a 30-day month both come out right.
 */
export function priorMonthEnd(today: string): string {
  return parseDate(today).set({ day: 1 }).subtract({ days: 1 }).toString();
}

/**
 * The companies a proposal runs for: only those with an accounting cutover.
 * The synthesizers write rental accruals and contract revenue rows for any
 * company they are pointed at, and a company with no cutover cannot post the
 * run (.ai/specs/implemented/2026-10-08-accounting-cutover.md).
 *
 * One read: `company` joined to its settings. It enumerates `company`, never
 * `companyPlan` — that billing table is empty on every install where nobody
 * completed Stripe checkout (see mrp.ts). Kysely has no row cap, so the list
 * is never truncated.
 */
export function companiesToPropose(db: Kysely<KyselyDatabase>) {
  return db
    .selectFrom("company")
    .innerJoin("companySettings", "companySettings.id", "company.id")
    .select(["company.id", "company.name"])
    .where("companySettings.accountingCutoverDate", "is not", null)
    .orderBy("company.id");
}

export const revenueRecognitionProposalFunction = inngest.createFunction(
  { id: "revenue-recognition-proposal", retries: 2 },
  // Noon UTC on the 1st: every inhabited zone (UTC-11 … UTC+14) is already on
  // the 1st or 2nd, so priorMonthEnd() names the month that just closed. At
  // 06:00 UTC a Pacific-time company would still be on the last day of the
  // prior month and be proposed a run for the month before that.
  { cron: "0 12 1 * *" },
  async ({ step, logger }) => {
    const serviceRole = getCarbonServiceRole();
    const scheduled = await step.run("find-companies", async () => {
      logger.info(
        `Scheduled revenue recognition proposal started: ${datetime.timestamp()}`
      );

      const proposing = await companiesToPropose(getJobDatabaseClient())
        .execute()
        .catch((error) => {
          logger.error("Failed to get companies", { error });
          // Throwing, not returning: a return is a step that succeeds having
          // proposed for nobody, and never spends the configured retries.
          throw error;
        });

      if (proposing.length === 0) {
        logger.warn("No companies to propose revenue recognition runs for");
      }

      return proposing;
    });

    // One step per company: each is its own invocation with its own retries
    // and is memoized on replay, so a slow or failing tenant costs only
    // itself.
    const failed: string[] = [];
    // Two runs per company, each its own step: a revenue recognition run and
    // a lease run (rental agreements and lessee leases).
    const runTypes = [
      { type: "Revenue Recognition" as const, step: "rev-rec" },
      { type: "Lease" as const, step: "lease-run" }
    ];
    for (const company of scheduled) {
      for (const { type, step: stepName } of runTypes) {
        try {
          await step.run(`${stepName}-${company.id}`, async () => {
            // The cron is UTC; the period is the month that just ended on the
            // company's own calendar.
            const tz = await getCompanyTimeZone(serviceRole, company.id);
            const periodEnd = priorMonthEnd(datetime.today(tz).toString());
            const db = getJobDatabaseClient();

            // A posted run for the period does not stop a second proposal:
            // rows can fall due after it posted. Only a Draft of the same
            // type does.
            const existing = await db
              .selectFrom("revenueRecognitionRun")
              .select("id")
              .where("companyId", "=", company.id)
              .where("type", "=", type)
              .where("periodEnd", "=", periodEnd)
              .where("status", "=", "Draft")
              .executeTakeFirst();

            if (existing) {
              logger.info(
                `Skipped ${company.name}: a draft ${type} run for ${periodEnd} already exists (${existing.id})`
              );
              return;
            }

            // Posting stays a human action in the ERP; this only drafts the run.
            const proposal = await postingOrThrow(
              "propose-revenue-recognition-run",
              { db, companyId: company.id, userId: "system" },
              {
                periodEnd,
                type
              }
            );

            logger.info(
              proposal
                ? `Proposed ${proposal.runId} (${proposal.lineCount} lines) for ${company.name}`
                : `Nothing to post in a ${type} run for ${company.name}`
            );
          });
        } catch (error) {
          logger.error("Failed to propose a {type} run for company {company}", {
            type,
            company: company.name,
            companyId: company.id,
            error
          });
          failed.push(company.id);
        }
      }
    }

    return { scheduled: scheduled.length, failed };
  }
);