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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Merge origin/main into naveenkash/receipt-default-quantity-zero
naveenkashe50661b11c56
diff --cc .claude/rules/shipments-receipts-ui-patterns.mdindex beedaecde1,6aa0670d7c..d83dcbf909--- a/.claude/rules/shipments-receipts-ui-patterns.md+++ b/.claude/rules/shipments-receipts-ui-patterns.md@@@ -132,9 -146,8 +150,9 @@@ the service-role client + Kysely `db.tr- **post-receipt** handles `Purchase Order`, `Inbound Transfer`, `Rental Agreement` (returns eachticked unit through `returnRentalUnit` and moves its `fixedAsset.locationId` to the receipt's- location; `post-receipt/rental-agreement.ts`), and `Sales Return Order`+ location; `returnRentalUnit` in `sales.service.ts`), and `Sales Return Order`- (customer RMA re-entry at original outbound cost, entities to On Hold). PO path: inserts `itemLedger`+ (customer RMA re-entry at original outbound cost, entities to On Hold). The PO, transfer and RMA branches skip a+ line received at 0 — it books no `itemLedger`, cost layer or journal line. PO path: inserts `itemLedger`(entry types `Positive/Negative Adjmt.` by sign), GR/IR + inventory `journalLine`s for everycompany (the journal is Provisional before the accounting cutover, Posted after it), advances PO line `quantityReceived`/`receivedComplete` and PO `status`,flips tracked entities to `Available` (**`On Hold` if the item has a Receipt-usage inspectiondiff --cc apps/erp/app/modules/inventory/inventory.service.tsindex 8c53975589,8486d07e08..6b5842a610--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@@ -4774,3 -4671,21019 +4671,21023 @@@ export async function updateWarehouseTr.select("id").single();}+ // ---------------------------------------------------------------------------+ // Shared steps+ // ---------------------------------------------------------------------------++ type RuleLines = Parameters<typeof evaluateLinesForSurface>[0]["lines"];++ type RuleSurface = Parameters<typeof evaluateLinesForSurface>[0]["surface"];++ /** A post a blocking rule refused: what the user must see, or acknowledge. */+ export type Blocked = {+ violations: Violation[];+ ruleNames: Record<string, string>;+ };++ /**+ * Every storage rule the lines break, on each surface in turn. Read as the+ * system: a user with `inventory` rights may not see the items or bins.+ */+ export async function storageRuleViolations(+ ctx: ServiceContext,+ surfaces: RuleSurface[],+ lines: RuleLines+ ): Promise<Blocked> {+ const violations: Violation[] = [];+ const ruleNames: Record<string, string> = {};+ for (const surface of surfaces) {+ const result = await evaluateLinesForSurface({+ client: ctx.asSystem.supabase,+ companyId: ctx.company.id,+ userId: ctx.auditUserId,+ targetType: "item",+ surface,+ lines+ });+ violations.push(...result.violations);+ Object.assign(ruleNames, result.ruleNames);+ }+ return { violations, ruleNames };+ }++ const CATEGORY_BY_STATUS = Object.fromEntries(+ Object.entries(ERROR_STATUS).map(([category, status]) => [status, category])+ ) as Record<number, ErrorCategory>;++ /**+ * A server function's failure as this operation's error, its category from+ * the function's own status. A call that returned no data and no error is+ * `internal`.+ */+ export function serverFnFailure(+ ctx: ServiceContext,+ error: ServerFnError | null,+ message: string+ ): CarbonError {+ return ctx.error(+ (error && CATEGORY_BY_STATUS[error.status]) || "internal",+ message,+ error+ );+ }++ /** The caller's default location, from their user defaults. */+ export async function defaultLocationOf(ctx: ServiceContext) {+ const defaults = await ctx.asCaller.supabase+ .from("userDefaults")+ .select("locationId")+ .eq("userId", ctx.auditUserId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ return defaults.data?.locationId ?? undefined;+ }++ /** Print a document's labels when its location's printer auto-prints. */+ export async function autoPrint(+ ctx: ServiceContext,+ {+ sourceDocument,+ sourceDocumentId,+ locationId,+ context+ }: {+ sourceDocument: "Receipt" | "Shipment";+ sourceDocumentId: string;+ locationId: string | null;+ context: "receiving" | "shipping";+ }+ ) {+ if (!locationId) return;+ try {+ const config = await getCachedPrinterConfig(+ ctx.asSystem.supabase,+ ctx.company.id,+ locationId,+ context+ );+ if (config?.autoPrint ?? true) {+ await trigger("print-job", {+ sourceDocument,+ sourceDocumentId,+ companyId: ctx.company.id,+ userId: ctx.auditUserId,+ locationId+ });+ }+ } catch (error) {+ logger.error("Auto-print failed", { error });+ }+ }++ /** Print a fresh label for each tracked entity a post or pick split. */+ export async function printEntityLabels(+ ctx: ServiceContext,+ entityIds: string[],+ locationId?: string+ ) {+ try {+ for (const entityId of entityIds) {+ await trigger("print-job", {+ sourceDocument: "Entity",+ sourceDocumentId: entityId,+ companyId: ctx.company.id,+ userId: ctx.auditUserId,+ ...(locationId ? { locationId } : {})+ });+ }+ } catch (error) {+ logger.error("Auto-print for split entities failed", { error });+ }+ }++ export function receiptFixedAssetLineChange(+ change: Omit<z.output<typeof receiptFixedAssetLineUpdateValidator>, "id">+ ) {+ switch (change.field) {+ case "received":+ return { received: change.value === "true" };+ case "serialNumber":+ return { serialNumber: change.value || null };+ case "meter":+ return { meter: change.value === "" ? null : Number(change.value) };+ case "notes":+ return { notes: change.value.trim() || null };+ case "outOfService":+ return change.value.trim() === ""+ ? { takeOutOfService: false, outOfServiceReason: null }+ : { takeOutOfService: true, outOfServiceReason: change.value.trim() };+ case "residualDestination":+ return {+ residualDestination: (change.value || null) as+ | "Fleet"+ | "Inventory"+ | null+ };+ }+ }++ /** The receipt line, read as the system: the tracking RPCs key on its ids alone. */+ export async function receiptLineOf(+ ctx: ServiceContext,+ { receiptId, receiptLineId }: { receiptId: string; receiptLineId: string }+ ) {+ const line = await ctx.asSystem.supabase+ .from("receiptLine")+ .select("id, itemId")+ .eq("id", receiptLineId)+ .eq("receiptId", receiptId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (line.error) {+ return ctx.error(+ "internal",+ "Failed to verify the receipt line",+ line.error+ );+ }+ if (!line.data) {+ return ctx.error(+ "notFound",+ "The receipt line could not be found. It may have been deleted, or it belongs to another company."+ );+ }+ return line.data;+ }++ /** A sales-return receipt line, and the receipt's return order. */+ export async function returnReceiptLineOf(+ ctx: ServiceContext,+ { receiptId, receiptLineId }: { receiptId: string; receiptLineId: string }+ ) {+ const client = ctx.asCaller.supabase;+ const [receipt, line] = await Promise.all([+ client+ .from("receipt")+ .select("id, sourceDocument, sourceDocumentId")+ .eq("id", receiptId)+ .eq("companyId", ctx.company.id)+ .maybeSingle(),+ client+ .from("receiptLine")+ .select("id, lineId")+ .eq("id", receiptLineId)+ // Scoped to the receipt too: without it, a line of another receipt of+ // the same return order would tag the entity with a mismatched pair.+ .eq("receiptId", receiptId)+ .eq("companyId", ctx.company.id)+ .maybeSingle()+ ]);+ if (!receipt.data || receipt.data.sourceDocument !== "Sales Return Order") {+ return ctx.error(+ "validation",+ "Return tracking requires a sales-return receipt"+ );+ }+ if (!line.data?.lineId) {+ return ctx.error("validation", "Receipt line not found");+ }+ return {+ returnOrderId: receipt.data.sourceDocumentId,+ returnLineId: line.data.lineId+ };+ }++ export function withoutReceiptTracking(attributes: Record<string, unknown>) {+ const {+ Receipt: _receipt,+ "Receipt Line": _line,+ "Receipt Line Index": _index,+ ...rest+ } = attributes;+ return rest;+ }++ /**+ * Save a sales order shipment's packing slip on the order's opportunity.+ * Best effort: a failure is logged and never stops the post.+ */+ export async function savePackingSlip(+ ctx: ServiceContext,+ { shipmentId, locale }: { shipmentId: string; locale: string }+ ) {+ const companyId = ctx.company.id;+ const serviceRole = ctx.asSystem.supabase;+ try {+ const shipment = await serviceRole+ .from("shipment")+ .select("sourceDocument, sourceDocumentId, shipmentId")+ .eq("id", shipmentId)+ .eq("companyId", companyId)+ .single();+ if (+ shipment.data?.sourceDocument !== "Sales Order" ||+ !shipment.data.sourceDocumentId+ ) {+ return;+ }++ const salesOrder = await serviceRole+ .from("salesOrder")+ .select("opportunityId")+ .eq("id", shipment.data.sourceDocumentId)+ .eq("companyId", companyId)+ .single();+ if (!salesOrder.data?.opportunityId) return;++ const pdf = await renderPackingSlip({+ client: ctx.asCaller.supabase,+ serviceRole,+ companyId,+ shipmentId,+ locale+ });+ if (pdf.headers.get("content-type") !== "application/pdf") return;++ const file = await pdf.arrayBuffer();+ const fileName = stripSpecialCharacters(+ `${shipment.data.shipmentId} - ${datetime.timestamp().slice(0, -5)}.pdf`+ );+ const documentFilePath = `${companyId}/opportunity/${salesOrder.data.opportunityId}/${fileName}`;+ const upload = await storage(serviceRole)+ .company(companyId)+ .upload(documentFilePath, file, {+ cacheControl: `${12 * 60 * 60}`,+ contentType: "application/pdf",+ upsert: true+ });+ if (upload.error) return;++ await upsertDocument(serviceRole, {+ path: documentFilePath,+ name: fileName,+ size: round(file.byteLength / 1024, 0),+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ readGroups: [ctx.auditUserId],+ writeGroups: [ctx.auditUserId],+ createdBy: ctx.auditUserId,+ companyId+ });+ } catch (error) {+ logger.error("Failed to generate packing slip PDF", { error });+ }+ }++ /** A stock transfer line of this company, with its transfer's status. */+ export async function stockTransferLineOf(ctx: ServiceContext, lineId: string) {+ const line = await ctx.asCaller.supabase+ .from("stockTransferLine")+ .select(+ "id, stockTransferId, quantity, pickedQuantity, requiresSerialTracking, requiresBatchTracking, stockTransfer(status)"+ )+ .eq("id", lineId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (line.error) {+ return ctx.error(+ "internal",+ "Failed to load stock transfer line",+ line.error+ );+ }+ if (!line.data) {+ return ctx.error("notFound", "Stock transfer line not found");+ }+ if (line.data.stockTransfer?.status === "Completed") {+ return ctx.error("rule", "Cannot pick from a completed stock transfer.");+ }+ return line.data;+ }++ /** Move a line's stock (or put it back), and label any batch it split. */+ export async function postStockTransferLine(+ ctx: ServiceContext,+ input: {+ type:+ | "inventory"+ | "unpickSerial"+ | "unpickBatch"+ | "unpickInventory"+ | "batch"+ | "serial";+ stockTransferId: string;+ stockTransferLineId: string;+ quantity: number;+ locationId: string;+ trackedEntityId?: string;+ },+ failure: (error: ServerFnError) => string+ ) {+ const moved = await invokePosting(+ ctx,+ "post-stock-transfer",+ // One body for every `type`; the function validates it per type.+ input as z.input<typeof postStockTransferInput>,+ postStockTransfer+ );+ if (moved.error)+ return serverFnFailure(ctx, moved.error, failure(moved.error));++ // The split child that arrives at the destination gets a fresh label; the+ // shelf parent whose quantity changed is reprinted.+ const splitEntityId = moved.data?.splitEntityId;+ if (splitEntityId) {+ await printEntityLabels(+ ctx,+ [+ splitEntityId,+ ...(input.trackedEntityId ? [input.trackedEntityId] : [])+ ],+ input.locationId || undefined+ );+ }+ return {+ stockTransferId: input.stockTransferId,+ stockTransferLineId: input.stockTransferLineId,+ quantity: input.quantity+ };+ }++ // ---------------------------------------------------------------------------+ // Warehouse transfers+ // ---------------------------------------------------------------------------++ export const WAREHOUSE_TRANSFER_NOT_FOUND =+ "The warehouse transfer could not be found";++ const WAREHOUSE_TRANSFER_LOCKED =+ "Cannot modify a locked warehouse transfer. Reopen it first.";++ /** A Draft warehouse transfer of this company: any other is locked. */+ export async function unlockedWarehouseTransfer(+ ctx: ServiceContext,+ transferId: string+ ) {+ const transfer = await ctx.asCaller.supabase+ .from("warehouseTransfer")+ .select("id, status, fromLocationId, toLocationId")+ .eq("id", transferId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (transfer.error) {+ return ctx.error(+ "internal",+ "Failed to load warehouse transfer",+ transfer.error+ );+ }+ if (!transfer.data) {+ return ctx.error("notFound", WAREHOUSE_TRANSFER_NOT_FOUND);+ }+ if (isWarehouseTransferLocked(transfer.data.status)) {+ return ctx.error("rule", WAREHOUSE_TRANSFER_LOCKED);+ }+ return transfer.data;+ }++ /**+ * A serial number is one unit: an adjustment of a serial item moves, sets or+ * scraps at most one. Read from the item, not from what the caller says it is.+ */+ export async function serialQuantityRefusal(+ ctx: ServiceContext,+ itemId: string,+ quantity: number+ ) {+ const item = await ctx.asCaller.supabase+ .from("item")+ .select("itemTrackingType")+ .eq("id", itemId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (item.error)+ return ctx.error("internal", "Failed to load item", item.error);+ if (!item.data) return ctx.error("notFound", "Item not found");+ if (item.data.itemTrackingType === "Serial" && Math.abs(quantity) > 1) {+ return ctx.error(+ "validation",+ "Serial items can only have a quantity of 1"+ );+ }+ return null;+ }++ export const STOCK_TRANSFER_LOCKED =+ "Cannot modify a locked stock transfer. Reopen it first.";++ /** A Draft stock transfer of this company: any other is locked. */+ export async function unlockedStockTransfer(+ ctx: ServiceContext,+ stockTransferId: string+ ) {+ const transfer = await ctx.asCaller.supabase+ .from("stockTransfer")+ .select("id, status")+ .eq("id", stockTransferId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (transfer.error) {+ return ctx.error(+ "internal",+ "Failed to load stock transfer",+ transfer.error+ );+ }+ if (!transfer.data) {+ return ctx.error("notFound", "The stock transfer could not be found");+ }+ if (isStockTransferLocked(transfer.data.status)) {+ return ctx.error("rule", STOCK_TRANSFER_LOCKED);+ }+ return transfer.data;+ }++ /** The line, when it is on this transfer. */+ export async function warehouseTransferLineOf(+ ctx: ServiceContext,+ { transferId, id }: { transferId: string; id: string }+ ) {+ const line = await ctx.asCaller.supabase+ .from("warehouseTransferLine")+ .select("id")+ .eq("id", id)+ .eq("transferId", transferId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (line.error) {+ return ctx.error(+ "internal",+ "Failed to load warehouse transfer line",+ line.error+ );+ }+ if (!line.data) {+ return ctx.error(+ "notFound",+ "The warehouse transfer line could not be found"+ );+ }+ return line.data;+ }++ /**+ * A pick's failure. A refusal written for the person picking (the building+ * blocks' own strings, and `post-picking`'s 4xx guards such as an over-pick)+ * keeps its message; anything else — a database error, a 5xx — is a failure+ * whose message is not theirs to read, logged as the cause.+ */+ export function pickRefusal(ctx: ServiceContext, error: unknown) {+ if (typeof error === "string") return ctx.error("rule", error);+ if (error instanceof ServerFnError && error.status < 500) {+ return ctx.error(+ CATEGORY_BY_STATUS[error.status] ?? "rule",+ error.message,+ error+ );+ }+ return ctx.error("internal", "Failed to pick line", error);+ }+ export type LineageDirection = "up" | "down" | "both";++ export type LineagePayload = {+ entities: TrackedEntity[];+ inputs: ActivityInput[];+ outputs: ActivityOutput[];+ activities: Activity[];+ stepRecords?: StepRecord[];+ containments?: IssueContainment[];+ };++ // The graph collapses identical serial siblings into group nodes, so a large+ // serial fan no longer costs a node each — the ceiling can afford whole jobs.+ // The BFS must stay COMPLETE up to it: cluster signatures are computed from+ // the full edge set, and a truncated frontier would split a group in two.+ const MAX_ENTITIES = 500;++ type LineageState = {+ companyId: string;+ entities: Map<string, TrackedEntity>;+ activities: Map<string, Activity>;+ inputs: Map<string, ActivityInput>;+ outputs: Map<string, ActivityOutput>;+ visited: Set<string>;+ };++ function newLineageState(companyId: string): LineageState {+ return {+ companyId,+ entities: new Map(),+ activities: new Map(),+ inputs: new Map(),+ outputs: new Map(),+ visited: new Set()+ };+ }++ async function expandActivitySiblings(+ client: SupabaseClient<Database>,+ state: LineageState,+ activityIds: string[]+ ): Promise<void> {+ const { companyId, entities, activities, inputs, outputs } = state;+ const newActivityIds = activityIds.filter((id) => !activities.has(id));+ if (newActivityIds.length > 0) {+ const fetched = await client+ .from("trackedActivity")+ .select("*")+ .in("id", newActivityIds)+ .eq("companyId", companyId);+ for (const row of fetched.data ?? []) {+ activities.set(row.id, row as unknown as Activity);+ }+ }++ // Pull sibling inputs/outputs for every activity so by-products (e.g. SCRAP)+ // appear even when not on the direct upstream/downstream path.+ const [siblingInputs, siblingOutputs] = await Promise.all([+ client+ .from("trackedActivityInput")+ .select("*")+ .in("trackedActivityId", activityIds)+ .eq("companyId", companyId),+ client+ .from("trackedActivityOutput")+ .select("*")+ .in("trackedActivityId", activityIds)+ .eq("companyId", companyId)+ ]);++ // These rows are the AUTHORITATIVE edge quantities — how much actually flowed+ // through this activity. Always overwrite: the BFS seeds edges from the+ // traversal RPCs, whose `quantity` column is the neighbour ENTITY's current+ // quantity (`te."quantity"`), not the edge's. Left as-is, a lot that was later+ // drawn down paints its post-hoc quantity onto a historical edge (a 6-unit+ // split reading "4" after 2 were consumed).+ const siblingEntityIds = new Set<string>();+ for (const row of siblingInputs.data ?? []) {+ const key = `${row.trackedActivityId}:${row.trackedEntityId}`;+ inputs.set(key, {+ trackedActivityId: row.trackedActivityId,+ trackedEntityId: row.trackedEntityId,+ quantity: row.quantity+ });+ if (!entities.has(row.trackedEntityId)) {+ siblingEntityIds.add(row.trackedEntityId);+ }+ }+ for (const row of siblingOutputs.data ?? []) {+ const key = `${row.trackedActivityId}:${row.trackedEntityId}`;+ outputs.set(key, {+ trackedActivityId: row.trackedActivityId,+ trackedEntityId: row.trackedEntityId,+ quantity: row.quantity+ });+ if (!entities.has(row.trackedEntityId)) {+ siblingEntityIds.add(row.trackedEntityId);+ }+ }++ if (siblingEntityIds.size > 0) {+ const remainingCapacity = MAX_ENTITIES - entities.size;+ const idsToFetch = Array.from(siblingEntityIds).slice(0, remainingCapacity);+ if (idsToFetch.length > 0) {+ const fetched = await client+ .from("trackedEntity")+ .select("*")+ .in("id", idsToFetch);+ for (const row of fetched.data ?? []) {+ entities.set(row.id, row as TrackedEntity);+ }+ }+ }+ }++ /**+ * Surface "event" activities (e.g. Pick, Transfer) that reference entities+ * already in the graph. The genealogy BFS only follows input→output+ * transformations (consume/produce/split), so input-only or output-only events+ * — a pick relocating a lot, say — would otherwise be invisible. These render as+ * activity nodes attached to their entity (no new genealogy edges).+ */+ async function expandEntityActivities(+ client: SupabaseClient<Database>,+ state: LineageState+ ): Promise<void> {+ const entityIds = Array.from(state.entities.keys());+ if (entityIds.length === 0) return;++ const [ins, outs] = await Promise.all([+ client+ .from("trackedActivityInput")+ .select("trackedActivityId")+ .in("trackedEntityId", entityIds)+ .eq("companyId", state.companyId),+ client+ .from("trackedActivityOutput")+ .select("trackedActivityId")+ .in("trackedEntityId", entityIds)+ .eq("companyId", state.companyId)+ ]);++ const activityIds = new Set<string>();+ for (const row of ins.data ?? []) {+ if (!state.activities.has(row.trackedActivityId))+ activityIds.add(row.trackedActivityId);+ }+ for (const row of outs.data ?? []) {+ if (!state.activities.has(row.trackedActivityId))+ activityIds.add(row.trackedActivityId);+ }++ if (activityIds.size > 0) {+ await expandActivitySiblings(client, state, Array.from(activityIds));+ }+ }++ async function runLineageBfs(+ client: SupabaseClient<Database>,+ state: LineageState,+ initialFrontier: string[],+ direction: LineageDirection,+ safeDepth: number+ ): Promise<void> {+ const { companyId, entities, inputs, outputs, visited } = state;+ let frontier = initialFrontier.filter((id) => {+ if (visited.has(id)) return true;+ visited.add(id);+ return true;+ });++ for (let hop = 0; hop < safeDepth; hop++) {+ if (frontier.length === 0) break;+ if (entities.size >= MAX_ENTITIES) break;++ type BatchRow = {+ sourceEntityId: string;+ trackedActivityId: string;+ id: string;+ quantity: number;+ };++ const calls: Promise<void>[] = [];+ let descendantsBatch: BatchRow[] = [];+ let ancestorsBatch: BatchRow[] = [];++ if (direction === "down" || direction === "both") {+ calls.push(+ (async () => {+ const res = await client.rpc(+ "get_direct_descendants_of_tracked_entities_strict",+ { p_tracked_entity_ids: frontier, p_company_id: companyId }+ );+ descendantsBatch = (res.data ?? []) as BatchRow[];+ })()+ );+ }+ if (direction === "up" || direction === "both") {+ calls.push(+ (async () => {+ const res = await client.rpc(+ "get_direct_ancestors_of_tracked_entities_strict",+ { p_tracked_entity_ids: frontier, p_company_id: companyId }+ );+ ancestorsBatch = (res.data ?? []) as BatchRow[];+ })()+ );+ }++ await Promise.all(calls);++ const nextFrontier = new Set<string>();+ const newEntityIds = new Set<string>();+ const activityIds = new Set<string>();++ for (let i = 0; i < descendantsBatch.length; i++) {+ const row = descendantsBatch[i];+ if (!row?.id) continue;+ activityIds.add(row.trackedActivityId);+ const outputKey = `${row.trackedActivityId}:${row.sourceEntityId}`;+ if (!outputs.has(outputKey)) {+ outputs.set(outputKey, {+ trackedActivityId: row.trackedActivityId,+ trackedEntityId: row.sourceEntityId,+ quantity: row.quantity+ });+ }+ if (!visited.has(row.id)) {+ visited.add(row.id);+ newEntityIds.add(row.id);+ nextFrontier.add(row.id);+ }+ const inputKey = `${row.trackedActivityId}:${row.id}`;+ if (!inputs.has(inputKey)) {+ inputs.set(inputKey, {+ trackedActivityId: row.trackedActivityId,+ trackedEntityId: row.id,+ quantity: row.quantity+ });+ }+ }++ for (let i = 0; i < ancestorsBatch.length; i++) {+ const row = ancestorsBatch[i];+ if (!row?.id) continue;+ activityIds.add(row.trackedActivityId);+ const inputKey = `${row.trackedActivityId}:${row.sourceEntityId}`;+ if (!inputs.has(inputKey)) {+ inputs.set(inputKey, {+ trackedActivityId: row.trackedActivityId,+ trackedEntityId: row.sourceEntityId,+ quantity: row.quantity+ });+ }+ if (!visited.has(row.id)) {+ visited.add(row.id);+ newEntityIds.add(row.id);+ nextFrontier.add(row.id);+ }+ const outputKey = `${row.trackedActivityId}:${row.id}`;+ if (!outputs.has(outputKey)) {+ outputs.set(outputKey, {+ trackedActivityId: row.trackedActivityId,+ trackedEntityId: row.id,+ quantity: row.quantity+ });+ }+ }++ if (newEntityIds.size > 0) {+ const remainingCapacity = MAX_ENTITIES - entities.size;+ const idsToFetch = Array.from(newEntityIds).slice(0, remainingCapacity);+ const fetched = await client+ .from("trackedEntity")+ .select("*")+ .in("id", idsToFetch)+ .eq("companyId", companyId);+ for (const row of fetched.data ?? []) {+ entities.set(row.id, row as TrackedEntity);+ }+ }++ if (activityIds.size > 0) {+ await expandActivitySiblings(client, state, Array.from(activityIds));+ }++ frontier = Array.from(nextFrontier);+ }+ }++ export async function fetchLineageSubgraph(+ client: SupabaseClient<Database>,+ rootEntityId: string,+ companyId: string,+ depth: number,+ direction: LineageDirection = "both"+ ): Promise<LineagePayload> {+ const safeDepth = clampDepth(depth);++ const rootEntity = await client+ .from("trackedEntity")+ .select("*")+ .eq("id", rootEntityId)+ .eq("companyId", companyId)+ .maybeSingle();++ const state = newLineageState(companyId);+ if (rootEntity.data)+ state.entities.set(rootEntity.data.id, rootEntity.data as TrackedEntity);++ await runLineageBfs(client, state, [rootEntityId], direction, safeDepth);++ // Attach event activities (Pick/Transfer/etc.) for the entities in the graph+ // so location moves like picking show up, not just genealogy transformations.+ await expandEntityActivities(client, state);++ return {+ entities: Array.from(state.entities.values()),+ inputs: Array.from(state.inputs.values()),+ outputs: Array.from(state.outputs.values()),+ activities: Array.from(state.activities.values())+ };+ }++ export async function fetchJobStepRecords(+ client: SupabaseClient<Database>,+ jobId: string,+ companyId: string+ ): Promise<StepRecord[]> {+ const res = await client.rpc("get_job_operation_step_records", {+ p_job_id: jobId,+ p_company_id: companyId+ });+ if (!res.data) return [];+ return (res.data as any[]).map((r) => ({+ id: r.id,+ jobOperationStepId: r.jobOperationStepId,+ index: r.index,+ type: r.type,+ name: r.name,+ value: r.value,+ numericValue: r.numericValue,+ booleanValue: r.booleanValue,+ userValue: r.userValue,+ unitOfMeasureCode: r.unitOfMeasureCode,+ minValue: r.minValue,+ maxValue: r.maxValue,+ operationId: r.operationId,+ operationDescription: r.operationDescription,+ itemId: r.itemId,+ itemReadableId: r.itemReadableId,+ createdAt: r.createdAt,+ createdBy: r.createdBy+ }));+ }++ export async function fetchContainmentsForEntities(+ client: SupabaseClient<Database>,+ entityIds: string[],+ companyId: string+ ): Promise<IssueContainment[]> {+ if (entityIds.length === 0) return [];++ // Single round-trip: PostgREST embed pulls the linked issue inline and+ // filters server-side to only Contained/Uncontained statuses.+ const res = await client+ .from("nonConformanceTrackedEntity")+ .select(+ `trackedEntityId,+ nonConformanceId,+ issue:issues!inner(id, status, priority, containmentStatus)`+ )+ .in("trackedEntityId", entityIds)+ .eq("companyId", companyId)+ .in("issue.containmentStatus", ["Contained", "Uncontained"]);++ const containments: IssueContainment[] = [];+ for (const row of res.data ?? []) {+ const issue = row.issue as {+ id: string | null;+ status: string | null;+ priority: string | null;+ containmentStatus: string | null;+ } | null;+ if (!issue) continue;+ const status = issue.containmentStatus;+ if (status !== "Contained" && status !== "Uncontained") continue;+ containments.push({+ id: issue.id ?? row.nonConformanceId,+ readableId: row.nonConformanceId,+ containmentStatus: status as IssueContainmentStatus,+ status: issue.status ?? "",+ priority: issue.priority ?? null,+ trackedEntityId: row.trackedEntityId+ });+ }+ return containments;+ }++ export async function fetchJobScopedLineage(+ client: SupabaseClient<Database>,+ jobId: string,+ companyId: string,+ depth: number+ ): Promise<LineagePayload> {+ const safeDepth = clampDepth(depth);++ const [seedEntitiesRes, seedActivitiesRes] = await Promise.all([+ client+ .from("trackedEntity")+ .select("*")+ .eq("attributes->>Job", jobId)+ .eq("companyId", companyId),+ client+ .from("trackedActivity")+ .select("*")+ .eq("attributes->>Job", jobId)+ .eq("companyId", companyId)+ ]);++ const state = newLineageState(companyId);+ for (const row of (seedEntitiesRes.data ?? []) as TrackedEntity[]) {+ state.entities.set(row.id, row);+ }+ for (const row of (seedActivitiesRes.data ?? []) as unknown as Activity[]) {+ state.activities.set(row.id, row);+ }++ if (state.activities.size > 0) {+ await expandActivitySiblings(+ client,+ state,+ Array.from(state.activities.keys())+ );+ }++ if (state.entities.size > 0) {+ await runLineageBfs(+ client,+ state,+ Array.from(state.entities.keys()),+ "both",+ safeDepth+ );+ }++ const containments = await fetchContainmentsForEntities(+ client,+ Array.from(state.entities.keys()),+ companyId+ );++ return {+ entities: Array.from(state.entities.values()),+ inputs: Array.from(state.inputs.values()),+ outputs: Array.from(state.outputs.values()),+ activities: Array.from(state.activities.values()),+ containments+ };+ }++ export function toGraphData(payload: LineagePayload): GraphData {+ const nodes = [+ ...payload.entities.map((entity) => ({+ id: entity.id,+ type: "entity" as const,+ data: entity,+ parentId: null+ })),+ ...payload.activities.map((activity) => ({+ id: activity.id,+ type: "activity" as const,+ data: activity,+ parentId: null+ }))+ ];++ // Historical split survivors are recorded as both input and output of their+ // own Split activity. Drop the output half of that self-loop so the graph+ // doesn't render the survivor as produced by its own split; the input edge+ // stays (it carries the drawn quantity).+ const splitActivityIds = new Set(+ payload.activities.filter((a) => a?.type === "Split").map((a) => a.id)+ );+ const inputPairs = new Set(+ pluckUnique(+ payload.inputs.filter((input) =>+ splitActivityIds.has(input.trackedActivityId)+ ),+ (input) => `${input.trackedActivityId}::${input.trackedEntityId}`+ )+ );++ const links = [+ ...payload.inputs.map((input) => ({+ source: input.trackedEntityId,+ target: input.trackedActivityId,+ type: "input" as const,+ quantity: input.quantity+ })),+ ...payload.outputs+ .filter(+ (output) =>+ !inputPairs.has(+ `${output.trackedActivityId}::${output.trackedEntityId}`+ )+ )+ .map((output) => ({+ source: output.trackedActivityId,+ target: output.trackedEntityId,+ type: "output" as const,+ quantity: output.quantity+ }))+ ];++ return { nodes, links };+ }++ /**+ * Resolve the storage-unit ids that movement activities carry in their+ * attributes ("From Shelf" / "To Shelf") into names, written back as+ * "From Storage Unit Name" / "To Storage Unit Name".+ *+ * The graph renders a lot as a chain of states; a movement produces two states+ * with the SAME quantity, so the bin is the only thing that distinguishes+ * them. Without this they render identically and a Pick looks like a no-op.+ * Enriching here keeps the ids server-side and needs no extra plumbing — the+ * activities already flow through the payload to the layout worker.+ */+ export async function enrichActivityBinNames(+ client: SupabaseClient<Database>,+ payload: LineagePayload,+ companyId: string+ ): Promise<LineagePayload> {+ const binIds = new Set<string>();+ for (const activity of payload.activities) {+ const attrs = activity.attributes as Record<string, unknown> | null;+ for (const key of ["From Shelf", "To Shelf"]) {+ const id = attrs?.[key];+ if (typeof id === "string" && id) binIds.add(id);+ }+ }+ if (binIds.size === 0) return payload;++ const storageUnits = await client+ .from("storageUnit")+ .select("id, name")+ .in("id", Array.from(binIds))+ .eq("companyId", companyId);+ if (storageUnits.error || !storageUnits.data?.length) return payload;++ const nameById = indexByMapped(+ storageUnits.data,+ (row) => row.id,+ (row) => row.name+ );++ return {+ ...payload,+ activities: payload.activities.map((activity) => {+ const attrs = activity.attributes as Record<string, unknown> | null;+ const from = attrs?.["From Shelf"];+ const to = attrs?.["To Shelf"];+ const fromName =+ typeof from === "string" ? nameById.get(from) : undefined;+ const toName = typeof to === "string" ? nameById.get(to) : undefined;+ if (!fromName && !toName) return activity;+ return {+ ...activity,+ attributes: {+ ...(attrs ?? {}),+ ...(fromName ? { "From Storage Unit Name": fromName } : {}),+ ...(toName ? { "To Storage Unit Name": toName } : {})+ }+ };+ })+ };+ }+ export const previewSerialUnitCostsInput = z.object({+ itemId: z.string().min(1),+ // Only the units on hand at this location; every location when absent.+ locationId: z.string().optional().nullable()+ });++ export type SerialUnitCosts = {+ costs: Record<string, number>;+ // Only a FIFO / LIFO item's unit can be recosted on its own.+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"] | null;+ };++ export const previewSerialUnitCostsPermission = {+ view: "accounting"+ } satisfies PermissionRule<z.output<typeof previewSerialUnitCostsInput>>;++ export async function previewSerialUnitCosts(+ ctx: ServiceContext,+ raw: z.input<typeof previewSerialUnitCostsInput>+ ) {+ const { itemId, locationId } = previewSerialUnitCostsInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const item = await db+ .selectFrom("item")+ .select("itemTrackingType")+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!item) throw new NotFoundError("Item not found");+ if (item.itemTrackingType !== "Serial") {+ return { costs: {}, costingMethod: null };+ }++ let onHandQuery = db+ .selectFrom("itemLedger")+ .select("trackedEntityId")+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .where("trackedEntityId", "is not", null)+ .groupBy("trackedEntityId")+ .having(sql<number>`SUM("quantity")`, ">", 0);+ if (locationId)+ onHandQuery = onHandQuery.where("locationId", "=", locationId);++ const [onHand, itemCost] = await inOrder([+ () => onHandQuery.execute(),+ () =>+ db+ .selectFrom("itemCost")+ .select(["costingMethod", "unitCost", "standardCost"])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ ]);+ if (!itemCost) throw new NotFoundError("Item cost not found");+ const units = onHand.flatMap((row) =>+ row.trackedEntityId ? [row.trackedEntityId] : []+ );+ if (units.length === 0) {+ return { costs: {}, costingMethod: itemCost.costingMethod };+ }++ const isLayered =+ itemCost.costingMethod === "FIFO" || itemCost.costingMethod === "LIFO";+ const direction = itemCost.costingMethod === "LIFO" ? "desc" : "asc";+ // The layers calculateCOGS would consume from, in its order.+ const layers = isLayered+ ? await db+ .selectFrom("costLedger")+ .select([+ "id",+ "trackedEntityId",+ "quantity",+ "cost",+ "remainingQuantity"+ ])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .where("remainingQuantity", ">", 0)+ .where("adjustment", "=", false)+ .where("appliesToCostLedgerId", "is", null)+ .where((eb) =>+ eb.or([+ eb("documentType", "is", null),+ eb("documentType", "!=", "Purchase Order")+ ])+ )+ .orderBy("postingDate", direction)+ .orderBy("createdAt", direction)+ .execute()+ : [];++ const childrenByLayer = new Map<string, UnitCostChild[]>();+ if (layers.length > 0) {+ const children = await db+ .selectFrom("costLedger")+ .select([+ "appliesToCostLedgerId",+ "quantity",+ "cost",+ "remainingQuantity"+ ])+ .where(+ "appliesToCostLedgerId",+ "in",+ layers.map((layer) => layer.id)+ )+ .where("companyId", "=", companyId)+ .where("remainingQuantity", ">", 0)+ .orderBy("createdAt", "asc")+ .execute();+ for (const child of children) {+ if (!child.appliesToCostLedgerId) continue;+ const list = childrenByLayer.get(child.appliesToCostLedgerId) ?? [];+ list.push({+ quantity: Number(child.quantity),+ cost: Number(child.cost),+ remainingQuantity: Number(child.remainingQuantity)+ });+ childrenByLayer.set(child.appliesToCostLedgerId, list);+ }+ }++ const basis = {+ costingMethod: itemCost.costingMethod,+ unitCost: itemCost.unitCost == null ? null : Number(itemCost.unitCost),+ standardCost:+ itemCost.standardCost == null ? null : Number(itemCost.standardCost)+ };+ const valuedLayers = layers.map((layer) => ({+ id: layer.id,+ trackedEntityId: layer.trackedEntityId,+ quantity: Number(layer.quantity),+ cost: Number(layer.cost),+ remainingQuantity: Number(layer.remainingQuantity)+ }));++ const costs: Record<string, number> = {};+ for (const trackedEntityId of units) {+ costs[trackedEntityId] = round(+ serialUnitCost({+ itemCost: basis,+ layers: valuedLayers,+ childrenByLayer,+ trackedEntityId+ })+ );+ }+ return { costs, costingMethod: itemCost.costingMethod };+ }+ export const recostSerialUnitInput = z.object({+ trackedEntityId: z.string().min(1),+ // The unit's new carrying cost, in base currency.+ unitCost: z.number().min(0),+ offsetAccountId: z.string().optional().nullable(),+ postingDate: z+ .string()+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Expected a YYYY-MM-DD date")+ });++ export type RecostResult = {+ previousCost: number;+ unitCost: number;+ journalId: string | null;+ };++ export const recostSerialUnitPermission = {+ update: "accounting"+ } satisfies PermissionRule<z.output<typeof recostSerialUnitInput>>;++ export async function recostSerialUnit(+ ctx: ServiceContext,+ raw: z.input<typeof recostSerialUnitInput>+ ) {+ const input = recostSerialUnitInput.parse(raw);+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const unitCost = round(input.unitCost);++ return db.transaction().execute(async (trx): Promise<RecostResult> => {+ // Lock the unit before reading where it is: a second recost, or an+ // issue, pick, transfer or adjustment of it (they lock it too), waits,+ // so the on-hand check below still holds when calculateCOGS relieves+ // its layer (which locks the layers it reads).+ const entity = await trx+ .selectFrom("trackedEntity")+ .select(["id", "itemId", "readableId", "status"])+ .where("id", "=", input.trackedEntityId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!entity?.itemId) throw new NotFoundError("Tracked entity not found");+ const itemId = entity.itemId;+ const serial = entity.readableId ?? entity.id;++ const [item, itemCost] = await inOrder([+ () =>+ trx+ .selectFrom("item")+ .select(["readableId", "itemTrackingType", "replenishmentSystem"])+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst(),+ () =>+ trx+ .selectFrom("itemCost")+ .select(["costingMethod", "itemPostingGroupId"])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ ]);+ if (!item || !itemCost) throw new NotFoundError("Item not found");+ if (item.itemTrackingType !== "Serial") {+ throw new InvalidInputError("Only a serialized unit can be recosted");+ }+ if (+ itemCost.costingMethod !== "FIFO" &&+ itemCost.costingMethod !== "LIFO"+ ) {+ throw new InvalidInputError(+ `${item.readableId} uses ${itemCost.costingMethod} costing, so every unit carries the item's cost; one unit cannot have its own`+ );+ }++ // Where the unit is: exactly one on hand, at one location.+ const stock = await trx+ .selectFrom("itemLedger")+ .select([+ "locationId",+ (eb) => eb.fn.sum<number>("quantity").as("onHand")+ ])+ .where("trackedEntityId", "=", entity.id)+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .groupBy("locationId")+ .having(sql<number>`SUM("quantity")`, ">", 0)+ .execute();+ const onHand = stock.reduce((sum, row) => sum + Number(row.onHand), 0);+ if (round(onHand) !== 1 || stock.length !== 1) {+ throw new InvalidInputError(+ `${serial} must have exactly one unit on hand to be recosted`+ );+ }+ const locationId = stock[0]?.locationId ?? null;++ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);+ const accounting = await loadAccounting(+ trx,+ companyId,+ input,+ postingStatus+ );++ // Relieve what the unit carries today, exactly as a shipment would.+ const relieved = await calculateCOGS(trx, {+ itemId,+ quantity: 1,+ companyId,+ trackedEntityIds: [entity.id]+ });+ const previousCost = round(relieved.totalCost);+ const delta = round(unitCost - previousCost);+ if (delta === 0) {+ throw new InvalidInputError(`${serial} is already carried at that cost`);+ }++ const ledger = {+ documentType: null,+ documentId: entity.id,+ itemId,+ postingDate: input.postingDate,+ trackedEntityId: entity.id,+ companyId+ };+ await trx+ .insertInto("costLedger")+ .values([+ {+ ...buildCostLedgerRow({+ ...ledger,+ entryType: "Negative Adjmt.",+ quantity: -1,+ cost: -previousCost+ }),+ costLedgerType: "Revaluation"+ },+ {+ // The unit's own layer: it is relieved first when it leaves.+ ...buildCostLedgerRow({+ ...ledger,+ entryType: "Positive Adjmt.",+ quantity: 1,+ cost: unitCost+ }),+ costLedgerType: "Revaluation"+ }+ ])+ .execute();++ const inventoryAccount = resolveInventoryAccount(+ item.replenishmentSystem,+ accounting.accountDefaults+ );+ const journalId = await createAdjustmentJournal(trx, {+ companyId,+ accountingPeriodId: accounting.accountingPeriodId,+ status: postingStatus,+ description: `Recost ${item.readableId} ${serial}`,+ postingDate: input.postingDate,+ userId,+ sourceType: "Inventory Adjustment"+ });+ const journalLineReference = nanoid();+ const lines = await trx+ .insertInto("journalLine")+ .values(+ buildOffsetLines({+ amount: delta,+ accountId: inventoryAccount.account,+ description: inventoryAccount.description,+ offsetAccountId: accounting.offsetAccount.id,+ offsetDescription: "Inventory Recost",+ offsetAccountType: accounting.offsetAccount.type,+ label: "Inventory recost journal"+ }).map((line) => ({+ journalId,+ accountId: line.accountId,+ description: line.description,+ amount: line.amount,+ quantity: 1,+ documentType: "Inventory Adjustment" as const,+ documentId: entity.id,+ journalLineReference,+ companyId+ }))+ )+ .returning(["id"])+ .execute();+ const dimensions = buildJournalLineDimensions({+ journalLineIds: lines.map((line) => line.id),+ dimensions: accounting.dimensions,+ itemId,+ itemPostingGroupId: itemCost.itemPostingGroupId,+ locationId,+ companyId+ });+ if (dimensions.length > 0) {+ await trx.insertInto("journalLineDimension").values(dimensions).execute();+ }++ return { previousCost, unitCost, journalId };+ });+ }++ // Everything the journal needs, read on the recost's transaction.+ async function loadAccounting(+ db: Kysely<DB>,+ companyId: string,+ input: z.output<typeof recostSerialUnitInput>,+ postingStatus: AutomaticJournalStatus+ ) {+ const [defaults, offsetAccount, company] = await inOrder([+ () => getDefaultPostingGroup(db, companyId),+ () => getOffsetAccount(db, companyId, input.offsetAccountId),+ () =>+ db+ .selectFrom("company")+ .select("companyGroupId")+ .where("id", "=", companyId)+ .executeTakeFirst()+ ]);+ if (defaults.error || !defaults.data) {+ throw new Error("Error getting account defaults");+ }+ if (!company) throw new Error("Failed to fetch company");+ // Fail closed: journal lines must not silently lose dimension tags.+ const dimensionRows = await db+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("companyGroupId", "=", company.companyGroupId)+ .where("active", "=", true)+ .where("entityType", "in", ["Item", "ItemPostingGroup", "Location"])+ .execute();+ const dimensions: Record<string, string> = {};+ for (const row of dimensionRows) {+ if (row.entityType) dimensions[row.entityType] = row.id;+ }+ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getAccountingPeriodForDate(companyId, db, input.postingDate)+ : null;+ return {+ accountingPeriodId,+ accountDefaults: {+ rawMaterialsAccount: defaults.data.rawMaterialsAccount,+ finishedGoodsAccount: defaults.data.finishedGoodsAccount+ },+ offsetAccount,+ dimensions+ };+ }+ // Pure decision for how a counted tracked entity's quantity and status settle.+ // A count books its ledger delta from the SNAPSHOT taken when the count was+ // generated; the entity's live quantity may have moved since. Applying the same+ // delta to the live quantity keeps entity and ledger in step — but if that lands+ // below zero the two have genuinely diverged, so we refuse (recount) rather than+ // clamp, which would desync the entity from the already-booked ledger delta.++ export function resolveCountedEntity<S extends string>(input: {+ currentQuantity: number;+ delta: number;+ currentStatus: S;+ }): { quantity: number; status: S | "Consumed" } {+ return settleQuantity({+ quantity: input.currentQuantity + input.delta,+ status: input.currentStatus,+ refusal:+ "Stock moved since the count was taken; recount this line before posting"+ });+ }++ // Pure planning core for posting an inventory count, extracted so the delta math+ // can be unit-tested without a database.+ //+ // Reconciliation model: post the variance the counter reviewed against the+ // FROZEN snapshot — `delta = counted - systemQuantity` — NOT against live on-hand.+ // This preserves any stock movements that posted between the snapshot and the+ // post (a receipt/shipment isn't clobbered; the count's correction is applied on+ // top of it). A line whose delta is 0 is still returned; the caller skips writing+ // it.++ export type PlannableLine = {+ id: string;+ itemId: string;+ systemQuantity: number | string | null;+ // Callers pass only counted lines; null is tolerated for the row type and+ // coerces to 0 (delta = −systemQuantity), never actually reached.+ countedQuantity: number | string | null;+ };++ export type PlanResult<L extends PlannableLine> = {+ planned: { line: L; delta: number }[];+ };++ export function planInventoryCountPost<L extends PlannableLine>(+ lines: L[]+ ): PlanResult<L> {+ const planned = lines.map((line) => ({+ line,+ delta: Number(line.countedQuantity) - Number(line.systemQuantity)+ }));+ return { planned };+ }+ // Base for post-blocking validation errors. Carries the offending line ids so+ // the response can hand them to the UI to highlight the rows.+ // A 400 whose `body.invalidLineIds` the caller reads to highlight the rows.+ class InvalidLinesError extends InvalidInputError {+ constructor(message: string, lineIds: string[]) {+ super(message, { invalidLineIds: lineIds });+ this.name = "InvalidLinesError";+ }+ }++ // Thrown when a serial-tracked line is counted as anything other than 0 or 1+ // (a serial entity is a single unique unit).+ class SerialQuantityError extends InvalidLinesError {+ constructor(lineIds: string[]) {+ super(+ `${lineIds.length} serial line(s) must be counted as 0 or 1 — a serial number is a single unit.`,+ lineIds+ );+ this.name = "SerialQuantityError";+ }+ }++ // Inventory Count posting uses snapshot-delta reconciliation: for each counted+ // line we post a single Positive/Negative adjustment for the variance the counter+ // reviewed — `counted - systemQuantity` (the FROZEN snapshot on the line), NOT+ // `counted - live on-hand`. This preserves any stock movements that posted between+ // the snapshot and the post (a receipt/shipment isn't clobbered; the correction is+ // applied on top of it). Each variance books through the shared posting core:+ // item ledger + cost layers + a GL journal (Provisional before the accounting+ // cutover, Posted after it) against the inventory adjustment variance account.+ // A count posts exactly once (Posted is terminal). Fixing a posted movement+ // happens per-movement via the correct-stock-movement server function, which+ // links the fix through itemLedger.correctionOfItemLedgerId.+ export const postInventoryCountInput = z.object({+ inventoryCountId: z.string()+ });++ export const postInventoryCountPermission = {+ update: "inventory"+ } satisfies PermissionRule<z.output<typeof postInventoryCountInput>>;++ /** Posts a Pending inventory count: one adjustment per counted variance, atomically. */+ export async function postInventoryCount(+ ctx: ServiceContext,+ raw: z.input<typeof postInventoryCountInput>+ ) {+ const { inventoryCountId } = postInventoryCountInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();+ const nowIso = datetime.timestamp();++ const inventoryCount = await single(db, "inventoryCount", {+ id: inventoryCountId,+ companyId+ });++ if (inventoryCount.error)+ throw new NotFoundError("Inventory count not found");++ const lines = await many(db, "inventoryCountLine", {+ inventoryCountId,+ companyId,+ countedQuantity: notNull+ });++ if (lines.error) throw new Error(lines.error.message);++ const comment = `Inventory Count ${inventoryCount.data.inventoryCountId}`;+ const countedLines = (lines.data ?? []).filter(+ (line) => line.countedQuantity !== null+ );++ // Serial validation: a serial-tracked item is a single unique unit, so each+ // serial line can only be counted 0 or 1. Block the post (before any write)+ // and return the offending line ids so the UI can highlight them.+ const itemIds = [...new Set(countedLines.map((line) => line.itemId))];+ const items = itemIds.length+ ? await many(+ db,+ "item",+ { id: itemIds, companyId },+ { columns: ["id", "itemTrackingType", "replenishmentSystem"] }+ )+ : null;+ if (items?.error) throw new Error(items.error.message);++ const trackingTypeByItem = new Map<string, string | null>(+ (items?.data ?? []).map((item) => [item.id, item.itemTrackingType])+ );+ // Explicit row types for these selects.+ type CountItemRow = {+ id: string;+ replenishmentSystem:+ | Database["public"]["Enums"]["itemReplenishmentSystem"]+ | null;+ };+ type CountItemCostRow = {+ itemId: string;+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"];+ unitCost: number | null;+ standardCost: number | null;+ itemPostingGroupId: string | null;+ };+ const replenishmentByItem = new Map(+ ((items?.data ?? []) as CountItemRow[]).map((item) => [+ item.id,+ item.replenishmentSystem+ ])+ );++ const itemCosts = itemIds.length+ ? await many(+ db,+ "itemCost",+ { itemId: itemIds, companyId },+ {+ columns: [+ "itemId",+ "costingMethod",+ "unitCost",+ "standardCost",+ "itemPostingGroupId"+ ]+ }+ )+ : null;+ if (itemCosts?.error) throw new Error(itemCosts.error.message);+ const itemCostByItem = new Map(+ ((itemCosts?.data ?? []) as CountItemCostRow[]).map((cost) => [+ cost.itemId,+ cost+ ])+ );+ const serialInvalidLineIds = countedLines+ .filter((line) => {+ if (trackingTypeByItem.get(line.itemId) !== "Serial") return false;+ const counted = Number(line.countedQuantity);+ return counted !== 0 && counted !== 1;+ })+ .map((line) => line.id);+ if (serialInvalidLineIds.length > 0) {+ throw new SerialQuantityError(serialInvalidLineIds);+ }++ // Reconcile against the frozen snapshot — no live on-hand read needed.+ const { planned } = planInventoryCountPost(countedLines);++ // Every variance that carries value posts to ONE journal: Provisional+ // before the company's accounting cutover, Posted after it. Resolve the+ // status + period BEFORE the transaction (REST hops mid-transaction park+ // the size-1 pool in idle-in-transaction); the status is read again inside.+ const postingStatus = await journalPostingStatus(db, companyId);+ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }+ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ // Active dimensions for the company group (post-shipment precedent) —+ // journal lines get Item / ItemPostingGroup / Location tags.+ const dimensionMap: Record<string, string> = {};+ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );+ if (companyRecord.error) throw new Error("Failed to fetch company");+ const dimensions = await many(+ db,+ "dimension",+ {+ companyGroupId: companyRecord.data.companyGroupId!,+ active: true,+ entityType: ["Item", "ItemPostingGroup", "Location"]+ },+ { columns: ["id", "entityType"] }+ );+ // Fail closed: journal lines must not silently lose dimension tags.+ if (dimensions.error) throw new Error("Failed to fetch dimensions");+ for (const dim of dimensions.data ?? []) {+ if (dim.entityType) dimensionMap[dim.entityType] = dim.id;+ }++ const accounting = {+ postingStatus,+ accountingPeriodId,+ accountDefaults: {+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,+ inventoryAdjustmentVarianceAccount:+ accountDefaults.data.inventoryAdjustmentVarianceAccount+ },+ description: comment,+ userId,+ dimensions: dimensionMap+ };++ await db.transaction().execute(async (trx) => {+ // Concurrency guard: lock the header and re-assert it is still Pending so+ // two concurrent posts can't both apply the delta (double-post). Mirrors+ // the FOR UPDATE guard in post-payment / post-memo; the end-of-transaction+ // guarded UPDATE below is the backstop.+ const locked = await trx+ .selectFrom("inventoryCount")+ .select(["id", "status"])+ .where("id", "=", inventoryCountId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();++ if (!locked) throw new NotFoundError("Inventory count not found");+ if (locked.status !== "Pending") {+ throw new Error("Inventory count is no longer pending");+ }+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);++ // ONE journal per count post: created lazily on the first variance that+ // carries value, then shared by every line's journal-line pair.+ let sharedJournalId: string | null = null;+ const accountingForLines = {+ ...accounting,+ getJournalId: async () => {+ if (!sharedJournalId) {+ sharedJournalId = await createAdjustmentJournal(trx, {+ companyId,+ accountingPeriodId: accounting.accountingPeriodId,+ status: postingStatus,+ description: accounting.description,+ postingDate: today,+ userId+ });+ }+ return sharedJournalId;+ }+ };++ // Post the reviewed variance for each line as an inventory adjustment,+ // booked through the shared core (ledger + cost layers + journal).+ for (const { line, delta } of planned) {+ if (delta === 0) continue;++ const itemCost = itemCostByItem.get(line.itemId);+ if (!itemCost) {+ throw new Error(`Missing item cost for item ${line.itemId}`);+ }++ const booked = await bookAdjustment(trx, {+ ledger: {+ postingDate: today,+ itemId: line.itemId,+ quantity: delta,+ locationId: line.locationId,+ storageUnitId: line.storageUnitId,+ trackedEntityId: line.trackedEntityId,+ entryType: delta > 0 ? "Positive Adjmt." : "Negative Adjmt.",+ documentType: "Inventory Count",+ documentId: inventoryCountId,+ comment,+ companyId,+ createdBy: userId+ },+ item: {+ itemTrackingType: trackingTypeByItem.get(line.itemId) ?? null,+ replenishmentSystem: replenishmentByItem.get(line.itemId) ?? null,+ itemPostingGroupId: itemCost.itemPostingGroupId+ },+ itemCost,+ accounting: accountingForLines+ });++ // Tracked lines: apply the same delta to the entity's quantity (not a+ // set-to-counted) so movements since the snapshot aren't overwritten.+ // Lock and read the live row so the guard sees the current quantity;+ // a delta that would drive it negative means stock moved since the+ // count, so we throw to roll back rather than clamp (which would desync+ // the entity from the ledger delta already booked above). Landing on+ // zero flips the lot Consumed.+ if (line.trackedEntityId) {+ const entity = await trx+ .selectFrom("trackedEntity")+ .select(["quantity", "status"])+ .where("id", "=", line.trackedEntityId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ const settled = resolveCountedEntity({+ currentQuantity: Number(entity?.quantity ?? 0),+ delta,+ currentStatus: entity?.status ?? "Available"+ });+ await trx+ .updateTable("trackedEntity")+ .set({ quantity: settled.quantity, status: settled.status })+ .where("id", "=", line.trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }++ await trx+ .updateTable("inventoryCountLine")+ .set({ postedItemLedgerId: booked.itemLedgerId })+ .where("id", "=", line.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Guard the transition inside the transaction: only a still-Pending count+ // can be posted. If a concurrent post already moved it to Posted, this+ // matches 0 rows and we throw to roll back this transaction's ledger+ // writes — preventing a double-post.+ const posted = await trx+ .updateTable("inventoryCount")+ .set({+ status: "Posted",+ postedBy: userId,+ postedAt: nowIso,+ updatedBy: userId,+ updatedAt: nowIso+ })+ .where("id", "=", inventoryCountId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Pending")+ .returning(["id"])+ .executeTakeFirst();++ if (!posted) {+ throw new Error("Inventory count is no longer pending");+ }+ });++ return { success: true };+ }++ /**+ * A line moves stock out of the bin it names, and only that bin (`null` is the+ * unassigned bin). Picking a unit held elsewhere would book its -1 against a+ * bin that does not hold it.+ */+ async function assertInSourceBin(+ trx: Transaction<KyselyDatabase>,+ args: {+ trackedEntityId: string;+ readableId: string | null;+ quantity: number;+ locationId: string;+ storageUnitId: string | null;+ companyId: string;+ }+ ) {+ const onHand = await getTrackedEntityOnHandInBin(trx, args);+ if (round(onHand) < round(args.quantity)) {+ throw new PickGuardError(+ "over-pick",+ `${args.readableId ?? args.trackedEntityId} is not in this line's source storage unit`+ );+ }+ }++ /**+ * Applies the company's expired-entity policy to one entity about to be+ * transferred: a warning under `Warn`, a throw when blocked. An override with+ * a reason passes under `BlockWithOverride`.+ */+ function checkExpiredEntity(+ entity: { id: string; expirationDate: string | null },+ policy: ExpiredEntityPolicy,+ override: ExpiryOverride,+ today: CalendarDate+ ): { warning?: string } {+ if (expiredEntities([entity], today).length === 0) return {};+ switch (expiryVerdict(policy, override)) {+ case "warn":+ return { warning: `Transferred expired tracked entity: ${entity.id}` };+ case "allow":+ return {};+ case "block":+ throw new Error(`Cannot transfer expired tracked entity: ${entity.id}`);+ }+ }++ export const postStockTransferInput = z.discriminatedUnion("type", [+ z.object({+ type: z.literal("inventory"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ quantity: z.number().positive(),+ locationId: z.string()+ }),+ z.object({+ type: z.literal("unpickInventory"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ locationId: z.string()+ }),+ z.object({+ type: z.literal("serial"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ trackedEntityId: z.string(),+ locationId: z.string()+ }),+ z.object({+ type: z.literal("batch"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ trackedEntityId: z.string(),+ quantity: z.number().positive(),+ overrideExpired: z.boolean().optional(),+ overrideReason: z.string().optional(),+ locationId: z.string()+ }),+ z.object({+ type: z.literal("unpickSerial"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ trackedEntityId: z.string(),+ locationId: z.string()+ }),+ z.object({+ type: z.literal("unpickBatch"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ trackedEntityId: z.string(),+ locationId: z.string()+ })+ ]);++ export const postStockTransferPermission = {} satisfies PermissionRule<+ z.output<typeof postStockTransferInput>+ >;++ /** Picks or un-picks stock-transfer lines (untracked, serial or batch), per `type`. */+ export async function postStockTransfer(+ ctx: ServiceContext,+ raw: z.input<typeof postStockTransferInput>+ ) {+ const input = postStockTransferInput.parse(raw);++ const db = ctx.asSystem.pg;+ const validatedPayload = {+ ...input,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ };++ // The permission check proves the caller may act in companyId, not that the+ // body's ids belong to it. Every case writes stockTransferId as the+ // ledger/activity documentId and locationId onto this company's ledger+ // rows, so they are re-read under companyId — and the line must be on the+ // transfer the body names.+ {+ const { companyId, stockTransferId, stockTransferLineId, locationId } =+ validatedPayload;+ const line = await db+ .selectFrom("stockTransferLine")+ .select("id")+ .where("id", "=", stockTransferLineId)+ .where("stockTransferId", "=", stockTransferId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!line) throw new NotFoundError("Stock transfer line not found");+ await assertCompanyRecords(+ db,+ "location",+ [locationId],+ companyId,+ "Location"+ );+ }++ const companyToday = datetime.today(+ await getCompanyTimeZone(db, validatedPayload.companyId)+ );+ const today = companyToday.toString();+ let expiredWarning: string | undefined;+ let splitEntityId: string | undefined;++ logger.info({+ function: "post-stock-transfer",+ ...validatedPayload+ });++ switch (validatedPayload.type) {+ case "inventory": {+ const {+ stockTransferId,+ stockTransferLineId,+ quantity,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Create item ledger entries for inventory transfer+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(-quantity),+ locationId: locationId,+ storageUnitId: stockTransferLine.fromStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ createdBy: userId,+ companyId+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(quantity),+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ createdBy: userId,+ companyId+ });++ // Insert item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Update stock transfer line with picked quantity+ await trx+ .updateTable("stockTransferLine")+ .set({+ pickedQuantity: (stockTransferLine.pickedQuantity ?? 0) + quantity,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "unpickInventory": {+ const {+ stockTransferId,+ stockTransferLineId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const currentPickedQuantity = stockTransferLine.pickedQuantity ?? 0;++ if (currentPickedQuantity > 0) {+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Create reverse item ledger entries to undo the transfer+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(currentPickedQuantity), // Positive to restore inventory at from shelf+ locationId: locationId,+ storageUnitId: stockTransferLine.fromStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ createdBy: userId,+ companyId+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(-currentPickedQuantity), // Negative to remove inventory from to shelf+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ createdBy: userId,+ companyId+ });++ // Insert reverse item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }+ }++ // Reset picked quantity to 0+ await trx+ .updateTable("stockTransferLine")+ .set({+ trackedEntityId: null,+ pickedQuantity: 0,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "serial": {+ const {+ stockTransferId,+ stockTransferLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details. Lock the row so concurrent scans+ // of the same line cannot both write a +1 over a stale read.+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ // Refuse a scan that would exceed the line's serial count.+ const newPickedQuantity = resolvePick({+ lineQuantity: Number(stockTransferLine.quantity ?? 0),+ pickedQuantity: Number(stockTransferLine.pickedQuantity ?? 0),+ transferQuantity: 1+ });++ // Lock the serial itself BEFORE the repeat-scan query: the guard+ // below reads trackedActivityInput, and two concurrent scans of the+ // same serial would both read "not on this transfer" and both post a+ // Transfer activity + ledger pair. The batch case takes the same+ // lock; here it serializes the guard rather than an on-hand draw.+ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .select(["id", "readableId"])+ .forUpdate()+ .executeTakeFirstOrThrow();++ const fromStorageUnitId = stockTransferLine.fromStorageUnitId;+ await assertInSourceBin(trx, {+ trackedEntityId,+ readableId: trackedEntity.readableId,+ quantity: 1,+ locationId,+ storageUnitId: fromStorageUnitId,+ companyId+ });++ // Refuse a REPEAT scan of the same serial on this transfer. Each scan+ // posts a Transfer activity + a −1/+1 ledger pair, so a silent no-op+ // would let the ledger double; the guard is an explicit 400.+ const alreadyOnTransfer = await trx+ .selectFrom("trackedActivityInput as tai")+ .innerJoin("trackedActivity as ta", "ta.id", "tai.trackedActivityId")+ .where("tai.trackedEntityId", "=", trackedEntityId)+ .where("tai.companyId", "=", companyId)+ .where("ta.type", "=", "Transfer")+ .where("ta.sourceDocument", "=", "Stock Transfer")+ .where("ta.sourceDocumentId", "=", stockTransferId)+ .select("tai.trackedEntityId")+ .executeTakeFirst();+ if (alreadyOnTransfer) {+ throw new PickGuardError(+ "already-picked",+ `Serial ${trackedEntity.readableId ?? trackedEntityId} is already picked on this transfer`+ );+ }++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Create transfer activity+ const transferActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: transferActivityId,+ type: "Transfer",+ sourceDocument: "Stock Transfer",+ sourceDocumentId: stockTransferId,+ attributes: {+ "Stock Transfer": stockTransferId,+ "Stock Transfer Line": stockTransferLineId,+ "From Location": locationId,+ "To Location": locationId,+ "From Shelf": fromStorageUnitId,+ "To Shelf": stockTransferLine.toStorageUnitId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ // Record tracked entity as input to transfer+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: transferActivityId,+ trackedEntityId: trackedEntityId,+ quantity: 1,+ companyId,+ createdBy: userId+ })+ .execute();++ // Create item ledger entries for transfer+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -1,+ locationId: locationId,+ storageUnitId: fromStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: 1,+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ });++ // Insert item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Update stock transfer line with the accumulated picked quantity.+ await trx+ .updateTable("stockTransferLine")+ .set({+ trackedEntityId,+ pickedQuantity: newPickedQuantity,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "batch": {+ const {+ stockTransferId,+ stockTransferLineId,+ trackedEntityId,+ quantity,+ overrideExpired,+ overrideReason,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ const policy = await getExpiredEntityPolicy(db, companyId);++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details. Lock the row so two concurrent+ // scans of the same line accumulate instead of racing to overwrite+ // pickedQuantity (the ledger would double otherwise).+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ // Get tracked entity details. Lock it too so the on-hand this pick+ // draws against cannot be spent by a concurrent transaction.+ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ // Refuse a pick that over-draws the line or the source lot before any+ // record is written; resolvePick returns the new running total.+ const newPickedQuantity = resolvePick({+ lineQuantity: Number(stockTransferLine.quantity ?? 0),+ pickedQuantity: Number(stockTransferLine.pickedQuantity ?? 0),+ transferQuantity: quantity+ });+ assertEntityCoversPick({+ entityQuantity: Number(trackedEntity.quantity),+ transferQuantity: quantity+ });+ const fromStorageUnitId = stockTransferLine.fromStorageUnitId;+ await assertInSourceBin(trx, {+ trackedEntityId,+ readableId: trackedEntity.readableId,+ quantity,+ locationId,+ storageUnitId: fromStorageUnitId,+ companyId+ });++ // Expiry policy gate (throws on hard reject; returns warning for 'Warn').+ const expiredCheck = checkExpiredEntity(+ {+ id: trackedEntity.id,+ expirationDate: trackedEntity.expirationDate+ },+ policy,+ { allowed: !!overrideExpired, reason: overrideReason ?? null },+ companyToday+ );+ if (expiredCheck.warning) {+ expiredWarning = expiredCheck.warning;+ }++ // Round BOTH operands once, here: everything downstream — the split+ // gate, the split records, the Transfer activity input and the two+ // ledger rows — derives from these, so a residue draw can never book+ // an unrounded quantity against a lot the gate treated as whole.+ const entityQuantity = round(Number(trackedEntity.quantity));+ const transferQuantity = round(quantity);+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Split the batch when transferring less than the whole entity: the+ // source entity keeps its id and is decremented; a NEW child entity+ // departs to the destination bin with the transfer quantity.+ let transferredEntityId = trackedEntityId;+ if (!isFullDraw(entityQuantity, transferQuantity)) {+ const childId = nanoid();+ splitEntityId = childId;+ transferredEntityId = childId;++ const split = buildBatchSplitRecords({+ parent: {+ id: trackedEntity.id,+ readableId: trackedEntity.readableId,+ quantity: entityQuantity,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId: trackedEntity.sourceDocumentReadableId,+ itemId: trackedEntity.itemId ?? null,+ expirationDate: trackedEntity.expirationDate ?? null,+ attributes: trackedEntity.attributes as Record<+ string,+ unknown+ > | null+ },+ drawQuantity: transferQuantity,+ childId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Stock Transfer",+ activitySourceDocumentId: stockTransferId,+ bin: { storageUnitId: fromStorageUnitId, locationId },+ itemLedgerItemId: stockTransferLine.itemId,+ companyId,+ userId,+ postingDate: today,+ childStatus: "Available"+ });++ await trx+ .insertInto("trackedActivity")+ .values(+ split.activityInsert as Insertable<+ KyselyDatabase["trackedActivity"]+ >+ )+ .execute();++ await trx+ .insertInto("trackedEntity")+ .values(+ split.childEntityInsert as Insertable<+ KyselyDatabase["trackedEntity"]+ >+ )+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert)+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values(split.activityOutputInsert)+ .execute();++ await trx+ .updateTable("trackedEntity")+ .set(split.parentUpdate)+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ itemLedgerInserts.push(+ ...(split.ledgerInserts.map((ledgerRow) => ({+ ...ledgerRow,+ quantity: round(ledgerRow.quantity)+ })) as typeof itemLedgerInserts)+ );+ }++ // Create transfer activity+ const transferActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: transferActivityId,+ type: "Transfer",+ sourceDocument: "Stock Transfer",+ sourceDocumentId: stockTransferId,+ attributes: {+ "Stock Transfer": stockTransferId,+ "Stock Transfer Line": stockTransferLineId,+ "From Location": locationId,+ "To Location": locationId,+ "From Shelf": fromStorageUnitId,+ "To Shelf": stockTransferLine.toStorageUnitId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ // Record the DEPARTING entity (split child, or the whole entity on+ // a full-quantity transfer) as input to the transfer.+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: transferActivityId,+ trackedEntityId: transferredEntityId,+ quantity: transferQuantity,+ companyId,+ createdBy: userId+ })+ .execute();++ // A transfer MOVES the batch between bins — it stays Available+ // (consumed at production). Matches the serial case and post-picking.++ // Create item ledger entries for transfer+ itemLedgerInserts.push(+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(-transferQuantity),+ locationId: locationId,+ storageUnitId: fromStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: transferredEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(transferQuantity),+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: transferredEntityId,+ createdBy: userId,+ companyId+ }+ );++ // Insert item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Update stock transfer line with the accumulated picked quantity.+ // trackedEntityId is keep-last: each partial pick mints a fresh child+ // entity, so the line points at the newest departing lot (matching+ // serial). Unpick reverses only the last activity on such a line.+ await trx+ .updateTable("stockTransferLine")+ .set({+ trackedEntityId: transferredEntityId,+ pickedQuantity: newPickedQuantity,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "unpickSerial": {+ const {+ stockTransferId,+ stockTransferLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line AND the entity: an unpick read-modify-writes the+ // entity's quantity/status and the line's pickedQuantity, so two+ // concurrent unpicks of the same child would both credit the parent+ // and both decrement the line off the same stale read. Same locks the+ // pick paths take.+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ // Find the transfer activity for this tracked entity+ const transferActivity = await trx+ .selectFrom("trackedActivity")+ .innerJoin(+ "trackedActivityInput",+ "trackedActivity.id",+ "trackedActivityInput.trackedActivityId"+ )+ .where("trackedActivity.type", "=", "Transfer")+ .where("trackedActivity.sourceDocument", "=", "Stock Transfer")+ .where("trackedActivity.sourceDocumentId", "=", stockTransferId)+ .where("trackedActivityInput.trackedEntityId", "=", trackedEntityId)+ .where("trackedActivity.companyId", "=", companyId)+ .selectAll("trackedActivity")+ .executeTakeFirstOrThrow();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Create reverse item ledger entries to undo the transfer+ // First, remove the entity from the destination shelf (toStorageUnitId)+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -1, // Negative to remove inventory from to shelf+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ });++ // Then, restore the entity to the source shelf (fromStorageUnitId)+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: 1, // Positive to restore inventory at from shelf+ locationId: locationId,+ storageUnitId: stockTransferLine.fromStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ });++ // Insert reverse item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Delete the tracked activity and its related records+ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", transferActivity.id!)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", transferActivity.id!)+ .where("companyId", "=", companyId)+ .execute();++ // Update tracked entity status back to available and restore shelf location+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ attributes: {+ ...(trackedEntity.attributes as Record<string, unknown>),+ Shelf: stockTransferLine.fromStorageUnitId+ }+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ // Update stock transfer line with reduced picked quantity+ await trx+ .updateTable("stockTransferLine")+ .set({+ trackedEntityId: null,+ pickedQuantity: Math.max(+ 0,+ (stockTransferLine.pickedQuantity ?? 0) - 1+ ),+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "unpickBatch": {+ const {+ stockTransferId,+ stockTransferLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line AND the entity: an unpick read-modify-writes the+ // entity's quantity/status and the line's pickedQuantity, so two+ // concurrent unpicks of the same child would both credit the parent+ // and both decrement the line off the same stale read. Same locks the+ // pick paths take.+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ // Find the transfer activity for this tracked entity+ const transferActivity = await trx+ .selectFrom("trackedActivity")+ .innerJoin(+ "trackedActivityInput",+ "trackedActivity.id",+ "trackedActivityInput.trackedActivityId"+ )+ .where("trackedActivity.type", "=", "Transfer")+ .where("trackedActivity.sourceDocument", "=", "Stock Transfer")+ .where("trackedActivity.sourceDocumentId", "=", stockTransferId)+ .where("trackedActivityInput.trackedEntityId", "=", trackedEntityId)+ .where("trackedActivity.companyId", "=", companyId)+ .selectAll("trackedActivity")+ .executeTakeFirstOrThrow();++ // The whole child returns to its parent, so round once here and let+ // the parent increase, the ledger pair and the pickedQuantity+ // decrement all derive from the same value.+ const transferQuantity = round(Number(trackedEntity.quantity));++ // Re-checked UNDER the lock: a lot holding nothing has either already+ // been unpicked or been consumed at production. Either way there is+ // nothing to return, and proceeding would delete the transfer+ // activity and reset pickedQuantity for a no-op.+ if (transferQuantity <= 0) {+ throw new PickGuardError(+ "already-picked",+ `Lot ${trackedEntity.readableId ?? trackedEntityId} has no quantity left to unpick`+ );+ }+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ const entityAttributes = (trackedEntity.attributes ?? {}) as Record<+ string,+ unknown+ >;+ // New convention: the line's entity is a split CHILD carrying a+ // back-pointer to the parent that stayed at the source bin.+ const splitFromParentId = entityAttributes["Split From Entity ID"] as+ | string+ | undefined;+ // Legacy convention (pre-flip rows): the departed ORIGINAL carries a+ // forward pointer to the remainder entity it left behind.+ const legacyRemainderId = entityAttributes["Split Entity ID"] as+ | string+ | undefined;++ if (splitFromParentId) {+ // Merge the child fully back into its parent and delete the Split+ // — a clean undo, as if the partial transfer never happened.+ // Locked too — its quantity is incremented from this read.+ const parent = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", splitFromParentId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: round(round(Number(parent.quantity)) + transferQuantity)+ })+ .where("id", "=", parent.id)+ .where("companyId", "=", companyId)+ .execute();++ // Drain the child (don't delete it — ledger history keeps the FK).+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Consumed",+ quantity: 0+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ itemLedgerInserts.push(+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(-transferQuantity), // drain the child at the destination+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(transferQuantity), // restore the parent at the source+ locationId: locationId,+ storageUnitId: stockTransferLine.fromStorageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: parent.id,+ createdBy: userId,+ companyId+ }+ );++ // Delete the Split activity that minted the child — scoped to the+ // entity AND this transfer (a bare sourceDocumentId lookup grabs+ // a sibling line's split on multi-line transfers).+ const splitActivity = await trx+ .selectFrom("trackedActivity")+ .where("type", "=", "Split")+ .where("sourceDocument", "=", "Stock Transfer")+ .where("sourceDocumentId", "=", stockTransferId)+ .where(attributesContain({ "Split Entity ID": trackedEntityId }))+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ if (splitActivity) {+ await trx+ .deleteFrom("trackedActivityOutput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();+ }+ } else if (legacyRemainderId) {+ // This entity was created from a split, need to merge it back+ const originalEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", legacyRemainderId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const originalQuantity = round(+ round(Number(originalEntity.quantity)) + transferQuantity+ );++ // Find the split activity — scoped to the remainder entity this+ // pointer names, not just the transfer (multi-line safety).+ const splitActivity = await trx+ .selectFrom("trackedActivity")+ .where("type", "=", "Split")+ .where("sourceDocument", "=", "Stock Transfer")+ .where("sourceDocumentId", "=", stockTransferId)+ .where(attributesContain({ "Split Entity ID": legacyRemainderId }))+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Update original entity with merged quantity and restore shelf location+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Consumed",+ quantity: 0+ })+ .where("id", "=", legacyRemainderId)+ .where("companyId", "=", companyId)+ .execute();++ // Mark the split entity as consumed (don't delete it)+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ quantity: originalQuantity+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ // Create item ledger entries for merge+ // Both entities are on the fromStorageUnitId during the merge operation+ itemLedgerInserts.push(+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(originalQuantity), // zero out the split entity+ locationId: locationId,+ storageUnitId: stockTransferLine.fromStorageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(-transferQuantity), // Positive to restore to original entity+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId, // Both entities are on the source shelf+ entryType: "Negative Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(-(originalQuantity - transferQuantity)), // Positive to restore to original entity+ locationId: locationId,+ storageUnitId: stockTransferLine.fromStorageUnitId, // Both entities are on the source shelf+ entryType: "Negative Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: legacyRemainderId,+ createdBy: userId,+ companyId+ }+ );++ // Delete split activity records+ await trx+ .deleteFrom("trackedActivityOutput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ // This was a direct transfer, just restore the entity and shelf location+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ attributes: {+ ...(trackedEntity.attributes as Record<string, unknown>),+ Shelf: stockTransferLine.fromStorageUnitId+ }+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ // Create reverse item ledger entries to undo the transfer+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(transferQuantity), // Positive to restore inventory at from shelf+ locationId: locationId,+ storageUnitId: stockTransferLine.fromStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: round(-transferQuantity), // Negative to remove inventory from to shelf+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId+ });+ }++ // Insert item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Delete the transfer activity and its related records+ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", transferActivity.id!)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", transferActivity.id!)+ .where("companyId", "=", companyId)+ .execute();++ // Update stock transfer line with reduced picked quantity+ await trx+ .updateTable("stockTransferLine")+ .set({+ trackedEntityId: null,+ pickedQuantity: Math.max(+ 0,+ round(+ round(stockTransferLine.pickedQuantity ?? 0) - transferQuantity+ )+ ),+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }+ }++ return {+ success: true,+ warning: expiredWarning,+ splitEntityId+ };+ }+ // Corrects a posted stock movement by inserting ONE opposite (delta) movement+ // linked to the original via itemLedger.correctionOfItemLedgerId. The caller+ // supplies the SIGNED quantity the movement should have been; the delta is+ // derived against the movement's current effective quantity (original + all+ // prior corrections in its group), so repeated corrections converge.+ //+ // The correction carries the ORIGINAL movement's postingDate and posts its GL+ // journal into the accounting period containing that date (fails when that+ // period is Locked/Closed). entryNumber is a SERIAL and cannot be+ // retro-inserted — "next to the original" is delivered by the postingDate and+ // by the stock-movements UI, which nests corrections under their original.+ export const correctStockMovementInput = z.object({+ itemLedgerId: z.string(),+ // SIGNED corrected quantity, matching the ledger's sign convention+ // (a shipment of -5 that should have been -3 → correctedQuantity: -3).+ correctedQuantity: z.number(),+ comment: z.string().optional().nullable()+ });++ const MAX_CORRECTION_CHAIN_DEPTH = 100;++ export const postStockMovementCorrectionPermission = {+ update: "inventory"+ } satisfies PermissionRule<z.output<typeof correctStockMovementInput>>;++ export async function postStockMovementCorrection(+ ctx: ServiceContext,+ raw: z.input<typeof correctStockMovementInput>+ ) {+ const { itemLedgerId, correctedQuantity, comment } =+ correctStockMovementInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const ledgerColumns = [+ "id",+ "itemId",+ "locationId",+ "storageUnitId",+ "trackedEntityId",+ "quantity",+ "postingDate",+ "entryType",+ "documentType",+ "documentId",+ "correctionOfItemLedgerId"+ ] as const;++ const originalResult = await maybeSingle(+ db,+ "itemLedger",+ { id: itemLedgerId, companyId },+ { columns: ledgerColumns }+ );+ if (originalResult.error) throw new Error("Failed to fetch stock movement");+ if (!originalResult.data) {+ throw new NotFoundError("Stock movement not found");+ }++ // Walk up to the topmost ancestor: corrections always link to the ROOT so+ // the group stays flat and its effective quantity is a simple sum.+ let root = originalResult.data;+ for (+ let depth = 0;+ root.correctionOfItemLedgerId && depth < MAX_CORRECTION_CHAIN_DEPTH;+ depth+++ ) {+ const parent = await maybeSingle(+ db,+ "itemLedger",+ { id: root.correctionOfItemLedgerId, companyId },+ { columns: ledgerColumns }+ );+ if (parent.error) throw new Error("Failed to fetch stock movement");+ // Broken link (no FK on correctionOfItemLedgerId): treat the current row+ // as the root rather than failing the correction.+ if (!parent.data) break;+ root = parent.data;+ }++ // Collect the whole correction group (historical count corrections chained+ // fix→fix, so descendants can be more than one level deep).+ let effectiveQuantity = Number(root.quantity);+ let frontier = [root.id];+ const seen = new Set<string>([root.id]);+ while (frontier.length > 0) {+ const children = await many(+ db,+ "itemLedger",+ { correctionOfItemLedgerId: frontier, companyId },+ { columns: ["id", "quantity"] }+ );+ if (children.error) throw new Error("Failed to fetch corrections");+ frontier = [];+ for (const child of children.data ?? []) {+ if (seen.has(child.id)) continue;+ seen.add(child.id);+ effectiveQuantity += Number(child.quantity);+ frontier.push(child.id);+ }+ }++ // Round the delta ONCE, here: it is persisted twice — into the entity via+ // eb("quantity", "+", delta) and into the correction's own itemLedger row —+ // and both must carry the same value at internal scale. A raw `=== 0` no-op+ // gate also lets float residue (correcting a -5 line back to exactly its+ // effective -4.99999999999999 sum) through as a 1e-14 correction row.+ const delta = round(correctedQuantity - effectiveQuantity);+ if (equals(delta, 0)) {+ throw new InvalidInputError(+ "Corrected quantity matches the current effective quantity — nothing to correct"+ );+ }++ // A correction row shows only its delta (+4), which doesn't tell the reader+ // the from→to intent — so when the user gives no reason, self-document it.+ const resolvedComment =+ comment?.trim() ||+ `Corrected from ${effectiveQuantity} to ${correctedQuantity}`;++ const [itemResult, itemCostResult, trackingQuantities] = await inOrder([+ () =>+ single(+ db,+ "item",+ { id: root.itemId, companyId },+ { columns: ["id", "itemTrackingType", "replenishmentSystem"] }+ ),+ () =>+ single(+ db,+ "itemCost",+ { itemId: root.itemId, companyId },+ {+ columns: [+ "costingMethod",+ "unitCost",+ "standardCost",+ "itemPostingGroupId"+ ]+ }+ ),+ () =>+ root.locationId+ ? rpcRows(db, "get_item_quantities_by_tracking_id", {+ item_id: root.itemId,+ company_id: companyId,+ location_id: root.locationId+ })+ : Promise.resolve({ data: null, error: null })+ ]);++ if (itemResult.error) throw new Error("Failed to fetch item");+ if (itemCostResult.error) throw new Error("Failed to fetch item cost");+ // Fail closed: a failed quantity read must abort, not read as "no stock".+ if (trackingQuantities.error) {+ throw new Error("Failed to fetch current quantities");+ }++ const item = {+ itemTrackingType: itemResult.data.itemTrackingType,+ replenishmentSystem: itemResult.data.replenishmentSystem,+ itemPostingGroupId: itemCostResult.data.itemPostingGroupId+ };++ const isSerial = item.itemTrackingType === "Serial";+ if (isSerial) {+ if (!Number.isInteger(delta)) {+ throw new InvalidInputError(+ "Corrections on serial-tracked items must be whole numbers"+ );+ }+ // A serial number is a single unique unit — the corrected movement can+ // never carry more than one of it (matches inventoryAdjustmentValidator).+ if (Math.abs(correctedQuantity) > 1) {+ throw new InvalidInputError("Serial items can only have a quantity of 1");+ }+ }++ // A negative delta removes stock now — it must not drive the stock target+ // (tracked entity, or untracked stock in the original's bin) below zero.+ if (delta < 0 && root.locationId) {+ type TrackingQuantityRow = {+ trackedEntityId: string | null;+ storageUnitId: string | null;+ quantity: number | null;+ };+ const trackingRows = (trackingQuantities.data ??+ []) as TrackingQuantityRow[];+ // null == undefined — loose equality is deliberate (matches+ // post-inventory-adjustment's storage-unit lookup).+ const stockTarget = root.trackedEntityId+ ? trackingRows.find((q) => q.trackedEntityId == root.trackedEntityId)+ : trackingRows.find(+ (q) =>+ q.trackedEntityId == null && q.storageUnitId == root.storageUnitId+ );+ if ((stockTarget?.quantity ?? 0) < Math.abs(delta)) {+ throw new InvalidInputError(+ "Insufficient quantity for negative adjustment"+ );+ }+ }++ let trackedEntityStatus: string | null = null;+ if (root.trackedEntityId) {+ const entity = await maybeSingle(+ db,+ "trackedEntity",+ { id: root.trackedEntityId, companyId },+ { columns: ["status", "quantity"] }+ );+ if (entity.error || !entity.data) {+ throw new Error("Failed to fetch tracked entity");+ }+ trackedEntityStatus = entity.data.status;+ if (trackedEntityStatus === "Consumed") {+ throw new InvalidInputError(+ "Cannot correct a movement of a consumed tracked entity"+ );+ }+ // Round before comparing: a correction that lands the lot exactly on+ // zero can read as −1e-17 raw and refuse a legitimate full correction.+ if (round(Number(entity.data.quantity) + delta) < 0) {+ throw new InvalidInputError(+ "Correction would make the tracked entity quantity negative"+ );+ }+ if (isSerial && Number(entity.data.quantity) + delta > 1) {+ throw new InvalidInputError("Serial items can only have a quantity of 1");+ }+ }++ // A correction that carries value posts a journal: Provisional before the+ // company's accounting cutover, Posted after it. Read here to decide+ // whether to resolve a period, and again inside the transaction.+ const postingStatus = await journalPostingStatus(db, companyId);+ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ const dimensionMap: Record<string, string> = {};+ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );+ if (companyRecord.error) throw new Error("Failed to fetch company");+ const companyGroupId = companyRecord.data.companyGroupId;+ if (companyGroupId) {+ const dimensions = await many(+ db,+ "dimension",+ {+ companyGroupId,+ active: true,+ entityType: ["Item", "ItemPostingGroup", "Location"]+ },+ { columns: ["id", "entityType"] }+ );+ if (dimensions.error) throw new Error("Failed to fetch dimensions");+ for (const dim of dimensions.data ?? []) {+ if (dim.entityType) dimensionMap[dim.entityType] = dim.id;+ }+ }++ // Resolve the accounting period BEFORE opening the Kysely transaction —+ // the REST client mid-transaction parks the (size 1) pool. The period is+ // the one containing the ORIGINAL movement's postingDate; Locked/Closed+ // periods throw here with a user-facing message. A Provisional journal has+ // no accounting period.+ // A movement dated before the cutover sits in the opening balance: a+ // correction would resolve (or create) a period before the cutover and+ // post against value the opening journal already holds.+ await refuseVoidBeforeCutover(+ db,+ companyId,+ root.postingDate ? String(root.postingDate) : null,+ STOCK_CORRECTION_BEFORE_CUTOVER_ERROR+ );+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getAccountingPeriodForDate(companyId, db, root.postingDate)+ : null;+ const accounting = {+ postingStatus,+ accountingPeriodId,+ accountDefaults: {+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,+ inventoryAdjustmentVarianceAccount:+ accountDefaults.data.inventoryAdjustmentVarianceAccount+ },+ description: `Stock Movement Correction — ${resolvedComment}`,+ userId,+ dimensions: dimensionMap+ };++ let resultLedgerId: string | null = null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);++ if (root.trackedEntityId) {+ const updated = await trx+ .updateTable("trackedEntity")+ .set((eb) => ({ quantity: eb("quantity", "+", delta) }))+ .where("id", "=", root.trackedEntityId!)+ .where("companyId", "=", companyId)+ .where("status", "!=", "Consumed")+ .where((eb) => eb("quantity", ">=", -delta))+ // Serial ceiling re-checked atomically: resulting quantity ≤ 1.+ .$if(isSerial, (qb) =>+ qb.where((eb) => eb("quantity", "<=", 1 - delta))+ )+ .returning(["id", "quantity", "status"])+ .executeTakeFirst();+ if (!updated) {+ throw new InvalidInputError(+ "Tracked entity changed while correcting — try again"+ );+ }+ // If the correction drove the lot to zero, Consume it (a Scrapped lot+ // stays Scrapped). `updated.status` is the unchanged pre-flip status.+ const settledStatus = statusAfterQuantityChange(+ Number(updated.quantity),+ updated.status+ );+ if (settledStatus !== updated.status) {+ await trx+ .updateTable("trackedEntity")+ .set({ status: settledStatus })+ .where("id", "=", root.trackedEntityId!)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ const booked = await bookAdjustment(trx, {+ ledger: {+ postingDate: root.postingDate,+ itemId: root.itemId,+ quantity: delta,+ locationId: root.locationId,+ storageUnitId: root.storageUnitId,+ trackedEntityId: root.trackedEntityId,+ entryType: delta > 0 ? "Positive Adjmt." : "Negative Adjmt.",+ documentType: root.documentType,+ documentId: root.documentId,+ correctionOfItemLedgerId: root.id,+ comment: resolvedComment,+ companyId,+ createdBy: userId+ },+ item,+ itemCost: itemCostResult.data,+ accounting+ });+ resultLedgerId = booked.itemLedgerId;+ });++ return { itemLedger: resultLedgerId ? { id: resultLedgerId } : null };+ }++ export const kanbanReplenishInput = z.discriminatedUnion("mode", [+ z.object({ mode: z.literal("scan"), kanbanId: z.string().min(1) }),+ z.object({+ mode: z.literal("level"),+ kanbanIds: z.array(z.string().min(1)).min(1)+ })+ ]);++ // The first three are the scan route's own error strings, kept exact.+ export const KANBAN_REPLENISH_REASONS = {+ missingStorageUnit: "Kanban is missing a from or to storage unit",+ foreignStorageUnit: "Storage unit does not belong to the kanban location",+ missingItem: "Failed to get item",+ notTransfer: "Kanban is not a transfer kanban",+ notArmed: "Kanban has no replenishment level"+ } as const;++ type KanbanReplenishReason =+ (typeof KANBAN_REPLENISH_REASONS)[keyof typeof KANBAN_REPLENISH_REASONS];++ export type KanbanReplenishOutcome =+ | {+ kanbanId: string;+ outcome: "created";+ id: string;+ stockTransferId: string;+ }+ | { kanbanId: string; outcome: "at-level"; projectedQuantity: number }+ | { kanbanId: string; outcome: "invalid"; reason: KanbanReplenishReason };++ export type KanbanReplenishResult = { results: KanbanReplenishOutcome[] };++ export const replenishKanbanPermission = {+ by: "mode",+ rules: { scan: { create: "inventory" }, level: "system" }+ } satisfies PermissionRule<z.output<typeof kanbanReplenishInput>>;++ /**+ * The only writer of a kanban replenishment: a Released stock transfer from a+ * Transfer kanban's From storage unit to its To storage unit, marked with+ * `kanbanId` and a "Kanban replenishment" note.+ *+ * - `scan` always creates (the operator asked for it).+ * - `level` creates only while the projected quantity at the To storage unit+ * (on-hand + open inbound transfers) is below `replenishmentLevel`, and then+ * moves enough whole kanban quantities to reach the level, so a second+ * signal for the same shortfall writes nothing.+ *+ * The kanban rows are locked `FOR UPDATE` in id order, so two signals for one+ * kanban serialise and the second reads the first one's transfer as supply.+ */+ export async function replenishKanban(+ ctx: ServiceContext,+ raw: z.input<typeof kanbanReplenishInput>+ ) {+ const input = kanbanReplenishInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ const { results, created } = await db.transaction().execute(async (trx) => {+ let kanbanQuery = trx+ .selectFrom("kanban")+ .select([+ "id",+ "itemId",+ "locationId",+ "replenishmentSystem",+ "replenishmentLevel",+ "quantity",+ "fromStorageUnitId",+ "storageUnitId"+ ])+ .where("companyId", "=", companyId);++ kanbanQuery =+ input.mode === "scan"+ ? kanbanQuery.where("id", "=", input.kanbanId)+ : kanbanQuery.where("id", "in", input.kanbanIds);++ const kanbans = await kanbanQuery.orderBy("id").forUpdate().execute();++ if (input.mode === "scan" && kanbans.length === 0) {+ throw new NotFoundError("Kanban not found");+ }++ const outcomes = new Map<string, KanbanReplenishOutcome>();+ const invalid = (kanbanId: string, reason: KanbanReplenishReason) =>+ outcomes.set(kanbanId, { kanbanId, outcome: "invalid", reason });++ let candidates = kanbans.filter((kanban) => {+ if (kanban.replenishmentSystem !== "Transfer") {+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.notTransfer);+ return false;+ }+ if (!kanban.fromStorageUnitId || !kanban.storageUnitId) {+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.missingStorageUnit);+ return false;+ }+ if (input.mode === "level" && kanban.replenishmentLevel === null) {+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.notArmed);+ return false;+ }+ return true;+ });++ // CWE-639: both storage units must belong to this company and to the+ // kanban's own location — never trust the stored ids.+ const storageUnitIds = [+ ...new Set(+ candidates.flatMap((kanban) => [+ kanban.fromStorageUnitId!,+ kanban.storageUnitId!+ ])+ )+ ];+ const storageUnits =+ storageUnitIds.length > 0+ ? await trx+ .selectFrom("storageUnit")+ .select(["id", "name", "locationId"])+ .where("companyId", "=", companyId)+ .where("id", "in", storageUnitIds)+ .execute()+ : [];+ const storageUnitById = new Map(storageUnits.map((su) => [su.id, su]));++ candidates = candidates.filter((kanban) => {+ const from = storageUnitById.get(kanban.fromStorageUnitId!);+ const to = storageUnitById.get(kanban.storageUnitId!);+ if (+ !from ||+ !to ||+ from.locationId !== kanban.locationId ||+ to.locationId !== kanban.locationId+ ) {+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.foreignStorageUnit);+ return false;+ }+ return true;+ });++ // Drop a kanban whose item cannot be read before sizing any transfer, so+ // the level loop below never counts supply for a transfer it will not write.+ const itemIds = [...new Set(candidates.map((kanban) => kanban.itemId))];+ const items =+ itemIds.length > 0+ ? await trx+ .selectFrom("item")+ .select([+ "id",+ "readableIdWithRevision",+ "itemTrackingType",+ "unitOfMeasureCode"+ ])+ .where("companyId", "=", companyId)+ .where("id", "in", itemIds)+ .execute()+ : [];+ const itemById = new Map(items.map((item) => [item.id, item]));++ candidates = candidates.filter((kanban) => {+ if (!itemById.has(kanban.itemId)) {+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.missingItem);+ return false;+ }+ return true;+ });++ // Level mode moves enough whole kanban quantities to reach the level in+ // one signal. Two kanbans can watch the same item at the same To storage+ // unit; `addedInbound` carries what this call has already created there,+ // so the second kanban sees the first one's transfer as supply.+ const projectedByKanban = new Map<string, number>();+ const transferQuantityByKanban = new Map<string, number>();+ if (input.mode === "level" && candidates.length > 0) {+ const projected = await sql<{+ kanbanId: string;+ replenishmentLevel: number;+ projectedQuantity: number;+ }>`+ SELECT * FROM get_kanban_projected_quantities(+ ${companyId},+ ${candidates.map((kanban) => kanban.id)}::text[]+ )+ `.execute(trx);+ const baseByKanban = new Map(+ projected.rows.map((row) => [+ row.kanbanId,+ Number(row.projectedQuantity)+ ])+ );++ const addedInbound = new Map<string, number>();+ candidates = candidates.filter((kanban) => {+ const key = `${kanban.itemId}:${kanban.storageUnitId}`;+ const projectedQuantity =+ (baseByKanban.get(kanban.id) ?? 0) + (addedInbound.get(key) ?? 0);+ projectedByKanban.set(kanban.id, projectedQuantity);+ const quantityToMove = levelReplenishmentQuantity(+ projectedQuantity,+ Number(kanban.replenishmentLevel),+ kanban.quantity+ );+ if (quantityToMove <= 0) {+ outcomes.set(kanban.id, {+ kanbanId: kanban.id,+ outcome: "at-level",+ projectedQuantity+ });+ return false;+ }+ transferQuantityByKanban.set(kanban.id, quantityToMove);+ addedInbound.set(key, (addedInbound.get(key) ?? 0) + quantityToMove);+ return true;+ });+ }+ // A scan always moves one kanban quantity.+ const transferQuantity = (kanban: { id: string; quantity: number }) =>+ transferQuantityByKanban.get(kanban.id) ?? kanban.quantity;++ if (candidates.length === 0) {+ return {+ results: kanbans.map((kanban) => outcomes.get(kanban.id)!),+ created: [] as KanbanReplenishOutcome[]+ };+ }++ let scannerName = "unknown user";+ if (input.mode === "scan") {+ const user = await trx+ .selectFrom("user")+ .select("fullName")+ .where("id", "=", userId)+ .executeTakeFirst();+ // A user with no last name has a fullName ending in a space.+ scannerName = user?.fullName?.trim() || scannerName;+ }++ const headers: Insertable<KyselyDatabase["stockTransfer"]>[] = [];+ for (const kanban of candidates) {+ const item = itemById.get(kanban.itemId)!;+ const stockTransferId = await sequence.getNextSequence(+ trx,+ "stockTransfer",+ companyId+ );+ const note = kanbanReplenishmentNote({+ itemReadableId: item.readableIdWithRevision ?? kanban.itemId,+ fromStorageUnitName:+ storageUnitById.get(kanban.fromStorageUnitId!)?.name ?? "",+ toStorageUnitName:+ storageUnitById.get(kanban.storageUnitId!)?.name ?? "",+ quantity: transferQuantity(kanban),+ unitOfMeasureCode: item.unitOfMeasureCode,+ signal:+ input.mode === "scan"+ ? { type: "scan", userName: scannerName }+ : {+ type: "level",+ replenishmentLevel: Number(kanban.replenishmentLevel),+ projectedQuantity: projectedByKanban.get(kanban.id) ?? 0+ }+ });+ headers.push({+ stockTransferId,+ locationId: kanban.locationId,+ status: "Released" as const,+ companyId,+ kanbanId: kanban.id,+ notes: toJson(note),+ createdBy: userId+ });+ }++ const inserted = await trx+ .insertInto("stockTransfer")+ .values(headers)+ .returning(["id", "kanbanId", "stockTransferId"])+ .execute();+ const headerByKanban = new Map(+ inserted.map((header) => [header.kanbanId!, header])+ );++ const lines = candidates.flatMap((kanban) => {+ const item = itemById.get(kanban.itemId)!;+ const header = headerByKanban.get(kanban.id)!;+ const draft: StockTransferLineDraft = {+ itemId: kanban.itemId,+ fromStorageUnitId: kanban.fromStorageUnitId,+ toStorageUnitId: kanban.storageUnitId,+ quantity: transferQuantity(kanban),+ requiresSerialTracking: item.itemTrackingType === "Serial",+ requiresBatchTracking: item.itemTrackingType === "Batch"+ };+ return expandSerialTrackedLines([draft]).map((line) => ({+ itemId: line.itemId,+ fromStorageUnitId: line.fromStorageUnitId ?? null,+ toStorageUnitId: line.toStorageUnitId ?? null,+ quantity: line.quantity ?? 0,+ requiresSerialTracking: line.requiresSerialTracking ?? false,+ requiresBatchTracking: line.requiresBatchTracking ?? false,+ stockTransferId: header.id,+ companyId,+ createdBy: userId+ }));+ });++ if (lines.length > 0) {+ await trx.insertInto("stockTransferLine").values(lines).execute();+ }++ const createdOutcomes: KanbanReplenishOutcome[] = [];+ for (const kanban of candidates) {+ const header = headerByKanban.get(kanban.id)!;+ const outcome: KanbanReplenishOutcome = {+ kanbanId: kanban.id,+ outcome: "created",+ id: header.id,+ stockTransferId: header.stockTransferId+ };+ outcomes.set(kanban.id, outcome);+ createdOutcomes.push(outcome);+ }++ return {+ results: kanbans.map((kanban) => outcomes.get(kanban.id)!),+ created: createdOutcomes+ };+ });++ for (const outcome of created) {+ if (outcome.outcome !== "created") continue;+ logger.info("Kanban replenishment created", {+ companyId,+ kanbanId: outcome.kanbanId,+ stockTransferId: outcome.stockTransferId,+ mode: input.mode+ });+ }++ return { results };+ }+ type Enums = Database["public"]["Enums"];++ type AccountDefaults = Database["public"]["Tables"]["accountDefault"]["Row"];++ type JournalLineInsert = Database["public"]["Tables"]["journalLine"]["Insert"];++ /** A journal line and its dimension values, by entity type. The caller adds+ * the journal and the company. */+ export type ReceiptJournalLine = Omit<+ JournalLineInsert,+ "journalId" | "companyId" | "createdBy"+ > & {+ dimensions: JournalLineDimensionValues;+ };++ /** One purchase order receipt line, as the posting reads it. */+ export type PurchaseReceiptLine = {+ purchaseOrderLineId: string | null;+ itemId: string | null;+ /** Signed. Null and NaN are read as 0 by the caller. */+ quantity: number;+ unitPrice: number | null;+ /** No item, or an item with no tracking type, is Inventory. */+ itemTrackingType: Enums["itemTrackingType"] | null | undefined;+ replenishmentSystem: Enums["itemReplenishmentSystem"] | null | undefined;+ itemPostingGroupId: string | null;+ locationId: string | null;+ /** The process of an outside processing line's job operation. */+ processId: string | null;+ };++ /** What a purchase order line was invoiced before it was received. */+ export type InvoiceFirstBasis = {+ /** Invoiced and not yet received, in inventory units, per PO line. */+ quantity: Map<string, number>;+ /** The unit cost the invoice accrued on GR/IR, per PO line. */+ unitCost: Map<string, number>;+ };++ export type PurchaseReceiptLineCost = {+ quantity: number;+ /** The line puts stock on (or takes it off) a cost layer. */+ createsLayers: boolean;+ /** Price × quantity and the line's share of the order's shipping. */+ poCost: number;+ /** The quantity claimed by an invoice posted before the receipt, valued at+ * the invoice's accrual cost. Positive lines only. */+ invoiceFirstQuantity: number;+ invoiceFirstCost: number;+ /** The rest of the line, at its PO unit cost. */+ normalQuantity: number;+ normalCost: number;+ /** What the line books: the PO cost of a negative line, the invoice-first+ * and normal portions of a positive one. */+ cost: number;+ };++ function trackingType(line: Pick<PurchaseReceiptLine, "itemTrackingType">) {+ return line.itemTrackingType ?? "Inventory";+ }++ /**+ * The cost of each line, in the order given. The shipping is shared by each+ * line's PO value. A positive line first claims the quantity its PO line was+ * invoiced before receipt, at the accrual unit cost; a later line of the same+ * PO line claims what is left. A missing accrual cost claims nothing.+ */+ export function purchaseReceiptLineCosts(+ lines: PurchaseReceiptLine[],+ {+ shippingCost,+ isOutsideProcessing,+ invoiceFirst+ }: {+ /** In base currency. */+ shippingCost: number;+ isOutsideProcessing: boolean;+ invoiceFirst?: InvoiceFirstBasis;+ }+ ): PurchaseReceiptLineCost[] {+ const totalLinesCost = lines.reduce(+ (sum, line) => sum + Math.abs(line.quantity) * (line.unitPrice ?? 0),+ 0+ );+ const unclaimed = new Map(invoiceFirst?.quantity);+ return lines.map((line) => {+ const absQuantity = Math.abs(line.quantity);+ const lineCost = absQuantity * (line.unitPrice ?? 0);+ const share = totalLinesCost === 0 ? 0 : lineCost / totalLinesCost;+ const poCost = lineCost + shippingCost * share;+ const poUnitCost = absQuantity > 0 ? poCost / absQuantity : 0;++ let invoiceFirstQuantity = 0;+ let accrualUnitCost = 0;+ const poLineId = line.purchaseOrderLineId;+ if (line.quantity >= 0 && poLineId && unclaimed.has(poLineId)) {+ const remaining = unclaimed.get(poLineId)!;+ const claimed = Math.min(absQuantity, remaining);+ const unitCost = invoiceFirst?.unitCost.get(poLineId);+ // A recorded accrual is claimed even at zero unit cost (a zero-priced+ // invoice); only a missing one leaves the line at PO cost.+ if (claimed > 0 && unitCost !== undefined) {+ invoiceFirstQuantity = claimed;+ accrualUnitCost = unitCost;+ unclaimed.set(poLineId, remaining - claimed);+ }+ }+ const invoiceFirstCost = invoiceFirstQuantity * accrualUnitCost;+ const normalQuantity = absQuantity - invoiceFirstQuantity;+ const normalCost = normalQuantity * poUnitCost;++ return {+ quantity: line.quantity,+ createsLayers:+ trackingType(line) !== "Non-Inventory" &&+ !isOutsideProcessing &&+ Boolean(line.itemId) &&+ absQuantity > 0,+ poCost,+ invoiceFirstQuantity,+ invoiceFirstCost,+ normalQuantity,+ normalCost,+ cost: line.quantity < 0 ? poCost : invoiceFirstCost + normalCost+ };+ });+ }++ /** A fixed asset purchase order line received on the receipt. */+ export type FixedAssetReceiptLine = {+ purchaseOrderLineId: string;+ quantity: number;+ cost: number;+ /** The asset class's asset account. */+ assetAccountId: string;+ fixedAssetClassId: string | null;+ locationId: string | null;+ };++ /**+ * The journal lines of a purchase order receipt: one pair per receipt line+ * with a quantity, then one pair per fixed asset line. A line books `cost`:+ * the cost its layers relieved or stored when the caller knows it, else its+ * `purchaseReceiptLineCosts` cost.+ */+ export function buildPurchaseReceiptJournalLines({+ documentId,+ externalDocumentId,+ isOutsideProcessing,+ supplierId,+ supplierTypeId,+ accounts,+ lines,+ fixedAssets+ }: {+ documentId: string;+ /** The supplier's reference on the purchase order. */+ externalDocumentId: string | null;+ isOutsideProcessing: boolean;+ supplierId: string | null;+ supplierTypeId: string | null;+ accounts: Pick<+ AccountDefaults,+ | "goodsReceivedNotInvoicedAccount"+ | "workInProgressAccount"+ | "indirectCostAccount"+ | "rawMaterialsAccount"+ | "finishedGoodsAccount"+ >;+ lines: (PurchaseReceiptLine & { cost: number })[];+ fixedAssets: FixedAssetReceiptLine[];+ }): ReceiptJournalLine[] {+ const journalLines: ReceiptJournalLine[] = [];+ const pair = (+ purchaseOrderLineId: string | null,+ quantity: number,+ dimensions: ReceiptJournalLine["dimensions"]+ ) => ({+ quantity: round(quantity),+ documentType: "Receipt" as const,+ documentId,+ externalDocumentId: externalDocumentId ?? undefined,+ documentLineReference: journalReference.to.receipt(+ String(purchaseOrderLineId)+ ),+ journalLineReference: nanoid(),+ dimensions+ });+ const goodsReceived = {+ accountId: accounts.goodsReceivedNotInvoicedAccount,+ description: "Goods Received Not Invoiced"+ };++ for (const line of lines) {+ const absQuantity = Math.abs(line.quantity);+ if (absQuantity <= 0) continue;++ let debitSide: { accountId: string; description: string };+ if (trackingType(line) !== "Non-Inventory" && !isOutsideProcessing) {+ const inventory = resolveInventoryAccount(+ line.replenishmentSystem ?? null,+ accounts+ );+ debitSide = {+ accountId: inventory.account,+ description: inventory.description+ };+ } else if (isOutsideProcessing) {+ debitSide = {+ accountId: accounts.workInProgressAccount,+ description: "WIP Account"+ };+ } else {+ debitSide = {+ accountId: accounts.indirectCostAccount,+ description: "Indirect Cost Account"+ };+ }++ const keys = pair(line.purchaseOrderLineId, absQuantity, {+ SupplierType: supplierTypeId,+ ItemPostingGroup: line.itemPostingGroupId,+ Item: line.itemId,+ Supplier: supplierId,+ Location: line.locationId,+ Process: line.processId+ });+ if (line.quantity < 0) {+ journalLines.push(+ {+ ...goodsReceived,+ ...keys,+ amount: round(debit("liability", line.cost))+ },+ { ...debitSide, ...keys, amount: round(credit("asset", line.cost)) }+ );+ } else {+ journalLines.push(+ { ...debitSide, ...keys, amount: round(debit("asset", line.cost)) },+ {+ ...goodsReceived,+ ...keys,+ amount: round(credit("liability", line.cost))+ }+ );+ }+ }++ for (const asset of fixedAssets) {+ const keys = pair(asset.purchaseOrderLineId, asset.quantity, {+ SupplierType: supplierTypeId,+ ItemPostingGroup: null,+ Item: null,+ Supplier: supplierId,+ Location: asset.locationId,+ Process: null,+ FixedAssetClass: asset.fixedAssetClassId+ });+ journalLines.push(+ {+ accountId: asset.assetAccountId,+ description: "Fixed Asset Acquisition",+ ...keys,+ amount: round(debit("asset", asset.cost))+ },+ {+ ...goodsReceived,+ ...keys,+ amount: round(credit("liability", asset.cost))+ }+ );+ }+ return journalLines;+ }++ /** One sales return receipt line and the value it re-enters stock at. */+ export type SalesReturnReceiptLine = {+ /** The sales return order line. */+ returnLineId: string;+ itemId: string;+ quantity: number;+ cost: number;+ replenishmentSystem: Enums["itemReplenishmentSystem"] | null | undefined;+ itemPostingGroupId: string | null;+ locationId: string | null;+ };++ /** The journal lines of a sales return receipt: inventory against COGS per+ * line with a value. A zero-value re-entry books nothing. */+ export function buildSalesReturnReceiptJournalLines({+ documentId,+ externalDocumentId,+ customerId,+ customerTypeId,+ accounts,+ lines+ }: {+ documentId: string;+ /** The receipt's own external document id. */+ externalDocumentId: string | null;+ customerId: string | null;+ customerTypeId: string | null;+ accounts: Pick<+ AccountDefaults,+ "costOfGoodsSoldAccount" | "rawMaterialsAccount" | "finishedGoodsAccount"+ >;+ lines: SalesReturnReceiptLine[];+ }): ReceiptJournalLine[] {+ return lines.flatMap((line) => {+ if (!(line.cost > 0)) return [];+ const inventory = resolveInventoryAccount(+ line.replenishmentSystem ?? null,+ accounts+ );+ const keys = {+ quantity: round(line.quantity),+ documentType: "Receipt" as const,+ documentId,+ externalDocumentId: externalDocumentId ?? undefined,+ documentLineReference: journalReference.to.receipt(line.returnLineId),+ journalLineReference: nanoid(),+ dimensions: {+ Item: line.itemId,+ ItemPostingGroup: line.itemPostingGroupId,+ Location: line.locationId,+ Customer: customerId,+ CustomerType: customerTypeId+ }+ };+ return [+ {+ accountId: inventory.account,+ description: inventory.description,+ ...keys,+ amount: round(debit("asset", line.cost))+ },+ {+ accountId: accounts.costOfGoodsSoldAccount,+ description: "Cost of Goods Sold",+ ...keys,+ amount: round(credit("expense", line.cost))+ }+ ];+ });+ }+ export async function postRentalReceipt(+ db: Kysely<KyselyDatabase>,+ args: {+ receiptId: string;+ companyId: string;+ userId: string;+ today: string;+ postingDate?: string;+ }+ ): Promise<void> {+ const { receiptId, companyId, userId, today } = args;++ await db.transaction().execute(async (trx) => {+ const returnedAt = args.postingDate ?? today;+ const future = futureReturnError(returnedAt, today);+ if (future) throw new InvalidInputError(future);++ const receipt = await trx+ .selectFrom("receipt")+ .select(["id", "receiptId", "sourceDocumentId", "locationId"])+ .where("id", "=", receiptId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!receipt) throw new NotFoundError("Receipt not found");++ const assetLines = await trx+ .selectFrom("receiptFixedAssetLine")+ .select([+ "id",+ "rentalAgreementLineId",+ "meter",+ "notes",+ "takeOutOfService",+ "outOfServiceReason",+ "residualDestination"+ ])+ .where("receiptId", "=", receiptId)+ .where("companyId", "=", companyId)+ .where("received", "=", true)+ .where("rentalAgreementLineId", "is not", null)+ .orderBy("createdAt")+ .orderBy("id")+ .execute();+ if (assetLines.length === 0) {+ throw new InvalidInputError("Select at least one unit to return");+ }++ if (!receipt.sourceDocumentId) {+ throw new NotFoundError("Rental agreement not found");+ }+ const agreement = await lockAgreement(+ trx,+ companyId,+ receipt.sourceDocumentId+ );+ if (agreement.status !== "Active") {+ throw new InvalidInputError(+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are returned from an Active agreement`+ );+ }++ const lineIds = assetLines.map((line) => line.rentalAgreementLineId!);+ const lines = await trx+ .selectFrom("rentalAgreementLine")+ .select([+ "id",+ "rentalAgreementId",+ "status",+ "lessorClassification",+ "fixedAssetId",+ "trackedEntityId"+ ])+ .where("id", "in", lineIds)+ .where("companyId", "=", companyId)+ .execute();+ const linesById = new Map(lines.map((line) => [line.id, line]));+ const assetIds = lines+ .map((line) => line.fixedAssetId)+ .filter((id): id is string => id !== null);+ const assets =+ assetIds.length === 0+ ? []+ : await trx+ .selectFrom("fixedAsset")+ .select(["id", "fixedAssetId", "name"])+ .where("id", "in", assetIds)+ .where("companyId", "=", companyId)+ .execute();+ const assetsById = new Map(assets.map((asset) => [asset.id, asset]));++ const units = assetLines.map((assetLine) => {+ const lineId = assetLine.rentalAgreementLineId!;+ const line = linesById.get(lineId);+ const asset = line?.fixedAssetId+ ? assetsById.get(line.fixedAssetId)+ : undefined;+ const label = unitLabel(asset, lineId);+ if (!line || line.rentalAgreementId !== agreement.id) {+ throw new NotFoundError("Rental agreement line not found");+ }+ const statusProblem = receiptReturnError(label, line.status);+ if (statusProblem) throw new InvalidInputError(statusProblem);++ const parsed = unitReturnValidator.safeParse({+ rentalAgreementLineId: lineId,+ returnedAt,+ meterIn: assetLine.meter === null ? null : Number(assetLine.meter),+ returnNotes: assetLine.notes,+ takeOutOfService: assetLine.takeOutOfService,+ outOfServiceReason: assetLine.outOfServiceReason,+ residualDestination: assetLine.residualDestination+ });+ if (!parsed.success) {+ throw new InvalidInputError(+ `${label}: ${parsed.error.issues[0]?.message ?? "invalid return"}`+ );+ }+ const unit: RentalUnitReturn = parsed.data;+ return { line, unit };+ });++ for (const { line, unit } of units) {+ const { fixedAssetId } = await returnRentalUnit(trx, {+ agreement,+ unit,+ companyId,+ userId,+ today,+ locationId: receipt.locationId ?? undefined+ });++ if (fixedAssetId && receipt.locationId) {+ await trx+ .updateTable("fixedAsset")+ .set({+ locationId: receipt.locationId,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", fixedAssetId)+ .where("companyId", "=", companyId)+ .execute();+ }++ if (line.lessorClassification === "Rental" && line.trackedEntityId) {+ await insertUnitActivity(trx, {+ type: "Rental Return",+ direction: "output",+ sourceDocument: "Receipt",+ sourceDocumentId: receipt.id,+ sourceDocumentReadableId: receipt.receiptId,+ attributes: { Receipt: receipt.id, "Rental Agreement": agreement.id },+ trackedEntityId: line.trackedEntityId,+ companyId,+ userId+ });+ }+ }++ await trx+ .updateTable("receipt")+ .set({+ status: "Posted",+ postingDate: returnedAt,+ postedBy: userId+ })+ .where("id", "=", receiptId)+ .where("companyId", "=", companyId)+ .execute();+ });+ }+ export type ReceiptCostLedgerRow = {+ id: string;+ itemId: string | null;+ quantity: number;+ remainingQuantity: number;+ cost: number;+ supplierId: string | null;+ trackedEntityId: string | null;+ };++ export type RestoringLayer = {+ itemId: string | null;+ quantity: number;+ cost: number;+ supplierId: string | null;+ trackedEntityId: string | null;+ };++ export type ReceiptVoidCostLedgerPlan = {+ consumed: boolean;+ layerIdsToClose: string[];+ restoringLayers: RestoringLayer[];+ };++ // A positive row is a layer the receipt created: the void closes it, unless+ // part of it was already issued or shipped — that stock has moved on, so the+ // void is refused (as the sales return void is) and the remainder is an+ // inventory adjustment. A negative row is what a negative line relieved from+ // older layers: the void puts that stock back as a new layer at the cost that+ // was relieved, the cost the reversing journal credits back to inventory.+ export function planReceiptVoidCostLedger(+ rows: ReceiptCostLedgerRow[]+ ): ReceiptVoidCostLedgerPlan {+ const created = rows.filter((row) => row.quantity > 0);+ const relieved = rows.filter((row) => row.quantity < 0);++ return {+ consumed: created.some(+ (row) => row.quantity - row.remainingQuantity > EPSILON+ ),+ layerIdsToClose: created.map((row) => row.id),+ restoringLayers: relieved.map((row) => ({+ itemId: row.itemId,+ quantity: -row.quantity,+ cost: -row.cost,+ supplierId: row.supplierId,+ trackedEntityId: row.trackedEntityId+ }))+ };+ }++ export const postReceiptInput = z.object({+ type: z.enum(["post", "void"]).default("post"),+ receiptId: z.string(),+ /** The return date of a rental receipt. Other sources ignore it. */+ postingDate: z+ .string()+ .regex(/^\d{4}-\d{2}-\d{2}$/)+ .optional()+ });++ export const postReceiptPermission = {+ update: "inventory"+ } satisfies PermissionRule<z.output<typeof postReceiptInput>>;++ /** Posts or voids a receipt: stock, tracked entities, cost layers and journal. */+ export async function postReceipt(+ ctx: ServiceContext,+ raw: z.input<typeof postReceiptInput>+ ) {+ const { type, receiptId, postingDate } = postReceiptInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ logger.info({ type, receiptId, userId, companyId });+ const fixedAssetWrites = new FixedAssetWrites();+ if (type === "post")+ await assertPostable(db, "receipt", receiptId, companyId);+ try {+ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );+ if (companyRecord.error) throw new Error("Failed to fetch company");+ const companyGroupId = companyRecord.data.companyGroupId;+ // Every receipt that carries value posts a journal: Provisional before+ // the company's accounting cutover, Posted after it. Read here to decide+ // whether to resolve a period, and again inside each transaction, where+ // FOR SHARE holds the status until commit.+ const postingStatus = await journalPostingStatus(db, companyId);++ const [receipt, receiptLines, receiptLineTracking, dimensions] =+ await inOrder([+ // The client is service-role: authorization proved the caller may+ // act in companyId, not that receiptId belongs to it.+ () => maybeSingle(db, "receipt", { id: receiptId, companyId }),+ () => many(db, "receiptLine", { receiptId, companyId }),+ () =>+ many(db, "trackedEntity", {+ attributes: contains({ Receipt: receiptId }),+ companyId+ }),+ () =>+ many(+ db,+ "dimension",+ {+ companyGroupId: companyGroupId!,+ active: true,+ entityType: [+ "SupplierType",+ "Supplier",+ "CustomerType",+ "Customer",+ "ItemPostingGroup",+ "Item",+ "Location",+ "Process",+ "FixedAssetClass"+ ]+ },+ { columns: ["id", "entityType"] }+ )+ ]);++ if (receipt.error) throw new Error("Failed to fetch receipt");+ if (!receipt.data) throw new NotFoundError("Receipt not found");+ const receiptHeader = receipt.data;+ if (receiptLines.error) throw new Error("Failed to fetch receipt lines");+ if (dimensions.error) {+ logger.error("Failed to fetch dimensions", {+ error: dimensions.error+ });+ }++ const dimensionMap = new Map<string, string>();+ for (const dim of dimensions.data ?? []) {+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);+ }++ const itemIds = receiptLines.data.reduce<string[]>((acc, receiptLine) => {+ if (receiptLine.itemId && !acc.includes(receiptLine.itemId)) {+ acc.push(receiptLine.itemId);+ }+ return acc;+ }, []);+ const [items, itemCosts, companySettings] = await inOrder([+ () =>+ many(+ db,+ "item",+ { id: itemIds, companyId },+ { columns: ["id", "itemTrackingType", "replenishmentSystem"] }+ ),+ () =>+ many(+ db,+ "itemCost",+ { itemId: itemIds },+ { columns: ["itemId", "itemPostingGroupId"] }+ ),+ () =>+ single(+ db,+ "companySettings",+ { id: companyId },+ { columns: ["samplingStandard"] }+ )+ ]);+ if (items.error) {+ throw new Error("Failed to fetch items");+ }+ if (itemCosts.error) {+ throw new Error("Failed to fetch item costs");+ }++ const samplingStandard: SamplingStandard =+ (companySettings.data as any)?.samplingStandard ?? "ANSI_Z1_4";++ // Receipt-usage inspection document assignments drive per-feature+ // measurement plans on the created lots.+ const inspectionDocumentAssignments = await many(+ db,+ "itemInspectionDocumentAssignment",+ { companyId, usage: "Receipt", itemId: itemIds },+ { columns: ["itemId", "inspectionDocumentId"] }+ );+ const assignmentByItemId = new Map<string, string>(+ ((inspectionDocumentAssignments.data as any[]) ?? []).map((a) => [+ a.itemId,+ a.inspectionDocumentId+ ])+ );+ const assignedDocumentIds = [...new Set(assignmentByItemId.values())];+ const inspectionFeaturesByDocumentId = new Map<string, any[]>();+ if (assignedDocumentIds.length > 0) {+ const inspectionFeatures = await many(+ db,+ "inspectionFeature",+ { inspectionDocumentId: assignedDocumentIds, companyId },+ {+ columns: [+ "id",+ "inspectionDocumentId",+ "type",+ "samplingPlanType",+ "samplingSampleSize",+ "samplingPercentage",+ "samplingAql",+ "samplingInspectionLevel",+ "samplingSeverity"+ ]+ }+ );+ for (const feature of (inspectionFeatures.data as any[]) ?? []) {+ const list =+ inspectionFeaturesByDocumentId.get(feature.inspectionDocumentId) ??+ [];+ list.push(feature);+ inspectionFeaturesByDocumentId.set(feature.inspectionDocumentId, list);+ }+ }++ // The document's default sampling rule is the lot-level plan base and the+ // fallback for features without their own rule (feature rule -> document+ // default -> All).+ const documentDefaultByDocumentId = new Map<string, any>();+ if (assignedDocumentIds.length > 0) {+ const assignedDocuments = await many(+ db,+ "inspectionDocument",+ { id: assignedDocumentIds, companyId },+ {+ columns: [+ "id",+ "samplingPlanType",+ "samplingSampleSize",+ "samplingPercentage",+ "samplingAql",+ "samplingInspectionLevel",+ "samplingSeverity"+ ]+ }+ );+ for (const doc of (assignedDocuments.data as any[]) ?? []) {+ if (!doc.samplingPlanType) continue;+ documentDefaultByDocumentId.set(doc.id, {+ type: doc.samplingPlanType,+ sampleSize: doc.samplingSampleSize,+ percentage:+ doc.samplingPercentage == null+ ? null+ : Number(doc.samplingPercentage),+ aql: doc.samplingAql == null ? null : Number(doc.samplingAql),+ inspectionLevel: doc.samplingInspectionLevel,+ severity: doc.samplingSeverity+ });+ }+ }++ if (type === "void") {+ if (receiptHeader.status !== "Posted") {+ throw new Error("Can only void posted receipts");+ }++ // The enable reset the cost layers this receipt created.+ await refuseVoidBeforeCutover(+ db,+ companyId,+ receiptHeader.postingDate,+ INVENTORY_VOID_BEFORE_CUTOVER_ERROR+ );++ if (receiptHeader.invoiced) {+ throw new Error(+ "Cannot void a receipt created by a purchase invoice. Void the invoice instead."+ );+ }++ if (receiptHeader.sourceDocument === "Rental Agreement") {+ throw new InvalidInputError(+ "A rental return cannot be voided. Correct the unit by hand."+ );+ }++ if (+ receiptHeader.sourceDocument !== "Purchase Order" &&+ receiptHeader.sourceDocument !== "Sales Return Order"+ ) {+ throw new Error(+ `Void is only supported for receipts with source document "Purchase Order" or "Sales Return Order"`+ );+ }++ if (!receiptHeader.sourceDocumentId) {+ throw new Error("Receipt has no sourceDocumentId");+ }++ if (receiptHeader.sourceDocument === "Sales Return Order") {+ // Reverse a posted sales-return receipt: sign-flip the ledger ++ // journal, roll back the RMA quantities and status ladder, flip the+ // reactivated entities back to Consumed (their pre-receipt state), and+ // zero this receipt's own cost layers so FIFO can never consume voided+ // return stock.+ const salesReturnOrderId = receiptHeader.sourceDocumentId;++ // The PO void path blocks voiding an invoiced receipt; the analogous+ // hazard here is a credit memo. Voiding after crediting would leave+ // quantityCredited > quantityReceived with no path to reconcile.+ const creditMemos = await many(+ db,+ "memo",+ { salesReturnOrderId, companyId, status: neq("Voided") },+ { columns: ["id", "status"] }+ );+ if (creditMemos.error)+ throw new Error("Failed to check for credit memos");+ if ((creditMemos.data ?? []).length > 0) {+ throw new Error(+ "Cannot void: a credit memo exists for this return order. Void it first."+ );+ }++ const [originalItemLedger, originalJournalLines, returnLinesVoid] =+ await inOrder([+ () =>+ many(db, "itemLedger", {+ documentId: receiptId,+ documentType: "Sales Return Receipt",+ companyId+ }),+ () =>+ documentJournalLines(db, companyId, {+ documentId: receiptId,+ documentType: "Receipt"+ }),+ () =>+ many(db, "salesReturnOrderLine", {+ salesReturnOrderId,+ companyId+ })+ ]);+ if (originalItemLedger.error)+ throw new Error("Failed to fetch original item ledger entries");+ if (returnLinesVoid.error)+ throw new Error("Failed to fetch return order lines");++ const reversingItemLedger = (originalItemLedger.data ?? []).map(+ (entry) => ({+ postingDate: today,+ itemId: entry.itemId,+ quantity: -entry.quantity,+ locationId: entry.locationId,+ storageUnitId: entry.storageUnitId,+ entryType:+ entry.entryType === "Positive Adjmt."+ ? ("Negative Adjmt." as const)+ : ("Positive Adjmt." as const),+ documentType: "Sales Return Receipt" as const,+ documentId: entry.documentId,+ externalDocumentId: entry.externalDocumentId,+ trackedEntityId: entry.trackedEntityId,+ createdBy: userId,+ companyId+ })+ );++ const reversingJournalLines = originalJournalLines.map((line) => ({+ accountId: line.accountId,+ description: `VOID: ${line.description ?? ""}`,+ amount: -line.amount,+ quantity: line.quantity == null ? undefined : -line.quantity,+ documentType: line.documentType,+ documentId: line.documentId,+ externalDocumentId: line.externalDocumentId ?? undefined,+ documentLineReference: line.documentLineReference ?? undefined,+ journalLineReference: line.journalLineReference,+ companyId+ }));++ const receivedByLine = new Map<string, number>();+ for (const receiptLine of receiptLines.data ?? []) {+ if (!receiptLine.lineId) continue;+ const qty = Number(receiptLine.receivedQuantity ?? 0);+ receivedByLine.set(+ receiptLine.lineId,+ (receivedByLine.get(receiptLine.lineId) ?? 0) + qty+ );+ }++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted" && reversingJournalLines.length > 0+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ // Refuse to void when this receipt's cost layers were already+ // (partially) consumed — the returned stock moved on (dispositioned,+ // sold, scrapped), so reversing the full receipt would drive stock+ // negative and double-count COGS. The remainder is a manual+ // inventory adjustment, not a void.+ const receiptLayers = await trx+ .selectFrom("costLedger")+ .select(["quantity", "remainingQuantity"])+ .where("documentId", "=", receiptId)+ .where("documentType", "=", "Sales Return Receipt")+ .where("companyId", "=", companyId)+ .forUpdate()+ .execute();+ const consumed = receiptLayers.some(+ (layer) =>+ Number(layer.quantity) > 0 &&+ Number(layer.remainingQuantity) < Number(layer.quantity)+ );+ if (consumed) {+ throw new Error(+ "Cannot void: stock received on this return was already consumed. Correct the remainder with an inventory adjustment instead."+ );+ }++ if (reversingItemLedger.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(reversingItemLedger)+ .execute();+ }++ if (reversingJournalLines.length > 0) {+ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );+ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `VOID Sales Return Receipt ${receiptHeader.receiptId}`,+ postingDate: today,+ companyId,+ sourceType: "Sales Return Receipt",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ await trx+ .insertInto("journalLine")+ .values(+ reversingJournalLines.map((line) => ({+ ...line,+ journalId: journalResult.id+ }))+ )+ .execute();+ }++ await trx+ .updateTable("costLedger")+ .set({ remainingQuantity: 0 })+ .where("documentId", "=", receiptId)+ .where("documentType", "=", "Sales Return Receipt")+ .where("companyId", "=", companyId)+ .execute();++ for await (const [lineId, received] of receivedByLine) {+ const line = returnLinesVoid.data?.find((l) => l.id === lineId);+ if (!line) continue;+ await trx+ .updateTable("salesReturnOrderLine")+ .set({+ quantityReceived: Math.max(+ 0,+ Number(line.quantityReceived ?? 0) - received+ ),+ updatedBy: userId+ })+ .where("id", "=", lineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ const remainingLines = await trx+ .selectFrom("salesReturnOrderLine")+ .select(["quantity", "quantityReceived", "closedComplete"])+ .where("salesReturnOrderId", "=", salesReturnOrderId)+ .execute();+ // Derived status (mirrors getSalesReturnOrderStatus): a void that+ // drops received quantity below the authorized total returns the RMA+ // to To Receive; otherwise it stays Completed.+ const allReceived =+ remainingLines.length > 0 &&+ remainingLines.every(+ (l) =>+ l.closedComplete ||+ Number(l.quantityReceived) >= Number(l.quantity)+ );+ const returnStatus = allReceived+ ? ("Completed" as const)+ : ("To Receive" as const);+ await trx+ .updateTable("salesReturnOrder")+ .set({ status: returnStatus, updatedBy: userId })+ .where("id", "=", salesReturnOrderId)+ .where("companyId", "=", companyId)+ .execute();++ const voidActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Void Receipt",+ sourceDocument: "Receipt",+ sourceDocumentId: receiptId,+ sourceDocumentReadableId: receiptHeader.receiptId,+ attributes: {+ "Sales Return Order": salesReturnOrderId,+ Receipt: receiptId,+ Employee: userId+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();+ const voidActivityId = voidActivity[0]?.id;++ for await (const entity of receiptLineTracking.data ?? []) {+ await trx+ .updateTable("trackedEntity")+ .set({ status: "Consumed" })+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();++ if (voidActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: voidActivityId,+ trackedEntityId: entity.id,+ quantity: entity.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }++ await trx+ .updateTable("receipt")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId+ })+ .where("id", "=", receiptId)+ .where("companyId", "=", companyId)+ .execute();+ });++ return { success: true };+ }++ const [originalItemLedger, originalJournalLines, purchaseOrderLinesVoid] =+ await inOrder([+ () =>+ many(db, "itemLedger", {+ documentId: receiptId,+ documentType: "Purchase Receipt",+ companyId+ }),+ () =>+ documentJournalLines(db, companyId, {+ documentId: receiptId,+ documentType: "Receipt"+ }),+ () =>+ many(db, "purchaseOrderLine", {+ purchaseOrderId: receiptHeader.sourceDocumentId+ })+ ]);++ if (originalItemLedger.error)+ throw new Error("Failed to fetch item ledger entries");+ if (purchaseOrderLinesVoid.error)+ throw new Error("Failed to fetch purchase order lines");++ const reversingItemLedger: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ originalItemLedger.data.map((entry) => ({+ postingDate: today,+ itemId: entry.itemId,+ quantity: -entry.quantity,+ locationId: entry.locationId,+ storageUnitId: entry.storageUnitId,+ trackedEntityId: entry.trackedEntityId,+ entryType:+ entry.entryType === "Positive Adjmt."+ ? "Negative Adjmt."+ : entry.entryType === "Negative Adjmt."+ ? "Positive Adjmt."+ : entry.entryType,+ documentType: entry.documentType,+ documentId: entry.documentId,+ externalDocumentId: entry.externalDocumentId,+ createdBy: userId,+ companyId+ }));++ const reversingJournalLines: Omit<+ Database["public"]["Tables"]["journalLine"]["Insert"],+ "journalId"+ >[] = originalJournalLines.map((entry) => ({+ accountId: entry.accountId,+ accrual: entry.accrual,+ description: `VOID: ${entry.description}`,+ // A reversal is a sign flip of an already-posted value, which is+ // exact — no rounding to do.+ amount: -entry.amount,+ quantity: -entry.quantity,+ documentType: entry.documentType,+ documentId: entry.documentId,+ externalDocumentId: entry.externalDocumentId,+ documentLineReference: entry.documentLineReference,+ journalLineReference: entry.journalLineReference,+ companyId+ }));++ const receiptLinesByPurchaseOrderLineId = receiptLines.data.reduce<+ Record<string, Database["public"]["Tables"]["receiptLine"]["Row"][]>+ >((acc, receiptLine) => {+ if (receiptLine.lineId) {+ acc[receiptLine.lineId] = [+ ...(acc[receiptLine.lineId] ?? []),+ receiptLine+ ];+ }+ return acc;+ }, {});++ const purchaseOrderLineUpdatesVoid = purchaseOrderLinesVoid.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ >+ >((acc, purchaseOrderLine) => {+ const receiptLinesForPoLine =+ receiptLinesByPurchaseOrderLineId[purchaseOrderLine.id];+ if (+ receiptLinesForPoLine &&+ receiptLinesForPoLine.length > 0 &&+ purchaseOrderLine.purchaseQuantity &&+ purchaseOrderLine.purchaseQuantity > 0+ ) {+ const receivedQuantityInPurchaseUnit =+ receiptLinesForPoLine.reduce((sum, receiptLine) => {+ const safe =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;+ return sum + safe;+ }, 0) / (receiptLinesForPoLine[0]!.conversionFactor ?? 1);++ const newQuantityReceived = Math.max(+ 0,+ (purchaseOrderLine.quantityReceived ?? 0) -+ receivedQuantityInPurchaseUnit+ );++ const receivedComplete =+ newQuantityReceived >= purchaseOrderLine.purchaseQuantity;++ acc[purchaseOrderLine.id] = {+ quantityReceived: newQuantityReceived,+ receivedComplete+ };+ }+ return acc;+ }, {});++ // Reverse FA PO line received status on void+ const faPoLinesForVoid = purchaseOrderLinesVoid.data.filter(+ (pol) =>+ pol.purchaseOrderLineType === "Fixed Asset" &&+ pol.assetId &&+ pol.receivedComplete+ );++ // CIP cost rows this receipt wrote, summed per asset. Their presence is+ // the durable record that the posting went into Construction in+ // Progress, even if the asset has since been capitalized into a+ // depreciating class.+ const cipCostByAssetVoid = new Map<string, number>();+ if (faPoLinesForVoid.length > 0) {+ const cipCostRowsVoid = await many(+ db,+ "fixedAssetCipCost",+ { companyId, sourceDocumentId: receiptId },+ { columns: ["fixedAssetId", "amount"] }+ );+ if (cipCostRowsVoid.error)+ throw new Error("Failed to fetch fixed asset CIP costs");+ for (const row of cipCostRowsVoid.data) {+ cipCostByAssetVoid.set(+ row.fixedAssetId,+ (cipCostByAssetVoid.get(row.fixedAssetId) ?? 0) + Number(row.amount)+ );+ }+ }+ // Reduced acquisition cost per CIP asset, written inside the void transaction+ const cipAssetUpdatesVoid = new Map<string, number>();++ type VoidedAsset = Pick<+ Tables["fixedAsset"]["Row"],+ "id" | "acquisitionCost" | "status"+ > & {+ fixedAssetClass: Pick<+ Tables["fixedAssetClass"]["Row"],+ "isConstructionInProgress"+ > | null;+ };+ const voidedAssets: { data: VoidedAsset[] } =+ faPoLinesForVoid.length > 0+ ? await many<"fixedAsset", VoidedAsset>(+ db,+ "fixedAsset",+ {+ companyId,+ id: faPoLinesForVoid.map((line) => line.assetId!)+ },+ {+ columns: ["id", "acquisitionCost", "status"],+ embed: {+ fixedAssetClass: {+ table: "fixedAssetClass",+ via: "fixedAssetClassId",+ columns: ["isConstructionInProgress"]+ }+ }+ }+ )+ : { data: [] };+ const voidedAssetById = new Map(+ voidedAssets.data.map((asset) => [asset.id, asset])+ );++ for (const faPoLine of faPoLinesForVoid) {+ const hasReceiptEntries = originalJournalLines.some(+ (jl) =>+ jl.documentLineReference ===+ journalReference.to.receipt(faPoLine.id)+ );++ if (hasReceiptEntries) {+ purchaseOrderLineUpdatesVoid[faPoLine.id] = {+ quantityReceived: 0,+ receivedComplete: false+ };++ const receiptCost = originalJournalLines+ .filter(+ (jl) =>+ jl.documentLineReference ===+ journalReference.to.receipt(faPoLine.id) &&+ (jl.amount ?? 0) > 0+ )+ .reduce((sum, jl) => sum + Math.abs(jl.amount ?? 0), 0);++ const asset = voidedAssetById.get(faPoLine.assetId!);+ if (asset) {+ fixedAssetWrites.overlay(faPoLine.assetId!, asset);+ const isConstructionInProgress =+ cipCostByAssetVoid.has(faPoLine.assetId!) ||+ Boolean(asset.fixedAssetClass?.isConstructionInProgress);+ if (isConstructionInProgress) {+ if (asset.status !== "Under Construction") {+ throw new Error(+ "Asset was capitalized; reverse the capitalization first"+ );+ }+ const cipCost = cipCostByAssetVoid.get(faPoLine.assetId!);+ if (cipCost !== undefined) {+ cipAssetUpdatesVoid.set(+ faPoLine.assetId!,+ Math.max(0, round(Number(asset.acquisitionCost) - cipCost))+ );+ continue;+ }+ // No CIP cost row for this receipt (posted before the class+ // was a CIP class): the cost still came in through this+ // receipt, so back it out like any other asset below rather+ // than leave it on the asset.+ }++ const newAcquisitionCost = Math.max(+ 0,+ Number(asset.acquisitionCost) - receiptCost+ );+ const faUpdate: Database["public"]["Tables"]["fixedAsset"]["Update"] =+ {+ acquisitionCost: newAcquisitionCost,+ updatedBy: userId+ };+ if (newAcquisitionCost === 0 && asset.status === "Active") {+ faUpdate.status = "Draft";+ faUpdate.acquisitionDate = null;+ faUpdate.depreciationStartDate = null;+ }+ fixedAssetWrites.patch(faPoLine.assetId!, faUpdate);+ }+ }+ }++ const projectedPurchaseOrderLines = purchaseOrderLinesVoid.data.map(+ (line) => {+ const update = purchaseOrderLineUpdatesVoid[line.id];+ if (update && update.quantityReceived !== undefined) {+ return {+ ...line,+ quantityReceived: update.quantityReceived+ };+ }+ return line;+ }+ );++ const areAllLinesInvoicedProjected = projectedPurchaseOrderLines.every(+ (line) => {+ if (line.purchaseOrderLineType === "Comment") return true;+ const target = line.purchaseQuantity ?? 0;+ if (target <= 0) return true;+ return (line.quantityInvoiced ?? 0) >= target;+ }+ );++ const areAllLinesReceivedProjected = projectedPurchaseOrderLines.every(+ (line) => {+ if (+ line.purchaseOrderLineType === "Comment" ||+ line.purchaseOrderLineType === "G/L Account" ||+ line.purchaseOrderLineType === "Service"+ )+ return true;+ const target = line.purchaseQuantity ?? 0;+ if (target <= 0) return true;+ return (line.quantityReceived ?? 0) >= target;+ }+ );++ let purchaseOrderStatusVoid: Database["public"]["Tables"]["purchaseOrder"]["Row"]["status"] =+ "To Receive and Invoice";+ if (areAllLinesInvoicedProjected && areAllLinesReceivedProjected) {+ purchaseOrderStatusVoid = "Completed";+ } else if (areAllLinesInvoicedProjected) {+ purchaseOrderStatusVoid = "To Receive";+ } else if (areAllLinesReceivedProjected) {+ purchaseOrderStatusVoid = "To Invoice";+ }++ const trackedEntityUpdatesVoid =+ receiptLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ // Voiding restores the lot, but a lot with nothing in it must not+ // come back Available — that is the zero-quantity husk the drain+ // rule forbids. Scrapped/Rejected are terminal quality states and+ // must survive a void, so keep them; everything else returns to+ // Available (the helper then drains a zero-quantity lot to Consumed).+ acc[trackedEntity.id] = settleQuantity({+ quantity: Number(trackedEntity.quantity ?? 0),+ status:+ trackedEntity.status === "Scrapped" ||+ trackedEntity.status === "Rejected"+ ? trackedEntity.status+ : ("Available" as const)+ });+ return acc;+ }, {}) ?? {};++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ // The cost layers this receipt wrote. Without this, a voided+ // receipt's layer stayed open and later issues consumed stock that+ // was never there.+ const receiptCostLedger = await trx+ .selectFrom("costLedger")+ .select([+ "id",+ "itemId",+ "quantity",+ "remainingQuantity",+ "cost",+ "supplierId",+ "trackedEntityId"+ ])+ .where("documentId", "=", receiptId)+ .where("documentType", "=", "Purchase Receipt")+ .where("adjustment", "=", false)+ .where("companyId", "=", companyId)+ .forUpdate()+ .execute();+ const costLedgerPlan = planReceiptVoidCostLedger(+ receiptCostLedger.map((row) => ({+ ...row,+ quantity: Number(row.quantity),+ remainingQuantity: Number(row.remainingQuantity),+ cost: Number(row.cost)+ }))+ );+ if (costLedgerPlan.consumed) {+ throw new Error(+ "Cannot void: stock received on this receipt was already consumed. Correct the remainder with an inventory adjustment instead."+ );+ }+ if (costLedgerPlan.layerIdsToClose.length > 0) {+ await trx+ .updateTable("costLedger")+ .set({ remainingQuantity: 0 })+ .where("id", "in", costLedgerPlan.layerIdsToClose)+ .where("companyId", "=", companyId)+ .execute();+ }+ if (costLedgerPlan.restoringLayers.length > 0) {+ await trx+ .insertInto("costLedger")+ .values(+ costLedgerPlan.restoringLayers.map((layer) => ({+ itemLedgerType: "Purchase" as const,+ costLedgerType: "Direct Cost" as const,+ adjustment: false,+ documentType: "Purchase Receipt" as const,+ documentId: receiptId,+ externalDocumentId:+ receiptHeader.externalDocumentId ?? undefined,+ itemId: layer.itemId,+ trackedEntityId: layer.trackedEntityId,+ quantity: layer.quantity,+ cost: layer.cost,+ remainingQuantity: layer.quantity,+ supplierId: layer.supplierId,+ companyId,+ postingDate: today+ }))+ )+ .execute();+ }++ await fixedAssetWrites.apply(trx, companyId);+ for await (const [purchaseOrderLineId, update] of Object.entries(+ purchaseOrderLineUpdatesVoid+ )) {+ await trx+ .updateTable("purchaseOrderLine")+ .set(update)+ .where("id", "=", purchaseOrderLineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ await trx+ .updateTable("purchaseOrder")+ .set({ status: purchaseOrderStatusVoid })+ .where("id", "=", receiptHeader.sourceDocumentId!)+ .where("companyId", "=", companyId)+ .execute();++ for (const [assetId, acquisitionCost] of cipAssetUpdatesVoid) {+ await trx+ .deleteFrom("fixedAssetCipCost")+ .where("companyId", "=", companyId)+ .where("sourceDocumentId", "=", receiptId)+ .where("fixedAssetId", "=", assetId)+ .execute();+ await trx+ .updateTable("fixedAsset")+ .set({ acquisitionCost, updatedBy: userId })+ .where("id", "=", assetId)+ .where("companyId", "=", companyId)+ .execute();+ }++ if (reversingJournalLines.length > 0) {+ const voidJournalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const journal = await trx+ .insertInto("journal")+ .values({+ journalEntryId: voidJournalEntryId,+ accountingPeriodId,+ description: `VOID Purchase Receipt ${receiptHeader.receiptId}`,+ postingDate: today,+ companyId,+ sourceType: "Purchase Receipt",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ const journalId = journal[0]!.id;+ if (!journalId) throw new Error("Failed to insert journal");++ await trx+ .insertInto("journalLine")+ .values(+ reversingJournalLines.map((journalLine) => ({+ ...journalLine,+ journalId+ }))+ )+ .execute();+ }++ if (reversingItemLedger.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(reversingItemLedger)+ .execute();+ }++ if (Object.keys(trackedEntityUpdatesVoid).length > 0) {+ const voidActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Void Receipt",+ sourceDocument: "Receipt",+ sourceDocumentId: receiptId,+ sourceDocumentReadableId: receiptHeader.receiptId,+ attributes: {+ "Purchase Order": receiptHeader.sourceDocumentId,+ Receipt: receiptId,+ Employee: userId+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();++ const voidActivityId = voidActivity[0]!.id;++ for await (const [id, update] of Object.entries(+ trackedEntityUpdatesVoid+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ if (voidActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: voidActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }++ await trx+ .updateTable("receipt")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId+ })+ .where("id", "=", receiptId)+ .where("companyId", "=", companyId)+ .execute();+ });++ return { success: true };+ }++ if (receiptHeader.status === "Voided") {+ throw new Error("Cannot post a voided receipt");+ }++ switch (receiptHeader.sourceDocument) {+ case "Purchase Order": {+ if (!receiptHeader.sourceDocumentId)+ throw new Error("Receipt has no sourceDocumentId");++ const [purchaseOrder, purchaseOrderLines, purchaseOrderDelivery] =+ await inOrder([+ () =>+ single(db, "purchaseOrder", {+ companyId,+ id: receiptHeader.sourceDocumentId+ }),+ () =>+ many(db, "purchaseOrderLine", {+ companyId,+ purchaseOrderId: receiptHeader.sourceDocumentId+ }),+ () =>+ single(+ db,+ "purchaseOrderDelivery",+ { companyId, id: receiptHeader.sourceDocumentId },+ { columns: ["supplierShippingCost"] }+ )+ ]);+ if (purchaseOrder.error)+ throw new Error("Failed to fetch purchase order");+ if (purchaseOrderLines.error)+ throw new Error("Failed to fetch purchase order lines");+ if (purchaseOrderDelivery.error)+ throw new Error("Failed to fetch purchase order delivery");++ // supplierShippingCost is a supplier-currency amount and the order's+ // exchangeRate is foreign-units-per-base, so supplier -> base is+ // DIVIDE. It is mixed into base line costs below and becomes the+ // cost-ledger layer value, so multiplying inflated every foreign+ // receipt's capitalised cost by the rate squared. Matches+ // post-purchase-invoice (supplierShippingCost) and migration+ // 20260702061504, which fixed the same expression in the+ // purchaseOrders/purchaseInvoices views.+ const shippingCost =+ (purchaseOrderDelivery.data?.supplierShippingCost ?? 0) /+ (purchaseOrder.data?.exchangeRate || 1);++ const supplier = await single(db, "supplier", {+ id: purchaseOrder.data.supplierId,+ companyId+ });+ if (supplier.error) throw new Error("Failed to fetch supplier");++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ // Cost layers created by this receipt (the receipt is the sole creator+ // of purchase layers; the invoice adjusts them later). Rows flagged+ // isInvoiceFirst carry their PO line so the flush can exclude quantity+ // already represented by a legacy invoice-created layer (documents+ // posted before receipt-created layers shipped).+ const costLedgerInserts: (Database["public"]["Tables"]["costLedger"]["Insert"] & {+ isInvoiceFirst?: boolean;+ poLineId?: string;+ })[] = [];+ // Negative receipt lines (by index) consume layers at layer cost+ // inside the transaction (calculateCOGS), and book what they+ // relieved. The PO cost is used when no layers yield a cost.+ const negativeReceiptConsumptions: {+ index: number;+ itemId: string;+ quantity: number;+ }[] = [];++ const isOutsideProcessing =+ purchaseOrder.data.purchaseOrderType === "Outside Processing";++ const processIdByJobOperationId = new Map<string, string>();+ if (isOutsideProcessing) {+ const jobOpIds = purchaseOrderLines.data+ .map((pol) => pol.jobOperationId)+ .filter((id): id is string => !!id);+ if (jobOpIds.length > 0) {+ const jobOps = await many(+ db,+ "jobOperation",+ { companyId, id: jobOpIds },+ { columns: ["id", "processId"] }+ );+ for (const op of jobOps.data ?? []) {+ if (op.processId)+ processIdByJobOperationId.set(op.id, op.processId);+ }+ }+ }++ const receiptLinesByPurchaseOrderLineId = receiptLines.data.reduce<+ Record<string, Database["public"]["Tables"]["receiptLine"]["Row"][]>+ >((acc, receiptLine) => {+ if (receiptLine.lineId) {+ acc[receiptLine.lineId] = [+ ...(acc[receiptLine.lineId] ?? []),+ receiptLine+ ];+ }+ return acc;+ }, {});++ // Build one inspection lot per receiptLine whose item has a Receipt-usage+ // inspection plan (a document assignment). The assigned document is the+ // plan for the receipt; without one, no lot is created. Compute the+ // sampling plan snapshot from the company's chosen standard and the+ // document's default plan (or "Inspect All" when the document has none).+ const inspectionInserts: Array<Record<string, any>> = [];+ // Per-feature resolved plans, keyed by receiptLineId until the lot ids+ // exist (they are joined after the insert returns ids).+ type InspectionSamplingPlanInsert = {+ inspectionFeatureId: string;+ sampleSize: number;+ acceptanceNumber: number;+ rejectionNumber: number;+ codeLetter: string | null;+ companyId: string;+ createdBy: string;+ };+ const samplingPlanInsertsByReceiptLineId = new Map<+ string,+ Array<InspectionSamplingPlanInsert>+ >();+ for (const receiptLine of receiptLines.data ?? []) {+ if (!receiptLine.itemId) continue;++ // An item is inspected at receipt when it has a Receipt-usage+ // inspection plan (document assignment); without one, no lot.+ const assignedDocumentId =+ assignmentByItemId.get(receiptLine.itemId) ?? null;+ if (!assignedDocumentId) continue;++ const safeReceivedQuantity =+ isNaN(receiptLine.receivedQuantity as any) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;+ if (safeReceivedQuantity <= 0) continue;++ const documentDefault = assignedDocumentId+ ? (documentDefaultByDocumentId.get(assignedDocumentId) ?? null)+ : null;++ const plan = documentDefault ?? {+ type: "All",+ sampleSize: null,+ percentage: null,+ aql: null,+ inspectionLevel: "II",+ severity: "Normal"+ };++ const snapshot = resolveSamplingPlan(+ plan,+ safeReceivedQuantity,+ samplingStandard+ );++ const documentFeatures = assignedDocumentId+ ? (inspectionFeaturesByDocumentId.get(assignedDocumentId) ?? [])+ : [];+ const featurePlans = documentFeatures.map((feature) => ({+ inspectionFeatureId: feature.id,+ resolved: resolveFeatureSamplingPlan(+ feature,+ documentDefault,+ safeReceivedQuantity,+ samplingStandard+ )+ }));+ if (featurePlans.length > 0) {+ samplingPlanInsertsByReceiptLineId.set(+ receiptLine.id,+ featurePlans.map((p) => ({+ inspectionFeatureId: p.inspectionFeatureId,+ sampleSize: p.resolved.sampleSize,+ acceptanceNumber: p.resolved.acceptance,+ rejectionNumber: p.resolved.rejection,+ codeLetter: p.resolved.codeLetter,+ companyId,+ createdBy: userId+ }))+ );+ }++ inspectionInserts.push({+ sourceDocument: "Receipt",+ sourceDocumentId: receiptId,+ sourceDocumentLineId: receiptLine.id,+ sourceDocumentReadableId: receiptHeader.receiptId ?? null,+ itemId: receiptLine.itemId,+ supplierId: purchaseOrder.data.supplierId ?? null,+ lotSize: safeReceivedQuantity,+ samplingStandard,+ samplingPlanType: plan.type,+ // With a document attached, the lot-level sample size is the max+ // across the per-feature plans (SAP-style); Ac/Re remain the+ // item-plan fallback numbers used by the no-document flow.+ sampleSize:+ featurePlans.length > 0+ ? Math.max(...featurePlans.map((p) => p.resolved.sampleSize))+ : snapshot.sampleSize,+ acceptanceNumber: snapshot.acceptance,+ rejectionNumber: snapshot.rejection,+ aql: plan.aql ?? null,+ inspectionLevel: plan.inspectionLevel ?? null,+ severity: plan.severity ?? null,+ codeLetter: snapshot.codeLetter,+ inspectionDocumentId: assignedDocumentId,+ status: "Pending",+ companyId,+ createdBy: userId+ });+ }++ // Tracked entities for items with a Receipt-usage inspection plan stay+ // On Hold after posting (they are released individually by the sample+ // inspection or en masse by lot disposition). Everything else flips to+ // Available.+ const trackedEntityUpdates =+ receiptLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, itemTracking) => {+ const receiptLine = receiptLines.data?.find(+ (receiptLine) =>+ receiptLine.id ===+ (itemTracking.attributes as TrackedEntityAttributes)?.[+ "Receipt Line"+ ]?.toString()+ );++ const safeReceivedQuantity =+ // @ts-ignore - chillllllll+ isNaN(receiptLine?.receivedQuantity) ||+ receiptLine?.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;+ const quantity = receiptLine?.requiresSerialTracking+ ? 1+ : safeReceivedQuantity || itemTracking.quantity;++ const requiresInspection = receiptLine?.itemId+ ? assignmentByItemId.has(receiptLine.itemId)+ : false;++ acc[itemTracking.id] = {+ status: requiresInspection ? "On Hold" : "Available",+ quantity: quantity+ };++ return acc;+ }, {}) ?? {};++ const jobOperationUpdates = isOutsideProcessing+ ? purchaseOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["jobOperation"]["Update"]+ >+ >((acc, purchaseOrderLine) => {+ const receiptLines =+ receiptLinesByPurchaseOrderLineId[purchaseOrderLine.id];+ if (+ receiptLines &&+ receiptLines.length > 0 &&+ purchaseOrderLine.purchaseQuantity &&+ purchaseOrderLine.purchaseQuantity > 0 &&+ purchaseOrderLine.jobOperationId+ ) {+ const recivedQuantityInPurchaseUnit =+ receiptLines.reduce((acc, receiptLine) => {+ const safeReceivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;+ return acc + safeReceivedQuantity;+ }, 0) / (receiptLines[0]!.conversionFactor ?? 1);++ const receivedComplete =+ purchaseOrderLine.receivedComplete ||+ recivedQuantityInPurchaseUnit >=+ (purchaseOrderLine.quantityToReceive ??+ purchaseOrderLine.purchaseQuantity);++ return {+ ...acc,+ [purchaseOrderLine.jobOperationId]: {+ status: receivedComplete ? "Done" : "In Progress"+ }+ };+ }++ return acc;+ }, {})+ : {};++ const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ >+ >((acc, purchaseOrderLine) => {+ const receiptLines =+ receiptLinesByPurchaseOrderLineId[purchaseOrderLine.id];+ if (+ receiptLines &&+ receiptLines.length > 0 &&+ purchaseOrderLine.purchaseQuantity &&+ purchaseOrderLine.purchaseQuantity > 0+ ) {+ const recivedQuantityInPurchaseUnit =+ receiptLines.reduce((acc, receiptLine) => {+ const safeReceivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;+ return acc + safeReceivedQuantity;+ }, 0) / (receiptLines[0]!.conversionFactor ?? 1);++ const newQuantityReceived =+ (purchaseOrderLine.quantityReceived ?? 0) ++ recivedQuantityInPurchaseUnit;++ const receivedComplete =+ purchaseOrderLine.receivedComplete ||+ recivedQuantityInPurchaseUnit >=+ (purchaseOrderLine.quantityToReceive ??+ purchaseOrderLine.purchaseQuantity);++ return {+ ...acc,+ [purchaseOrderLine.id]: {+ quantityReceived: newQuantityReceived,+ receivedComplete,+ receivedDate: today+ }+ };+ }++ return acc;+ }, {});++ // Get account defaults (once for all lines) for the journal entries+ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ // Detect invoice-first scenario: PO lines where qty invoiced > qty received+ const invoiceFirstQtyByPoLine = new Map<string, number>();+ const accrualUnitCostByPoLine = new Map<string, number>();+ const receivedBeforeInvUnitsByPoLine = new Map<string, number>();++ for (const pol of purchaseOrderLines.data) {+ const invoicedInInventoryUnit =+ (pol.quantityInvoiced ?? 0) * (pol.conversionFactor ?? 1);+ const receivedInInventoryUnit =+ (pol.quantityReceived ?? 0) * (pol.conversionFactor ?? 1);+ const invoiceFirstQty = Math.max(+ 0,+ invoicedInInventoryUnit - receivedInInventoryUnit+ );+ if (invoiceFirstQty > 0) {+ invoiceFirstQtyByPoLine.set(pol.id, invoiceFirstQty);+ receivedBeforeInvUnitsByPoLine.set(pol.id, receivedInInventoryUnit);+ }+ }++ if (invoiceFirstQtyByPoLine.size > 0) {+ const accrualDocRefs = [...invoiceFirstQtyByPoLine.keys()].map((id) =>+ journalReference.to.purchaseInvoice(id)+ );++ const accrualJournalLines = await documentJournalLines(+ db,+ companyId,+ {+ documentLineReference: accrualDocRefs,+ accrual: true+ }+ );++ // GR/IR debit entries have non-positive amounts (debit on a+ // liability; zero-priced invoices accrue at exactly 0). Matching+ // the GR/IR account keeps the paired AP credit lines, which are+ // also 0 on zero-priced invoices, out of the quantity sum.+ const accrualCostByPoLine: Record<+ string,+ { totalCost: number; totalQty: number }+ > = {};+ for (const jl of accrualJournalLines) {+ if (+ (jl.amount ?? 0) <= 0 &&+ (jl.quantity ?? 0) > 0 &&+ jl.accountId ===+ accountDefaults.data.goodsReceivedNotInvoicedAccount+ ) {+ const [, poLineId] = (jl.documentLineReference ?? "").split(+ ":"+ ) as [string, string];+ if (!accrualCostByPoLine[poLineId]) {+ accrualCostByPoLine[poLineId] = {+ totalCost: 0,+ totalQty: 0+ };+ }+ accrualCostByPoLine[poLineId].totalCost += Math.abs(+ jl.amount ?? 0+ );+ accrualCostByPoLine[poLineId].totalQty += jl.quantity ?? 0;+ }+ }++ for (const [poLineId, info] of Object.entries(accrualCostByPoLine)) {+ if (info.totalQty > 0) {+ accrualUnitCostByPoLine.set(+ poLineId,+ info.totalCost / info.totalQty+ );+ }+ }++ // Units invoiced before receipt with no accrual to clear stay at+ // PO cost, so GR/IR keeps the difference to the invoice's cost.+ // A service or fixed asset invoice accrues nothing on GR/IR.+ const unaccrued = [...invoiceFirstQtyByPoLine.entries()].filter(+ ([poLineId]) => {+ const lineType = purchaseOrderLines.data.find(+ (pol) => pol.id === poLineId+ )?.purchaseOrderLineType;+ return (+ !accrualUnitCostByPoLine.has(poLineId) &&+ lineType !== "Service" &&+ lineType !== "Fixed Asset" &&+ lineType !== "G/L Account"+ );+ }+ );+ if (unaccrued.length > 0) {+ logger.warn(+ "Units invoiced before receipt have no GR/IR accrual; the receipt costs them at PO cost",+ {+ companyId,+ receiptId,+ purchaseOrderLines: unaccrued.map(+ ([purchaseOrderLineId, quantity]) => ({+ purchaseOrderLineId,+ quantity+ })+ )+ }+ );+ }+ }++ const itemById = new Map(items.data.map((item) => [item.id, item]));+ const itemPostingGroupByItem = new Map(+ itemCosts.data.map((cost) => [cost.itemId, cost.itemPostingGroupId])+ );+ const purchaseOrderLineById = new Map(+ purchaseOrderLines.data.map((line) => [line.id, line])+ );+ const receiptJournalLines: PurchaseReceiptLine[] =+ receiptLines.data.map((receiptLine) => {+ const item = receiptLine.itemId+ ? itemById.get(receiptLine.itemId)+ : undefined;+ const jobOperationId = receiptLine.lineId+ ? purchaseOrderLineById.get(receiptLine.lineId)?.jobOperationId+ : null;+ return {+ purchaseOrderLineId: receiptLine.lineId,+ itemId: receiptLine.itemId,+ quantity:+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity,+ unitPrice: receiptLine.unitPrice,+ itemTrackingType: item?.itemTrackingType,+ replenishmentSystem: item?.replenishmentSystem,+ itemPostingGroupId: receiptLine.itemId+ ? (itemPostingGroupByItem.get(receiptLine.itemId) ?? null)+ : null,+ locationId: receiptLine.locationId ?? null,+ processId: jobOperationId+ ? (processIdByJobOperationId.get(jobOperationId) ?? null)+ : null+ };+ });+ // Line cost at PO price + proportional shipping. The portion of a+ // line invoiced before receipt is valued at the accrual (invoice)+ // unit cost, so the invoice's GR/IR accrual clears exactly — no+ // PPV. The remainder stays at PO cost until its invoice adjusts it.+ const receiptLineCosts = purchaseReceiptLineCosts(receiptJournalLines, {+ shippingCost,+ isOutsideProcessing,+ invoiceFirst: {+ quantity: invoiceFirstQtyByPoLine,+ unitCost: accrualUnitCostByPoLine+ }+ });++ for (const [index, receiptLine] of receiptLines.data.entries()) {+ const {+ quantity: receivedQuantity,+ createsLayers,+ invoiceFirstQuantity: invoiceFirstQty,+ invoiceFirstCost: invoiceFirstPortionCost,+ normalQuantity: normalQty,+ normalCost: normalPortionCost+ } = receiptLineCosts[index]!;++ // A line nothing arrived for books nothing — the Sales Return and++ // Inbound Transfer branches skip it the same way.++ if (receivedQuantity === 0) continue;+++ const itemTrackingType =+ receiptJournalLines[index]!.itemTrackingType ?? "Inventory";+ const isNegativeReceipt = receivedQuantity < 0;+ const poLineId = receiptLine.lineId;++ if (createsLayers && isNegativeReceipt) {+ negativeReceiptConsumptions.push({+ index,+ itemId: receiptLine.itemId!,+ quantity: Math.abs(receivedQuantity)+ });+ }++ // Cost layers: the receipt is the sole creator of purchase layers.+ // The invoice later adjusts them via appliesToCostLedgerId children.+ if (createsLayers && !isNegativeReceipt) {+ if (invoiceFirstQty > 0) {+ costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: receiptHeader.id ?? undefined,+ externalDocumentId:+ receiptHeader.externalDocumentId ?? undefined,+ itemId: receiptLine.itemId,+ quantity: round(invoiceFirstQty),+ nominalCost: round(+ invoiceFirstQty * (receiptLine.unitPrice ?? 0)+ ),+ cost: round(invoiceFirstPortionCost),+ remainingQuantity: round(invoiceFirstQty),+ supplierId: purchaseOrder.data?.supplierId ?? undefined,+ companyId,+ postingDate: today,+ isInvoiceFirst: true,+ poLineId: poLineId ?? undefined+ });+ }+ if (normalQty > 0) {+ costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: receiptHeader.id ?? undefined,+ externalDocumentId:+ receiptHeader.externalDocumentId ?? undefined,+ itemId: receiptLine.itemId,+ quantity: round(normalQty),+ nominalCost: round(normalQty * (receiptLine.unitPrice ?? 0)),+ cost: round(normalPortionCost),+ remainingQuantity: round(normalQty),+ supplierId: purchaseOrder.data?.supplierId ?? undefined,+ companyId,+ postingDate: today+ });+ }+ }++ if (itemTrackingType === "Inventory" && !isOutsideProcessing) {+ // For inventory entries, use the appropriate entry type based on quantity sign+ const entryType =+ receivedQuantity < 0 ? "Negative Adjmt." : "Positive Adjmt.";++ itemLedgerInserts.push({+ postingDate: today,+ itemId: receiptLine.itemId,+ quantity: round(receivedQuantity),+ locationId: receiptLine.locationId,+ storageUnitId: receiptLine.storageUnitId,+ entryType,+ documentType: "Purchase Receipt",+ documentId: receiptHeader.id ?? undefined,+ externalDocumentId: receiptHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ }++ if (receiptLine.requiresBatchTracking && !isOutsideProcessing) {+ const entryType =+ receivedQuantity < 0 ? "Negative Adjmt." : "Positive Adjmt.";++ itemLedgerInserts.push({+ postingDate: today,+ itemId: receiptLine.itemId,+ quantity: round(receivedQuantity),+ locationId: receiptLine.locationId,+ storageUnitId: receiptLine.storageUnitId,+ entryType,+ documentType: "Purchase Receipt",+ documentId: receiptHeader.id ?? undefined,+ trackedEntityId: receiptLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Receipt Line"] === receiptLine.id+ )?.id,+ externalDocumentId: receiptHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ }++ if (receiptLine.requiresSerialTracking && !isOutsideProcessing) {+ const lineTracking = receiptLineTracking.data?.filter(+ (tracking) =>+ (tracking.attributes as TrackedEntityAttributes | undefined)?.[+ "Receipt Line"+ ] === receiptLine.id+ );++ const safeReceiptLineQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;+ const absReceivedQuantity = Math.abs(safeReceiptLineQuantity);+ const entryType =+ receivedQuantity < 0 ? "Negative Adjmt." : "Positive Adjmt.";+ const quantityPerEntry = receivedQuantity < 0 ? -1 : 1;++ for (let i = 0; i < absReceivedQuantity; i++) {+ const trackingWithIndex = lineTracking?.find(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Receipt Line Index"] === i+ );++ itemLedgerInserts.push({+ postingDate: today,+ itemId: receiptLine.itemId,+ quantity: round(quantityPerEntry),+ locationId: receiptLine.locationId,+ storageUnitId: receiptLine.storageUnitId,+ entryType,+ documentType: "Purchase Receipt",+ documentId: receiptHeader.id ?? undefined,+ trackedEntityId: trackingWithIndex?.id,+ externalDocumentId:+ receiptHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ }+ }+ }++ // Process Fixed Asset PO lines (no receipt lines — handled directly from PO)+ const { data: receiptFaLines } = await many(+ db,+ "receiptFixedAssetLine",+ { receiptId, received: true, companyId },+ { columns: ["id", "purchaseOrderLineId", "serialNumber"] }+ );+ const poFaLines = (receiptFaLines ?? []).filter(+ (r): r is typeof r & { purchaseOrderLineId: string } =>+ r.purchaseOrderLineId !== null+ );+ const receivedFaPoLineIds = new Set(+ poFaLines.map((r) => r.purchaseOrderLineId)+ );+ const faSerialNumbers = new Map(+ poFaLines.map((r) => [r.purchaseOrderLineId, r.serialNumber])+ );+ const faReceiptLineIds = new Map<string, string>();+ for (const r of poFaLines) {+ faReceiptLineIds.set(r.purchaseOrderLineId, r.id);+ }+ // A Construction in Progress asset records every posting that adds to+ // its acquisition cost as a CIP cost row. Written inside the+ // transaction, after the journal, so it can carry the journal id.+ const cipCostInserts: Omit<+ Database["public"]["Tables"]["fixedAssetCipCost"]["Insert"],+ "journalId"+ >[] = [];++ const faPurchaseOrderLines = purchaseOrderLines.data.filter(+ (pol) =>+ pol.purchaseOrderLineType === "Fixed Asset" &&+ pol.assetId &&+ !pol.receivedComplete &&+ pol.purchaseQuantity &&+ pol.purchaseQuantity > 0 &&+ receivedFaPoLineIds.has(pol.id)+ );++ const fixedAssetJournalLines: FixedAssetReceiptLine[] = [];+ type ReceivedAsset = Pick<+ Tables["fixedAsset"]["Row"],+ | "id"+ | "status"+ | "acquisitionDate"+ | "depreciationStartDate"+ | "acquisitionCost"+ | "locationId"+ | "fixedAssetClassId"+ > & {+ fixedAssetClass: Pick<+ Tables["fixedAssetClass"]["Row"],+ "assetAccountId" | "isConstructionInProgress"+ > | null;+ };+ const faAssets: { data: ReceivedAsset[] } =+ faPurchaseOrderLines.length > 0+ ? await many<"fixedAsset", ReceivedAsset>(+ db,+ "fixedAsset",+ {+ companyId,+ id: faPurchaseOrderLines.map((line) => line.assetId!)+ },+ {+ columns: [+ "id",+ "status",+ "acquisitionDate",+ "depreciationStartDate",+ "acquisitionCost",+ "locationId",+ "fixedAssetClassId"+ ],+ embed: {+ fixedAssetClass: {+ table: "fixedAssetClass",+ via: "fixedAssetClassId",+ columns: ["assetAccountId", "isConstructionInProgress"]+ }+ }+ }+ )+ : { data: [] };+ const faAssetById = new Map(+ faAssets.data.map((asset) => [asset.id, asset])+ );++ for (const faPoLine of faPurchaseOrderLines) {+ const quantity = faPoLine.purchaseQuantity ?? 1;+ const unitPrice = faPoLine.unitPrice ?? 0;+ const cost = quantity * unitPrice;++ const asset = faAssetById.get(faPoLine.assetId!);+ if (!asset) throw new Error("Failed to fetch fixed asset");+ fixedAssetWrites.overlay(faPoLine.assetId!, asset);++ const isConstructionInProgress = Boolean(+ asset.fixedAssetClass?.isConstructionInProgress+ );++ fixedAssetJournalLines.push({+ purchaseOrderLineId: faPoLine.id,+ quantity,+ cost,+ assetAccountId: asset.fixedAssetClass!.assetAccountId,+ fixedAssetClassId: asset.fixedAssetClassId ?? null,+ locationId:+ faPoLine.locationId ??+ receiptHeader.locationId ??+ asset.locationId ??+ null+ });++ const updateData: Database["public"]["Tables"]["fixedAsset"]["Update"] =+ {+ acquisitionCost: (Number(asset.acquisitionCost) ?? 0) + cost,+ updatedBy: userId+ };+ if (!asset.acquisitionDate) {+ updateData.acquisitionDate = today;+ }+ // A CIP asset does not depreciate until it is capitalized, so its+ // depreciation start date stays null and it goes Under Construction.+ if (!isConstructionInProgress && !asset.depreciationStartDate) {+ updateData.depreciationStartDate = today;+ }+ if (asset.status === "Draft") {+ updateData.status = isConstructionInProgress+ ? "Under Construction"+ : "Active";+ }++ const serialNumber = faSerialNumbers.get(faPoLine.id!);+ if (serialNumber) {+ updateData.serialNumber = serialNumber;+ }++ const faLineLocationId =+ faPoLine.locationId ?? receiptHeader.locationId;+ if (faLineLocationId) {+ updateData.locationId = faLineLocationId;+ }++ fixedAssetWrites.patch(faPoLine.assetId!, updateData);++ if (isConstructionInProgress) {+ cipCostInserts.push({+ fixedAssetId: faPoLine.assetId!,+ sourceType: "Receipt",+ sourceDocumentId: receiptId,+ sourceDocumentLineId: faReceiptLineIds.get(faPoLine.id!) ?? null,+ amount: round(cost),+ costDate: today,+ companyId,+ createdBy: userId+ });+ }++ purchaseOrderLineUpdates[faPoLine.id!] = {+ quantityReceived: faPoLine.purchaseQuantity,+ receivedComplete: true,+ receivedDate: today+ };+ }++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ await fixedAssetWrites.apply(trx, companyId);+ // Negative receipts: consume layers at layer cost (FIFO/LIFO with+ // adjustment children), and the journal books what was relieved so+ // the GL credit matches what actually left the subledger.+ const relievedCostByLine = new Map<number, number>();+ for (const consumption of negativeReceiptConsumptions) {+ const cogsResult = await calculateCOGS(trx, {+ itemId: consumption.itemId,+ quantity: consumption.quantity,+ companyId+ });+ // A consumed layer's total is authoritative even at zero or+ // negative (free goods, credit-adjusted layers): the GL credit+ // must match the value actually relieved from the subledger. The+ // PO-cost fallback applies only when nothing was consumed and no+ // cost basis was found.+ const consumedCost =+ cogsResult.layersConsumed.length > 0 || cogsResult.totalCost > 0+ ? cogsResult.totalCost+ : receiptLineCosts[consumption.index]!.cost;+ relievedCostByLine.set(consumption.index, consumedCost);+ costLedgerInserts.push({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: receiptHeader.id ?? undefined,+ itemId: consumption.itemId,+ quantity: round(-consumption.quantity),+ cost: round(-consumedCost),+ remainingQuantity: 0,+ supplierId: purchaseOrder.data?.supplierId ?? undefined,+ companyId,+ postingDate: today+ });+ }++ // Flush cost layers. Transition guard: invoices posted before+ // receipt-created layers shipped created their own layers, so the+ // invoice-first quantity those legacy layers already represent must+ // not create a second one. Coverage is matched to the receipt's PO+ // lines through the legacy invoices' own lines, net of quantity+ // received before this receipt (which already consumed coverage);+ // only the covered quantity is excluded — any remainder still+ // creates a layer.+ if (costLedgerInserts.length > 0) {+ const invoiceFirstRows = costLedgerInserts.filter(+ (row) => row.isInvoiceFirst && row.itemId && row.poLineId+ );+ const legacyCoverageByPoLine = new Map<string, number>();+ if (invoiceFirstRows.length > 0) {+ const invoiceFirstItemIds = [+ ...new Set(invoiceFirstRows.map((row) => row.itemId!))+ ];+ const legacyLayers = await trx+ .selectFrom("costLedger")+ .select(["documentId"])+ .where("documentType", "=", "Purchase Invoice")+ .where("itemId", "in", invoiceFirstItemIds)+ .where("companyId", "=", companyId)+ .where("remainingQuantity", ">", 0)+ // adjustment children are corrections on receipt layers, not+ // legacy invoice-created layers — must not trip this guard+ .where("adjustment", "=", false)+ .where("appliesToCostLedgerId", "is", null)+ .execute();+ const legacyInvoiceIds = [+ ...new Set(+ legacyLayers+ .map((layer) => layer.documentId)+ .filter((id): id is string => !!id)+ )+ ];+ if (legacyInvoiceIds.length > 0) {+ const invoiceFirstPoLineIds = [+ ...new Set(invoiceFirstRows.map((row) => row.poLineId!))+ ];+ const legacyInvoiceLines = await trx+ .selectFrom("purchaseInvoiceLine")+ .select([+ "purchaseOrderLineId",+ "quantity",+ "conversionFactor"+ ])+ .where("invoiceId", "in", legacyInvoiceIds)+ .where("purchaseOrderLineId", "in", invoiceFirstPoLineIds)+ .where("companyId", "=", companyId)+ .execute();+ for (const line of legacyInvoiceLines) {+ if (!line.purchaseOrderLineId) continue;+ legacyCoverageByPoLine.set(+ line.purchaseOrderLineId,+ (legacyCoverageByPoLine.get(line.purchaseOrderLineId) ??+ 0) ++ Number(line.quantity ?? 0) *+ Number(line.conversionFactor ?? 1)+ );+ }+ // Legacy layers were created for the full invoiced quantity,+ // and units received earlier consumed that coverage first —+ // subtracting received-to-date leaves exactly the coverage+ // this and future receipts may still exclude.+ for (const [linePoId, covered] of legacyCoverageByPoLine) {+ const receivedBefore =+ receivedBeforeInvUnitsByPoLine.get(linePoId) ?? 0;+ legacyCoverageByPoLine.set(+ linePoId,+ Math.max(0, covered - receivedBefore)+ );+ }+ }+ }+ const costLedgerRows: Database["public"]["Tables"]["costLedger"]["Insert"][] =+ [];+ for (const row of costLedgerInserts) {+ const {+ isInvoiceFirst,+ poLineId: rowPoLineId,+ ...insertRow+ } = row;+ if (isInvoiceFirst && rowPoLineId) {+ const coverage = legacyCoverageByPoLine.get(rowPoLineId) ?? 0;+ const rowQty = Number(insertRow.quantity ?? 0);+ const excludedQty = Math.min(rowQty, coverage);+ if (excludedQty > 0) {+ legacyCoverageByPoLine.set(+ rowPoLineId,+ coverage - excludedQty+ );+ logger.info(+ "excluding invoice-first quantity already represented by legacy invoice-created layers",+ {+ itemId: insertRow.itemId,+ purchaseOrderLineId: rowPoLineId,+ excludedQty+ }+ );+ const layerQty = rowQty - excludedQty;+ if (layerQty <= 0) continue;+ const scale = layerQty / rowQty;+ insertRow.quantity = round(layerQty);+ insertRow.cost = round(Number(insertRow.cost ?? 0) * scale);+ insertRow.nominalCost = round(+ Number(insertRow.nominalCost ?? 0) * scale+ );+ insertRow.remainingQuantity = round(layerQty);+ }+ }+ costLedgerRows.push(insertRow);+ }+ if (costLedgerRows.length > 0) {+ await trx+ .insertInto("costLedger")+ .values(costLedgerRows)+ .execute();+ }+ }++ for await (const [purchaseOrderLineId, update] of Object.entries(+ purchaseOrderLineUpdates+ )) {+ await trx+ .updateTable("purchaseOrderLine")+ .set(update)+ .where("id", "=", purchaseOrderLineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ for await (const [jobOperationId, update] of Object.entries(+ jobOperationUpdates+ )) {+ await trx+ .updateTable("jobOperation")+ .set(update)+ .where("id", "=", jobOperationId)+ .where("companyId", "=", companyId)+ .execute();+ }++ const purchaseOrderLines = await trx+ .selectFrom("purchaseOrderLine")+ .select([+ "id",+ "purchaseOrderLineType",+ "invoicedComplete",+ "receivedComplete"+ ])+ .where("purchaseOrderId", "=", purchaseOrder.data.id)+ .execute();++ const areAllLinesInvoiced = purchaseOrderLines.every(+ (line) =>+ line.purchaseOrderLineType === "Comment" || line.invoicedComplete+ );++ const areAllLinesReceived = purchaseOrderLines.every(+ (line) =>+ line.purchaseOrderLineType === "Comment" ||+ line.purchaseOrderLineType === "G/L Account" ||+ line.purchaseOrderLineType === "Service" ||+ line.receivedComplete+ );++ let status: Database["public"]["Tables"]["purchaseOrder"]["Row"]["status"] =+ "To Receive and Invoice";+ if (areAllLinesInvoiced && areAllLinesReceived) {+ status = "Completed";+ } else if (areAllLinesInvoiced) {+ status = "To Receive";+ } else if (areAllLinesReceived) {+ status = "To Invoice";+ }++ await trx+ .updateTable("purchaseOrder")+ .set({+ status+ })+ .where("id", "=", purchaseOrder.data.id)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .updateTable("purchaseOrderDelivery")+ .set({+ deliveryDate: today,+ locationId: receiptHeader.locationId+ })+ .where("id", "=", receiptHeader.sourceDocumentId)+ .where("companyId", "=", companyId)+ .execute();++ const journalLines = buildPurchaseReceiptJournalLines({+ documentId: receiptHeader.id,+ externalDocumentId: purchaseOrder.data.supplierReference,+ isOutsideProcessing,+ supplierId: purchaseOrder.data.supplierId,+ supplierTypeId: supplier.data.supplierTypeId ?? null,+ accounts: accountDefaults.data,+ lines: receiptJournalLines.map((line, index) => ({+ ...line,+ cost:+ relievedCostByLine.get(index) ?? receiptLineCosts[index]!.cost+ })),+ fixedAssets: fixedAssetJournalLines+ });+ let receiptJournalId: string | null = null;+ if (journalLines.length > 0) {+ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `Purchase Receipt ${receiptHeader.receiptId}`,+ postingDate: today,+ companyId,+ sourceType: "Purchase Receipt",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ receiptJournalId = journalResult.id;++ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLines.map(({ dimensions: _, ...line }) => ({+ ...line,+ journalId: journalResult.id,+ companyId+ }))+ )+ .returning(["id"])+ .execute();++ const journalLineDimensionInserts = journalLineDimensionRows({+ journalLineIds: journalLineResults.map((jl) => jl.id),+ lines: journalLines,+ dimensionIdByEntity: dimensionMap,+ companyId+ });+ if (journalLineDimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(journalLineDimensionInserts)+ .execute();+ }+ }++ if (cipCostInserts.length > 0) {+ await trx+ .insertInto("fixedAssetCipCost")+ .values(+ cipCostInserts.map((row) => ({+ ...row,+ journalId: receiptJournalId+ }))+ )+ .execute();+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ await trx+ .updateTable("receipt")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId+ })+ .where("id", "=", receiptId)+ .where("companyId", "=", companyId)+ .execute();++ if (Object.keys(trackedEntityUpdates).length > 0) {+ const trackedActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Receive",+ sourceDocument: "Receipt",+ sourceDocumentId: receiptId,+ sourceDocumentReadableId: receiptHeader.receiptId,+ attributes: {+ "Purchase Order": receiptHeader.sourceDocumentId,+ Receipt: receiptId,+ Employee: userId+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();++ const trackedActivityId = trackedActivity[0]!.id;++ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }++ if (inspectionInserts.length > 0) {+ for (const row of inspectionInserts) {+ row.inspectionId = await sequence.getNextSequence(+ trx,+ "inspection",+ companyId+ );+ }+ const insertedInspections = await trx+ .insertInto("inspection")+ .values(+ inspectionInserts as Insertable<KyselyDatabase["inspection"]>[]+ )+ .returning(["id", "sourceDocumentLineId"])+ .execute();++ const samplingPlanInserts: Array<+ InspectionSamplingPlanInsert & { inspectionId: string }+ > = [];+ for (const inspection of insertedInspections) {+ const featureRows = inspection.sourceDocumentLineId+ ? samplingPlanInsertsByReceiptLineId.get(+ inspection.sourceDocumentLineId+ )+ : undefined;+ if (!featureRows) continue;+ for (const featureRow of featureRows) {+ samplingPlanInserts.push({+ ...featureRow,+ inspectionId: inspection.id+ });+ }+ }+ if (samplingPlanInserts.length > 0) {+ await trx+ .insertInto("inspectionSamplingPlan")+ .values(samplingPlanInserts)+ .execute();+ }+ }+ });+ break;+ }+ case "Sales Return Order": {+ // Customer RMA receipt: goods re-enter inventory at the ORIGINAL+ // outbound cost when the line links a shipment (exact cost reversing),+ // at current cost for blind returns, and at ZERO when the line's+ // return reason flags inventoryValueZero. Entities re-enter On Hold —+ // disposition is the only path to Available.+ if (!receiptHeader.sourceDocumentId)+ throw new Error("Receipt has no sourceDocumentId");+ const salesReturnOrderId = receiptHeader.sourceDocumentId;++ const [salesReturnOrder, salesReturnOrderLines, itemCostDetails] =+ await inOrder([+ () =>+ single(db, "salesReturnOrder", {+ id: salesReturnOrderId,+ companyId+ }),+ () =>+ many<+ "salesReturnOrderLine",+ Tables["salesReturnOrderLine"]["Row"] & {+ returnReason: Pick<+ Tables["returnReason"]["Row"],+ "inventoryValueZero"+ > | null;+ }+ >(+ db,+ "salesReturnOrderLine",+ { salesReturnOrderId, companyId },+ {+ embed: {+ returnReason: {+ table: "returnReason",+ via: "returnReasonId",+ columns: ["inventoryValueZero"]+ }+ }+ }+ ),+ () =>+ many(+ db,+ "itemCost",+ { itemId: itemIds, companyId },+ { columns: ["itemId", "unitCost"] }+ )+ ]);+ if (salesReturnOrder.error)+ throw new Error("Failed to fetch sales return order");+ if (salesReturnOrderLines.error)+ throw new Error("Failed to fetch sales return order lines");+ if (itemCostDetails.error)+ throw new Error("Failed to fetch item costs for cost resolution");+ // Allowlist, matching the create-side gate: a Draft RMA has never had+ // its caps validated, so it must be confirmed (To Receive) before+ // receiving.+ if (salesReturnOrder.data.status !== "To Receive") {+ throw new Error(+ `Cannot post a receipt against a return order in ${salesReturnOrder.data.status} status`+ );+ }++ const returnLineById = new Map(+ (salesReturnOrderLines.data ?? []).map((l) => [l.id, l])+ );+ const currentCostByItem = new Map(+ (itemCostDetails.data ?? []).map((c) => [+ c.itemId,+ Number(c.unitCost ?? 0)+ ])+ );++ // Original-outbound-cost resolution: the shipment's consumption rows+ // are per (shipment, item) — post-shipment aggregates across lines —+ // so resolve the shipment ids behind the linked shipment lines, then+ // average that shipment's consumption rows for the item.+ const linkedShipmentLineIds = [+ ...new Set(+ (salesReturnOrderLines.data ?? [])+ .map((l) => l.shipmentLineId)+ .filter(Boolean) as string[]+ )+ ];+ const shipmentIdByShipmentLine = new Map<string, string>();+ if (linkedShipmentLineIds.length > 0) {+ const shipmentLines = await many(+ db,+ "shipmentLine",+ { companyId, id: linkedShipmentLineIds },+ { columns: ["id", "shipmentId"] }+ );+ // A failed read must abort, not fall back: an empty map here would+ // silently book every linked line at CURRENT cost instead of the+ // original outbound cost, defeating exact-cost reversing unnoticed.+ if (shipmentLines.error)+ throw new Error(+ "Failed to resolve shipments for original-cost lookup"+ );+ for (const line of shipmentLines.data ?? []) {+ if (line.shipmentId)+ shipmentIdByShipmentLine.set(line.id, line.shipmentId);+ }+ }+ const shipmentIds = [...new Set(shipmentIdByShipmentLine.values())];+ const consumptionRowsByShipmentItem = new Map<+ string,+ { quantity: number; cost: number }[]+ >();+ if (shipmentIds.length > 0) {+ const consumptionRows = await many(+ db,+ "costLedger",+ {+ documentId: shipmentIds,+ documentType: "Sales Shipment",+ companyId,+ quantity: lt(0)+ },+ { columns: ["documentId", "itemId", "quantity", "cost"] }+ );+ if (consumptionRows.error)+ throw new Error(+ "Failed to fetch shipment cost layers for original-cost lookup"+ );+ for (const row of consumptionRows.data ?? []) {+ const key = `${row.documentId}::${row.itemId}`;+ const list = consumptionRowsByShipmentItem.get(key) ?? [];+ list.push({+ quantity: Number(row.quantity ?? 0),+ cost: Number(row.cost ?? 0)+ });+ consumptionRowsByShipmentItem.set(key, list);+ }+ }++ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ // Customer type for the return-receipt journal's GL dimensions.+ const customer = await single(+ db,+ "customer",+ { id: salesReturnOrder.data.customerId, companyId },+ { columns: ["id", "customerTypeId"] }+ );+ const customerTypeId = customer.data?.customerTypeId ?? null;++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const costLedgerInserts: Database["public"]["Tables"]["costLedger"]["Insert"][] =+ [];+ const returnJournalLines: SalesReturnReceiptLine[] = [];+ const itemById = new Map(items.data.map((item) => [item.id, item]));+ const itemPostingGroupByItem = new Map(+ itemCosts.data.map((cost) => [cost.itemId, cost.itemPostingGroupId])+ );+ const returnLineUpdates: Record<+ string,+ { quantityReceived: number; updatedBy: string }+ > = {};+ const trackedEntityUpdates: Record<+ string,+ {+ status: Database["public"]["Tables"]["trackedEntity"]["Row"]["status"];+ quantity: number;+ }+ > = {};++ for (const receiptLine of receiptLines.data ?? []) {+ if (!receiptLine.itemId || !receiptLine.lineId) continue;+ const returnLine = returnLineById.get(receiptLine.lineId);+ if (!returnLine) {+ throw new Error(+ `Receipt line ${receiptLine.id} does not map to a return order line`+ );+ }++ const safeReceivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;+ if (safeReceivedQuantity <= 0) continue;+ const receivedQuantity = safeReceivedQuantity;++ const item = itemById.get(receiptLine.itemId);+ const itemTrackingType = item?.itemTrackingType ?? "Inventory";++ // Cost resolution: zero-value reason -> 0; linked -> original+ // outbound cost from the shipment's consumption rows; else current.+ let unitCost: number;+ if (+ (+ returnLine.returnReason as {+ inventoryValueZero: boolean;+ } | null+ )?.inventoryValueZero+ ) {+ unitCost = 0;+ } else if (+ returnLine.shipmentLineId &&+ shipmentIdByShipmentLine.has(returnLine.shipmentLineId)+ ) {+ const shipmentId = shipmentIdByShipmentLine.get(+ returnLine.shipmentLineId+ )!;+ const rows =+ consumptionRowsByShipmentItem.get(+ `${shipmentId}::${receiptLine.itemId}`+ ) ?? [];+ // Falls back to current cost only when the resolved shipment+ // genuinely has no usable consumption rows for the item (empty,+ // zero-quantity, or NaN — resolveReturnUnitCost returns null).+ // Read failures throw above rather than reaching this fallback.+ unitCost =+ resolveReturnUnitCost(rows) ??+ currentCostByItem.get(receiptLine.itemId) ??+ 0;+ } else {+ unitCost = currentCostByItem.get(receiptLine.itemId) ?? 0;+ }++ const cost = receivedQuantity * unitCost;+ const createsLayers =+ itemTrackingType !== "Non-Inventory" &&+ !!receiptLine.itemId &&+ receivedQuantity > 0;++ // itemLedger — mirrors the Purchase Order branch's three sites,+ // with the Sales Return Receipt document identity.+ if (itemTrackingType === "Inventory") {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: receiptLine.itemId,+ quantity: round(receivedQuantity),+ locationId: receiptLine.locationId,+ storageUnitId: receiptLine.storageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Sales Return Receipt",+ documentId: receiptHeader.id ?? undefined,+ externalDocumentId: receiptHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ }++ if (receiptLine.requiresBatchTracking) {+ const entity = receiptLineTracking.data?.find(+ (tracking) =>+ (tracking.attributes as TrackedEntityAttributes | undefined)?.[+ "Receipt Line"+ ] === receiptLine.id+ );+ itemLedgerInserts.push({+ postingDate: today,+ itemId: receiptLine.itemId,+ quantity: round(receivedQuantity),+ locationId: receiptLine.locationId,+ storageUnitId: receiptLine.storageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Sales Return Receipt",+ documentId: receiptHeader.id ?? undefined,+ trackedEntityId: entity?.id,+ externalDocumentId: receiptHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ if (entity) {+ trackedEntityUpdates[entity.id] = {+ status: "On Hold",+ quantity: receivedQuantity+ };+ }+ }++ if (receiptLine.requiresSerialTracking) {+ const lineTracking = receiptLineTracking.data?.filter(+ (tracking) =>+ (tracking.attributes as TrackedEntityAttributes | undefined)?.[+ "Receipt Line"+ ] === receiptLine.id+ );+ for (let i = 0; i < receivedQuantity; i++) {+ const trackingWithIndex = lineTracking?.find(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Receipt Line Index"] === i+ );+ itemLedgerInserts.push({+ postingDate: today,+ itemId: receiptLine.itemId,+ quantity: 1,+ locationId: receiptLine.locationId,+ storageUnitId: receiptLine.storageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Sales Return Receipt",+ documentId: receiptHeader.id ?? undefined,+ trackedEntityId: trackingWithIndex?.id,+ externalDocumentId:+ receiptHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ if (trackingWithIndex) {+ trackedEntityUpdates[trackingWithIndex.id] = {+ status: "On Hold",+ quantity: 1+ };+ }+ }+ }++ // Cost layer: consumable re-entry at the resolved cost. A+ // zero-value reason still creates the (0-cost) layer so FIFO+ // consumption stays quantity-consistent.+ if (createsLayers) {+ costLedgerInserts.push({+ itemLedgerType: "Sale",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Sales Return Receipt",+ documentId: receiptHeader.id ?? undefined,+ externalDocumentId: receiptHeader.externalDocumentId ?? undefined,+ itemId: receiptLine.itemId,+ quantity: round(receivedQuantity),+ nominalCost: round(cost),+ cost: round(cost),+ remainingQuantity: round(receivedQuantity),+ companyId,+ postingDate: today+ });+ }++ // Journal: Dr Inventory / Cr COGS at the re-entry value. Zero-value+ // re-entries post no journal.+ returnJournalLines.push({+ returnLineId: receiptLine.lineId,+ itemId: receiptLine.itemId,+ quantity: receivedQuantity,+ cost,+ replenishmentSystem: item?.replenishmentSystem,+ itemPostingGroupId:+ itemPostingGroupByItem.get(receiptLine.itemId) ?? null,+ locationId: receiptLine.locationId+ });++ const existingUpdate = returnLineUpdates[returnLine.id];+ returnLineUpdates[returnLine.id] = {+ quantityReceived:+ (existingUpdate?.quantityReceived ??+ Number(returnLine.quantityReceived ?? 0)) + receivedQuantity,+ updatedBy: userId+ };+ }++ const journalLines = buildSalesReturnReceiptJournalLines({+ documentId: receiptHeader.id,+ externalDocumentId: receiptHeader.externalDocumentId,+ customerId: salesReturnOrder.data.customerId,+ customerTypeId,+ accounts: accountDefaults.data,+ lines: returnJournalLines+ });++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted" && journalLines.length > 0+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ // Double-post guard: serialize on the receipt row — a second+ // concurrent post waits here, then sees Posted and aborts, so+ // ledger rows, journals, and quantityReceived can never double.+ const lockedReceipt = await trx+ .selectFrom("receipt")+ .select(["status"])+ .where("id", "=", receiptId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (+ lockedReceipt.status === "Posted" ||+ lockedReceipt.status === "Voided"+ ) {+ throw new Error(`Receipt is already ${lockedReceipt.status}`);+ }++ // cancelSalesReturnOrder locks this same order row — re-check the+ // status under the lock so a cancel committed after our+ // pre-transaction read cannot be posted over (which would leave a+ // Cancelled order with received stock and a freed cap).+ const lockedOrder = await trx+ .selectFrom("salesReturnOrder")+ .select(["status"])+ .where("id", "=", salesReturnOrderId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (lockedOrder.status !== "To Receive") {+ throw new Error(+ `Cannot post a receipt against a return order in ${lockedOrder.status} status`+ );+ }++ if (costLedgerInserts.length > 0) {+ await trx+ .insertInto("costLedger")+ .values(costLedgerInserts)+ .execute();+ }++ for await (const [lineId, update] of Object.entries(+ returnLineUpdates+ )) {+ await trx+ .updateTable("salesReturnOrderLine")+ .set(update)+ .where("id", "=", lineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Derived status (mirrors getSalesReturnOrderStatus): the RMA is+ // Completed once every line has received its authorized quantity or+ // been short-closed, otherwise it stays To Receive.+ const allLines = await trx+ .selectFrom("salesReturnOrderLine")+ .select(["quantity", "quantityReceived", "closedComplete"])+ .where("salesReturnOrderId", "=", salesReturnOrderId)+ .execute();+ const allReceived =+ allLines.length > 0 &&+ allLines.every(+ (l) =>+ l.closedComplete ||+ Number(l.quantityReceived) >= Number(l.quantity)+ );+ const returnStatus = allReceived+ ? ("Completed" as const)+ : ("To Receive" as const);+ await trx+ .updateTable("salesReturnOrder")+ .set({ status: returnStatus, updatedBy: userId })+ .where("id", "=", salesReturnOrderId)+ .where("companyId", "=", companyId)+ .execute();++ if (journalLines.length > 0) {+ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `Sales Return Receipt ${receiptHeader.receiptId}`,+ postingDate: today,+ companyId,+ sourceType: "Sales Return Receipt",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLines.map(({ dimensions: _, ...line }) => ({+ ...line,+ journalId: journalResult.id,+ companyId+ }))+ )+ .returning(["id"])+ .execute();++ const journalLineDimensionInserts = journalLineDimensionRows({+ journalLineIds: journalLineResults.map((jl) => jl.id),+ lines: journalLines,+ dimensionIdByEntity: dimensionMap,+ companyId+ });+ if (journalLineDimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(journalLineDimensionInserts)+ .execute();+ }+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ await trx+ .updateTable("receipt")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId+ })+ .where("id", "=", receiptId)+ .where("companyId", "=", companyId)+ .execute();++ if (Object.keys(trackedEntityUpdates).length > 0) {+ const trackedActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Return Receipt",+ sourceDocument: "Receipt",+ sourceDocumentId: receiptId,+ sourceDocumentReadableId: receiptHeader.receiptId,+ attributes: {+ "Sales Return Order": salesReturnOrderId,+ Receipt: receiptId,+ Employee: userId+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();++ const trackedActivityId = trackedActivity[0]!.id;++ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }+ });+ break;+ }+ case "Inbound Transfer": {+ if (!receiptHeader.sourceDocumentId)+ throw new Error("Receipt has no sourceDocumentId");++ const [warehouseTransfer, warehouseTransferLines] = await inOrder([+ () =>+ single(db, "warehouseTransfer", {+ id: receiptHeader.sourceDocumentId,+ companyId+ }),+ () =>+ many(db, "warehouseTransferLine", {+ transferId: receiptHeader.sourceDocumentId,+ companyId+ })+ ]);++ if (warehouseTransfer.error)+ throw new Error("Failed to fetch warehouse transfer");+ if (warehouseTransferLines.error)+ throw new Error("Failed to fetch warehouse transfer lines");++ // Get item costs for valuation+ const transferItemIds = warehouseTransferLines.data+ .map((line) => line.itemId)+ .filter(Boolean) as string[];+ const [itemCosts, transferItems] = await inOrder([+ () =>+ many(+ db,+ "itemCost",+ { itemId: transferItemIds, companyId },+ { columns: ["itemId", "itemPostingGroupId", "unitCost"] }+ ),+ () =>+ many(+ db,+ "item",+ { id: transferItemIds, companyId },+ { columns: ["id", "replenishmentSystem"] }+ )+ ]);++ if (itemCosts.error) {+ throw new Error("Failed to fetch item costs");+ }+ if (transferItems.error) {+ throw new Error("Failed to fetch items");+ }++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const journalLineInserts: Omit<+ Database["public"]["Tables"]["journalLine"]["Insert"],+ "journalId"+ >[] = [];+ const journalLineDimensionsMeta: {+ itemPostingGroupId: string | null;+ itemId: string | null;+ locationId: string | null;+ fixedAssetClassId: string | null;+ }[] = [];+ const warehouseTransferLineUpdates: Record<+ string,+ Database["public"]["Tables"]["warehouseTransferLine"]["Update"]+ > = {};++ // Get account defaults (once for all lines) for the journal entries+ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ // Process each receipt line+ for await (const receiptLine of receiptLines.data) {+ const jlStartIdx = journalLineInserts.length;++ const warehouseTransferLine = warehouseTransferLines.data.find(+ (line) => line.id === receiptLine.lineId+ );++ if (!warehouseTransferLine) continue;++ const receivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;+ if (receivedQuantity === 0) continue;++ // Update warehouse transfer line received quantity+ const newReceivedQuantity =+ (warehouseTransferLine.receivedQuantity ?? 0) + receivedQuantity;++ warehouseTransferLineUpdates[warehouseTransferLine.id] = {+ receivedQuantity: newReceivedQuantity+ };++ // Get item cost for this item+ const itemCost = itemCosts.data?.find(+ (cost) => cost.itemId === receiptLine.itemId+ );+ const unitCost = itemCost?.unitCost ?? 0;+ const totalValue = Math.abs(receivedQuantity) * unitCost;++ // Create item ledger entry for positive adjustment at destination+ itemLedgerInserts.push({+ postingDate: today,+ itemId: receiptLine.itemId,+ quantity: receivedQuantity,+ locationId: receiptLine.locationId,+ storageUnitId: receiptLine.storageUnitId,+ entryType: "Transfer",+ documentType: "Transfer Receipt",+ documentId: warehouseTransfer.data?.transferId,+ externalDocumentId: receiptHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });++ // Create journal entries for inventory movement if there's value+ if (totalValue > 0) {+ const journalLineReference = nanoid();+ // Same account on both sides: a transfer moves stock between+ // locations, not between inventory classes.+ const inventoryAccount = resolveInventoryAccount(+ transferItems.data.find(+ (item: { id: string }) => item.id === receiptLine.itemId+ )?.replenishmentSystem ?? null,+ accountDefaults.data+ );++ journalLineInserts.push({+ accountId: inventoryAccount.account,+ description: `Transfer Out - ${warehouseTransfer.data?.transferId}`,+ amount: round(credit("asset", totalValue)),+ quantity: round(Math.abs(receivedQuantity)),+ documentType: "Receipt",+ documentId: receiptHeader.id,+ externalDocumentId: warehouseTransfer.data?.transferId,+ documentLineReference: `transfer-receipt:${receiptLine.lineId}`,+ journalLineReference,+ companyId+ });++ journalLineInserts.push({+ accountId: inventoryAccount.account,+ description: `Transfer In - ${warehouseTransfer.data?.transferId}`,+ amount: round(debit("asset", totalValue)),+ quantity: round(Math.abs(receivedQuantity)),+ documentType: "Receipt",+ documentId: receiptHeader.id,+ externalDocumentId: warehouseTransfer.data?.transferId,+ documentLineReference: `transfer-receipt:${receiptLine.lineId}`,+ journalLineReference,+ companyId+ });+ }++ // Track dimensions for this receipt line's journal lines+ const jlCount = journalLineInserts.length - jlStartIdx;+ for (let i = 0; i < jlCount; i++) {+ journalLineDimensionsMeta.push({+ itemPostingGroupId: itemCost?.itemPostingGroupId ?? null,+ itemId: receiptLine.itemId ?? null,+ locationId: receiptLine.locationId ?? null,+ fixedAssetClassId: null+ });+ }+ }++ // Check if all lines are fully received+ const allLinesFullyReceived = warehouseTransferLines.data.every(+ (line) => {+ const updates = warehouseTransferLineUpdates[line.id];+ const receivedQty =+ updates?.receivedQuantity ?? line.receivedQuantity ?? 0;+ return receivedQty >= (line.quantity ?? 0);+ }+ );++ // Check if all lines are fully shipped+ const allLinesFullyShipped = warehouseTransferLines.data.every(+ (line) => {+ const shippedQty = line.shippedQuantity ?? 0;+ return shippedQty >= (line.quantity ?? 0);+ }+ );++ // Determine new warehouse transfer status+ let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =+ warehouseTransfer.data.status;++ if (allLinesFullyReceived && allLinesFullyShipped) {+ newStatus = "Completed";+ } else if (allLinesFullyReceived && !allLinesFullyShipped) {+ newStatus = "To Ship";+ } else if (!allLinesFullyReceived && allLinesFullyShipped) {+ newStatus = "To Receive";+ }++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ // Update warehouse transfer lines+ for await (const [lineId, update] of Object.entries(+ warehouseTransferLineUpdates+ )) {+ await trx+ .updateTable("warehouseTransferLine")+ .set(update)+ .where("id", "=", lineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Update warehouse transfer status+ await trx+ .updateTable("warehouseTransfer")+ .set({+ status: newStatus,+ updatedBy: userId+ })+ .where("id", "=", warehouseTransfer.data.id)+ .where("companyId", "=", companyId)+ .execute();++ // Create journal entries if there are any+ if (journalLineInserts.length > 0) {+ const transferJournalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const transferJournalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId: transferJournalEntryId,+ accountingPeriodId,+ description: `Transfer Receipt ${receiptHeader.receiptId}`,+ postingDate: today,+ companyId,+ sourceType: "Transfer Receipt",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((line) => ({+ ...line,+ journalId: transferJournalResult.id+ }))+ )+ .returning(["id"])+ .execute();++ // Insert automatic dimensions for transfer journal lines+ if (dimensionMap.size > 0) {+ const journalLineDimensionInserts: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];++ journalLineResults.forEach((jl, index) => {+ const meta = journalLineDimensionsMeta[index];+ if (!meta) return;++ if (+ meta.itemPostingGroupId &&+ dimensionMap.has("ItemPostingGroup")+ ) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("ItemPostingGroup")!,+ valueId: meta.itemPostingGroupId,+ companyId+ });+ }+ if (meta.itemId && dimensionMap.has("Item")) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId+ });+ }+ if (meta.locationId && dimensionMap.has("Location")) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Location")!,+ valueId: meta.locationId,+ companyId+ });+ }+ if (+ meta.fixedAssetClassId &&+ dimensionMap.has("FixedAssetClass")+ ) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("FixedAssetClass")!,+ valueId: meta.fixedAssetClassId,+ companyId+ });+ }+ });++ if (journalLineDimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(journalLineDimensionInserts)+ .execute();+ }+ }+ }++ // Create item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update receipt status+ await trx+ .updateTable("receipt")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId+ })+ .where("id", "=", receiptId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }+ case "Rental Agreement": {+ await postRentalReceipt(db, {+ receiptId,+ companyId,+ userId,+ today,+ postingDate+ });+ break;+ }+ default: {+ break;+ }+ }++ return { success: true };+ } catch (err) {+ // A failed VOID leaves the receipt Posted: its rows still stand.+ if (type !== "void") {+ await updateRows(+ db,+ "receipt",+ { status: "Draft" },+ { id: receiptId, companyId }+ );+ }+ throw err;+ }+ }+ /** One line before it has a journal, and its dimension values by entity+ * type, in the order the posting writes them. A null value writes none. */+ export type ShipmentJournalLine = Omit<+ JournalLineInsert,+ "journalId" | "companyId" | "createdBy"+ > & {+ dimensions: JournalLineDimensionValues;+ };++ export type ShipmentJournal = {+ description: string;+ sourceType: Enums["journalEntrySourceType"];+ lines: ShipmentJournalLine[];+ };++ export type ShipmentAccountDefaults = Pick<+ Database["public"]["Tables"]["accountDefault"]["Row"],+ | "costOfGoodsSoldAccount"+ | "goodsReceivedNotInvoicedAccount"+ | "rawMaterialsAccount"+ | "finishedGoodsAccount"+ >;++ /** A sales order shipment line and the facts of its item. */+ export type SalesShipmentLine = {+ shipmentLineId: string;+ itemId: string | null;+ /** The shipped quantity, with null and NaN read as 0. */+ shippedQuantity: number;+ itemTrackingType: Enums["itemTrackingType"] | null;+ replenishmentSystem: Enums["itemReplenishmentSystem"] | null;+ itemPostingGroupId: string | null;+ /** The line's location, else the shipment's. */+ locationId: string | null;+ };++ /** A fixed asset sold on the sales order and shipped with this shipment. */+ export type FixedAssetSale = {+ salesOrderLineId: string;+ acquisitionCost: number;+ accumulatedDepreciation: number;+ assetAccountId: string;+ accumulatedDepreciationAccountId: string;+ /** Used as a disposal clearing account: the net book value parks here+ * until the invoice recognizes the proceeds. */+ writeOffAccountId: string;+ locationId: string | null;+ fixedAssetClassId: string | null;+ };++ type CostedLine = SalesShipmentLine & { itemId: string; quantity: number };++ /** The lines that carry a COGS pair: an item, a positive shipped quantity,+ * and stock (not Non-Inventory). `quantity` is the rounded shipped quantity+ * the pair carries. */+ function costedLines(lines: SalesShipmentLine[]): CostedLine[] {+ return lines.flatMap((line) =>+ line.itemId &&+ line.shippedQuantity > 0 &&+ line.itemTrackingType !== "Non-Inventory"+ ? [+ {+ ...line,+ itemId: line.itemId,+ quantity: round(line.shippedQuantity)+ }+ ]+ : []+ );+ }++ /**+ * Each item's shipped quantity across its costed lines, in first-line order:+ * the quantity the posting relieves per item (`calculateCOGS`).+ */+ export function shippedQuantityByItem(+ lines: SalesShipmentLine[]+ ): Map<string, number> {+ const totals = new Map<string, number>();+ for (const line of costedLines(lines)) {+ totals.set(line.itemId, (totals.get(line.itemId) ?? 0) + line.quantity);+ }+ return totals;+ }++ /** The net book value a fixed asset leaves the books at. */+ export function netBookValue(+ asset: Pick<FixedAssetSale, "acquisitionCost" | "accumulatedDepreciation">+ ): number {+ return asset.acquisitionCost - asset.accumulatedDepreciation;+ }++ /**+ * A sales order shipment: per costed line, COGS against inventory on+ * `shipment:<shipmentLineId>`. An item's relieved cost is shared across its+ * lines by quantity, the last line taking the remainder. Then, per fixed+ * asset sold, the accumulated depreciation cleared, the net book value moved+ * to disposal clearing, and the asset removed at cost.+ */+ export function buildSalesShipmentJournal({+ shipmentId,+ shipmentReadableId,+ externalDocumentId,+ customerId,+ customerTypeId,+ defaults,+ lines,+ relievedCostByItem,+ fixedAssetSales+ }: {+ shipmentId: string;+ shipmentReadableId: string;+ externalDocumentId: string | null;+ customerId: string | null;+ customerTypeId: string | null;+ defaults: ShipmentAccountDefaults;+ lines: SalesShipmentLine[];+ /** The cost each item's shipment relieved, positive. */+ relievedCostByItem: ReadonlyMap<string, number>;+ fixedAssetSales: FixedAssetSale[];+ }): ShipmentJournal {+ const costed = costedLines(lines);+ const totalQuantityByItem = shippedQuantityByItem(lines);++ const costByLine = new Map<string, number>();+ for (const [itemId, group] of Map.groupBy(costed, (line) => line.itemId)) {+ const total = relievedCostByItem.get(itemId) ?? 0;+ const totalQuantity = totalQuantityByItem.get(itemId) ?? 0;+ let assigned = 0;+ group.forEach((line, index) => {+ const lineCost =+ index === group.length - 1+ ? total - assigned+ : (line.quantity / totalQuantity) * total;+ assigned += lineCost;+ costByLine.set(line.shipmentLineId, lineCost);+ });+ }++ const document = {+ documentType: "Sales Shipment" as const,+ documentId: shipmentId,+ externalDocumentId+ };+ const journalLines: ShipmentJournalLine[] = [];++ for (const line of costed) {+ const cost = costByLine.get(line.shipmentLineId) ?? 0;+ const inventory = resolveInventoryAccount(+ line.replenishmentSystem,+ defaults+ );+ const keys = {+ ...document,+ quantity: line.quantity,+ documentLineReference: journalReference.to.shipment(line.shipmentLineId),+ journalLineReference: nanoid(),+ dimensions: {+ Customer: customerId,+ CustomerType: customerTypeId,+ Item: line.itemId,+ ItemPostingGroup: line.itemPostingGroupId,+ Location: line.locationId+ }+ };+ journalLines.push(+ {+ ...keys,+ accountId: defaults.costOfGoodsSoldAccount,+ description: "Cost of Goods Sold",+ amount: round(debit("expense", cost))+ },+ {+ ...keys,+ accountId: inventory.account,+ description: inventory.description,+ amount: round(credit("asset", cost))+ }+ );+ }++ for (const asset of fixedAssetSales) {+ const nbv = netBookValue(asset);+ const keys = {+ ...document,+ quantity: 1,+ documentLineReference: journalReference.to.shipment(+ asset.salesOrderLineId+ ),+ dimensions: {+ Customer: customerId,+ CustomerType: customerTypeId,+ Location: asset.locationId,+ FixedAssetClass: asset.fixedAssetClassId+ }+ };+ if (asset.accumulatedDepreciation > 0) {+ journalLines.push({+ ...keys,+ accountId: asset.accumulatedDepreciationAccountId,+ description: "Clear accumulated depreciation",+ amount: round(debit("asset", asset.accumulatedDepreciation)),+ journalLineReference: nanoid()+ });+ }+ if (nbv > 0) {+ journalLines.push({+ ...keys,+ accountId: asset.writeOffAccountId,+ description: "Transfer net book value to disposal clearing",+ amount: round(debit("expense", nbv)),+ journalLineReference: nanoid()+ });+ }+ journalLines.push({+ ...keys,+ accountId: asset.assetAccountId,+ description: "Remove asset at cost",+ amount: round(credit("asset", asset.acquisitionCost)),+ journalLineReference: nanoid()+ });+ }++ return {+ description: `Sales Shipment ${shipmentReadableId}`,+ sourceType: "Sales Shipment",+ lines: journalLines+ };+ }++ /** An item a return shipment relieved: its quantity and cost, positive. */+ export type ReturnShipmentItem = {+ itemId: string;+ quantity: number;+ cost: number;+ replenishmentSystem: Enums["itemReplenishmentSystem"] | null;+ itemPostingGroupId: string | null;+ };++ /**+ * A return shipment: per item, one pair against inventory on+ * `shipment:<shipmentId>`, at zero cost too. A sales return (back to the+ * customer) debits COGS; a purchase return (back to the supplier) debits+ * GR/IR, reversing the receipt.+ */+ export function buildReturnShipmentJournal({+ sourceDocument,+ shipmentId,+ shipmentReadableId,+ locationId,+ partyId,+ partyTypeId,+ defaults,+ items+ }: {+ sourceDocument: "Sales Return Order" | "Purchase Return Order";+ shipmentId: string;+ shipmentReadableId: string;+ locationId: string | null;+ /** The customer of a sales return, the supplier of a purchase return. */+ partyId: string | null;+ partyTypeId: string | null;+ defaults: ShipmentAccountDefaults;+ items: ReturnShipmentItem[];+ }): ShipmentJournal {+ const isSalesReturn = sourceDocument === "Sales Return Order";+ const party = isSalesReturn+ ? { Customer: partyId, CustomerType: partyTypeId }+ : { Supplier: partyId, SupplierType: partyTypeId };++ const lines = items.flatMap((item): ShipmentJournalLine[] => {+ const inventory = resolveInventoryAccount(+ item.replenishmentSystem,+ defaults+ );+ const keys = {+ quantity: round(item.quantity),+ documentType: "Return Order" as const,+ documentId: shipmentId,+ documentLineReference: journalReference.to.shipment(shipmentId),+ journalLineReference: nanoid(),+ dimensions: {+ Item: item.itemId,+ ItemPostingGroup: item.itemPostingGroupId,+ Location: locationId,+ ...party+ }+ };+ return [+ isSalesReturn+ ? {+ ...keys,+ accountId: defaults.costOfGoodsSoldAccount,+ description: "Cost of Goods Sold",+ amount: round(debit("expense", item.cost))+ }+ : {+ ...keys,+ accountId: defaults.goodsReceivedNotInvoicedAccount,+ description: "Goods Received Not Invoiced",+ amount: round(debit("liability", item.cost))+ },+ {+ ...keys,+ accountId: inventory.account,+ description: inventory.description,+ amount: round(credit("asset", item.cost))+ }+ ];+ });++ return isSalesReturn+ ? {+ description: `Return Shipment ${shipmentReadableId}`,+ sourceType: "Sales Return Shipment",+ lines+ }+ : {+ description: `Purchase Return Shipment ${shipmentReadableId}`,+ sourceType: "Purchase Return Shipment",+ lines+ };+ }+ export async function postRentalShipment(+ db: Kysely<KyselyDatabase>,+ args: {+ shipmentId: string;+ companyId: string;+ userId: string;+ today: string;+ postingDate?: string;+ }+ ): Promise<void> {+ const { shipmentId, companyId, userId, today } = args;++ await db.transaction().execute(async (trx) => {+ const deliveredOn = args.postingDate ?? today;+ const future = futureDeliveryError(deliveredOn, today);+ if (future) throw new InvalidInputError(future);++ const shipment = await trx+ .selectFrom("shipment")+ .select(["id", "shipmentId", "sourceDocumentId", "status"])+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!shipment) throw new NotFoundError("Shipment not found");++ const assetLines = await trx+ .selectFrom("shipmentFixedAssetLine")+ .select(["id", "rentalAgreementLineId", "meter"])+ .where("shipmentId", "=", shipmentId)+ .where("companyId", "=", companyId)+ .where("shipped", "=", true)+ .where("rentalAgreementLineId", "is not", null)+ .orderBy("createdAt")+ .orderBy("id")+ .execute();+ if (assetLines.length === 0) {+ throw new InvalidInputError("Select at least one unit to deliver");+ }++ if (!shipment.sourceDocumentId) {+ throw new NotFoundError("Rental agreement not found");+ }+ const agreement = await lockAgreement(+ trx,+ companyId,+ shipment.sourceDocumentId+ );+ if (agreement.status !== "Active") {+ throw new InvalidInputError(+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are delivered from an Active agreement`+ );+ }++ const { linesById, assetsById } = await lockRentalUnits(+ trx,+ companyId,+ assetLines.map((line) => line.rentalAgreementLineId!)+ );++ const units = assetLines.map((assetLine) => {+ const lineId = assetLine.rentalAgreementLineId!;+ const line = linesById.get(lineId);+ const asset = line?.fixedAssetId+ ? assetsById.get(line.fixedAssetId)+ : undefined;+ const label = unitLabel(asset, lineId);+ if (!line || line.rentalAgreementId !== agreement.id) {+ throw new NotFoundError("Rental agreement line not found");+ }+ if (line.status !== "Pending") {+ throw new InvalidInputError(+ `${label} is ${line.status}; only a Pending unit can be delivered`+ );+ }+ if (asset?.outOfServiceSince) {+ throw new InvalidInputError(+ `${label} is out of service: ${asset.outOfServiceReason ?? "no reason given"}`+ );+ }+ return { line, meter: assetLine.meter };+ });++ for (const { line, meter } of units) {+ await trx+ .updateTable("rentalAgreementLine")+ .set({+ status: "On Rent",+ deliveredAt: deliveredOn,+ meterOut: meter,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", line.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ for (const { line } of units) {+ if (!line.trackedEntityId) continue;+ await insertUnitActivity(trx, {+ type: "Rental Delivery",+ direction: "input",+ sourceDocument: "Shipment",+ sourceDocumentId: shipment.id,+ sourceDocumentReadableId: shipment.shipmentId,+ attributes: { Shipment: shipment.id, "Rental Agreement": agreement.id },+ trackedEntityId: line.trackedEntityId,+ companyId,+ userId+ });+ }++ await trx+ .updateTable("shipment")+ .set({+ status: "Posted",+ postingDate: deliveredOn,+ postedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ });+ }++ /** Voids a Posted rental shipment: its units go back to Pending, as if never+ * delivered. Refused once a unit has moved on or its accrued rent is in a+ * posted or draft recognition run. */+ export async function voidRentalShipment(+ db: Kysely<KyselyDatabase>,+ args: { shipmentId: string; companyId: string; userId: string }+ ): Promise<void> {+ const { shipmentId, companyId, userId } = args;++ await db.transaction().execute(async (trx) => {+ const shipment = await trx+ .selectFrom("shipment")+ .select(["id", "shipmentId", "sourceDocumentId"])+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!shipment) throw new NotFoundError("Shipment not found");++ const assetLines = await trx+ .selectFrom("shipmentFixedAssetLine")+ .select(["id", "rentalAgreementLineId"])+ .where("shipmentId", "=", shipmentId)+ .where("companyId", "=", companyId)+ .where("shipped", "=", true)+ .where("rentalAgreementLineId", "is not", null)+ .orderBy("createdAt")+ .orderBy("id")+ .execute();++ if (!shipment.sourceDocumentId) {+ throw new NotFoundError("Rental agreement not found");+ }+ const agreement = await lockAgreement(+ trx,+ companyId,+ shipment.sourceDocumentId+ );++ const lineIds = assetLines.map((line) => line.rentalAgreementLineId!);+ const { linesById, assetsById } = await lockRentalUnits(+ trx,+ companyId,+ lineIds+ );++ const accruals =+ lineIds.length === 0+ ? []+ : await trx+ .selectFrom("revenueRecognitionSchedule")+ .select(["rentalAgreementLineId", "status", "runLineId"])+ .where("type", "=", "Accrual")+ .where("companyId", "=", companyId)+ .where("rentalAgreementLineId", "in", lineIds)+ .execute();++ const units = assetLines.map((assetLine) => {+ const lineId = assetLine.rentalAgreementLineId!;+ const line = linesById.get(lineId);+ const asset = line?.fixedAssetId+ ? assetsById.get(line.fixedAssetId)+ : undefined;+ if (!line || line.rentalAgreementId !== agreement.id) {+ throw new NotFoundError("Rental agreement line not found");+ }+ const rows = accruals.filter(+ (row) => row.rentalAgreementLineId === lineId+ );+ const accrual: "Posted" | "Draft run" | null = rows.some(+ (row) => row.status === "Posted"+ )+ ? "Posted"+ : rows.some((row) => row.status === "Planned" && row.runLineId)+ ? "Draft run"+ : null;+ return {+ line,+ label: unitLabel(asset, lineId),+ status: line.status,+ accrual+ };+ });++ const blocker = rentalShipmentVoidBlocker(units);+ if (blocker) throw new InvalidInputError(blocker);++ if (lineIds.length > 0) {+ await trx+ .deleteFrom("revenueRecognitionSchedule")+ .where("type", "=", "Accrual")+ .where("status", "=", "Planned")+ .where("runLineId", "is", null)+ .where("companyId", "=", companyId)+ .where("rentalAgreementLineId", "in", lineIds)+ .execute();+ }++ for (const { line } of units) {+ await trx+ .updateTable("rentalAgreementLine")+ .set({+ status: "Pending",+ deliveredAt: null,+ meterOut: null,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", line.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ for (const { line } of units) {+ if (!line.trackedEntityId) continue;+ await insertUnitActivity(trx, {+ type: "Void Shipment",+ direction: "input",+ sourceDocument: "Shipment",+ sourceDocumentId: shipment.id,+ sourceDocumentReadableId: shipment.shipmentId,+ attributes: { Shipment: shipment.id, "Rental Agreement": agreement.id },+ trackedEntityId: line.trackedEntityId,+ companyId,+ userId+ });+ }++ await trx+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ });+ }++ // Locks the agreement lines a rental document names and reads their assets,+ // whose numbers name the units in a refusal.+ async function lockRentalUnits(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ lineIds: string[]+ ) {+ const lines =+ lineIds.length === 0+ ? []+ : await trx+ .selectFrom("rentalAgreementLine")+ .select([+ "id",+ "rentalAgreementId",+ "status",+ "fixedAssetId",+ "trackedEntityId"+ ])+ .where("id", "in", lineIds)+ .where("companyId", "=", companyId)+ .forUpdate()+ .execute();+ const linesById = new Map(lines.map((line) => [line.id, line]));++ const assetIds = lines+ .map((line) => line.fixedAssetId)+ .filter((id): id is string => id !== null);+ const assets =+ assetIds.length === 0+ ? []+ : await trx+ .selectFrom("fixedAsset")+ .select([+ "id",+ "fixedAssetId",+ "name",+ "outOfServiceSince",+ "outOfServiceReason"+ ])+ .where("id", "in", assetIds)+ .where("companyId", "=", companyId)+ .execute();+ const assetsById = new Map(assets.map((asset) => [asset.id, asset]));+ return { linesById, assetsById };+ }++ export const postShipmentInput = z.object({+ type: z.enum(["post", "void"]),+ shipmentId: z.string(),+ /** The delivery date of a rental shipment. Other sources ignore it. */+ postingDate: z+ .string()+ .regex(/^\d{4}-\d{2}-\d{2}$/)+ .optional()+ });++ export const postShipmentPermission = {+ update: "inventory"+ } satisfies PermissionRule<z.output<typeof postShipmentInput>>;++ /** Posts or voids a shipment: stock, tracked entities, COGS and journal rows. */+ export async function postShipment(+ ctx: ServiceContext,+ raw: z.input<typeof postShipmentInput>+ ) {+ const { type, shipmentId, postingDate } = postShipmentInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ logger.info({ type, shipmentId, userId, companyId });+ const fixedAssetWrites = new FixedAssetWrites();+ if (type === "post")+ await assertPostable(db, "shipment", shipmentId, companyId);+ try {+ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ const [shipment, shipmentLines, shipmentLineTracking] = await inOrder([+ // The client is service-role: authorization proved the caller may+ // act in companyId, not that shipmentId belongs to it.+ () => maybeSingle(db, "shipment", { id: shipmentId, companyId }),+ () =>+ many<+ "shipmentLine",+ Tables["shipmentLine"]["Row"] & {+ fulfillment: Tables["fulfillment"]["Row"] | null;+ }+ >(+ db,+ "shipmentLine",+ { shipmentId, companyId },+ {+ embed: {+ fulfillment: { table: "fulfillment", via: "fulfillmentId" }+ }+ }+ ),+ () =>+ many(db, "trackedEntity", {+ attributes: contains({ Shipment: shipmentId }),+ companyId+ })+ ]);++ if (shipment.error) throw new Error("Failed to fetch shipment");+ if (!shipment.data) throw new NotFoundError("Shipment not found");+ const shipmentHeader = shipment.data;+ if (shipmentLines.error) throw new Error("Failed to fetch shipment lines");++ const itemIds = shipmentLines.data.reduce<string[]>((acc, shipmentLine) => {+ if (shipmentLine.itemId && !acc.includes(shipmentLine.itemId)) {+ acc.push(shipmentLine.itemId);+ }+ return acc;+ }, []);++ const jobIds = shipmentLines.data.reduce<string[]>((acc, shipmentLine) => {+ if (+ shipmentLine.fulfillment?.jobId &&+ !acc.includes(shipmentLine.fulfillment?.jobId)+ ) {+ acc.push(shipmentLine.fulfillment?.jobId);+ }+ return acc;+ }, []);++ const [items, itemCosts, jobs] = await inOrder([+ () =>+ many(+ db,+ "item",+ { id: itemIds, companyId },+ { columns: ["id", "itemTrackingType", "replenishmentSystem"] }+ ),+ () =>+ many(+ db,+ "itemCost",+ { itemId: itemIds },+ { columns: ["itemId", "itemPostingGroupId"] }+ ),+ () =>+ many(+ db,+ "job",+ { companyId, id: jobIds },+ {+ columns: [+ "id",+ "quantity",+ "quantityComplete",+ "quantityShipped",+ "status"+ ]+ }+ )+ ]);+ if (items.error) {+ throw new Error("Failed to fetch items");+ }+ if (itemCosts.error) {+ throw new Error("Failed to fetch item costs");+ }+ if (jobs.error) {+ throw new Error("Failed to fetch jobs");+ }++ const splitEntityIds: string[] = [];++ switch (type) {+ case "post": {+ switch (shipmentHeader.sourceDocument) {+ case "Sales Order": {+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [salesOrder, salesOrderLines, salesOrderDelivery] =+ await inOrder([+ () =>+ single(db, "salesOrder", {+ id: shipmentHeader.sourceDocumentId+ }),+ () =>+ many(db, "salesOrderLine", {+ salesOrderId: shipmentHeader.sourceDocumentId+ }),+ () =>+ single(+ db,+ "salesOrderShipment",+ { companyId, id: shipmentHeader.sourceDocumentId },+ { columns: ["shippingCost"] }+ )+ ]);+ if (salesOrder.error)+ throw new Error("Failed to fetch purchase order");+ if (salesOrderLines.error)+ throw new Error("Failed to fetch sales order lines");+ if (salesOrderDelivery.error)+ throw new Error("Failed to fetch sales order delivery");++ const customer = await single(db, "customer", {+ id: salesOrder.data.customerId,+ companyId+ });+ if (customer.error) throw new Error("Failed to fetch customer");++ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );+ if (companyRecord.error) throw new Error("Failed to fetch company");+ const companyGroupId = companyRecord.data.companyGroupId;++ // Every shipment posts its journal: Provisional before the+ // company's accounting cutover, Posted after it. Read here to+ // decide whether to resolve a period, and again inside the+ // transaction.+ const postingStatus = await journalPostingStatus(db, companyId);++ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ // Guarded like the return-shipment branches: a company with no+ // group has no dimensions to read.+ const dimensions = companyGroupId+ ? await many(+ db,+ "dimension",+ {+ companyGroupId,+ active: true,+ entityType: [+ "Customer",+ "CustomerType",+ "Item",+ "ItemPostingGroup",+ "Location",+ "CostCenter",+ "FixedAssetClass"+ ]+ },+ { columns: ["id", "entityType"] }+ )+ : null;++ const dimensionMap = new Map<string, string>();+ if (dimensions?.data) {+ for (const dim of dimensions.data) {+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);+ }+ }++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // The journal's facts; the lines are built once the+ // transaction has relieved each item's cost.+ const journalShipmentLines: SalesShipmentLine[] = [];+ const fixedAssetSales: FixedAssetSale[] = [];++ const jobUpdates: Record<+ string,+ Database["public"]["Tables"]["job"]["Update"]+ > = {};++ const serialNumbersConsumed: string[] = [];++ const locationId = shipmentHeader.locationId;++ // A serial or batch leaves the bin it actually holds stock in; the+ // line's bin is only a default. A unit whose bin cannot cover the+ // quantity is refused rather than driving that bin negative.+ const trackedEntityBins = await getTrackedEntityBins(db, {+ trackedEntityIds: (shipmentLineTracking.data ?? []).map(+ (tracking) => tracking.id+ ),+ locationIds: [+ ...new Set(+ shipmentLines.data.flatMap(+ (line) => line.locationId ?? locationId ?? []+ )+ )+ ],+ companyId+ });+ const sourceBin = (+ trackedEntityId: string | undefined,+ lineLocationId: string | null,+ quantity: number+ ): string | null => {+ const bin =+ trackedEntityId && lineLocationId+ ? trackedEntityBins(trackedEntityId, lineLocationId)+ : undefined;+ if (!bin || round(bin.quantity) < round(quantity)) {+ const readableId =+ shipmentLineTracking.data?.find(+ (tracking) => tracking.id === trackedEntityId+ )?.readableId ??+ trackedEntityId ??+ "A tracked item";+ throw new Error(+ bin+ ? `${readableId} has only ${round(bin.quantity)} in one storage unit, ${round(quantity)} needed. Move it into one storage unit first`+ : `${readableId} has no stock to ship at this location`+ );+ }+ return bin.storageUnitId;+ };++ for await (const shipmentLine of shipmentLines.data) {+ if (+ shipmentLine.fulfillment?.type === "Job" &&+ shipmentLine.fulfillment?.jobId+ ) {+ // Update quantity shipped on job, accumulating totals from multiple shipments+ const jobId = shipmentLine.fulfillment.jobId;+ const currentJob = jobs.data.find((j) => j.id === jobId);++ // Log job and shipment line data to debug NaN issues+ logger.info("Processing job update:", {+ jobId,+ currentJob: currentJob+ ? {+ id: currentJob.id,+ quantity: currentJob.quantity,+ quantityShipped: currentJob.quantityShipped,+ quantityComplete: currentJob.quantityComplete,+ status: currentJob.status+ }+ : null,+ shipmentLine: {+ id: shipmentLine.id,+ shippedQuantity: shipmentLine.shippedQuantity,+ shippedQuantityType: typeof shipmentLine.shippedQuantity+ }+ });++ const currentQuantityShipped = currentJob?.quantityShipped ?? 0;++ // Ensure shippedQuantity is a valid number to prevent "100NaN" errors+ const shippedQuantity =+ typeof shipmentLine.shippedQuantity === "number" &&+ !isNaN(shipmentLine.shippedQuantity)+ ? shipmentLine.shippedQuantity+ : 0;++ logger.info("Calculated values:", {+ currentQuantityShipped,+ shippedQuantity,+ newTotal: currentQuantityShipped + shippedQuantity,+ jobQuantity: currentJob?.quantity+ });++ // If we've already updated this job in this transaction, use that as the base+ // instead of the current DB value to avoid double counting+ if (jobUpdates[jobId]) {+ const newQuantityShipped =+ (jobUpdates[jobId]?.quantityShipped ?? 0) + shippedQuantity;+ const newQuantityComplete =+ currentJob?.status === "Completed"+ ? currentJob?.quantityComplete+ : Math.max(+ currentJob?.quantityComplete ?? 0,+ shippedQuantity+ );+ const newStatus =+ currentQuantityShipped + shippedQuantity >=+ (currentJob?.quantity ?? 0)+ ? "Completed"+ : currentJob?.status;++ logger.info("Updating existing job update:", {+ jobId,+ previousUpdate: jobUpdates[jobId],+ newUpdate: {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped+ }+ });++ jobUpdates[jobId] = {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped+ };+ } else {+ const newQuantityShipped =+ currentQuantityShipped + shippedQuantity;+ const newQuantityComplete =+ currentJob?.status === "Completed"+ ? currentJob?.quantityComplete+ : Math.max(+ currentJob?.quantityComplete ?? 0,+ shippedQuantity+ );+ const newStatus =+ currentQuantityShipped + shippedQuantity >=+ (currentJob?.quantity ?? 0)+ ? "Completed"+ : currentJob?.status;++ logger.info("Creating new job update:", {+ jobId,+ update: {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped+ }+ });++ jobUpdates[jobId] = {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped+ };+ }+ }++ const shipmentLineItem = items.data.find(+ (item) => item.id === shipmentLine.itemId+ );+ const itemTrackingType =+ shipmentLineItem?.itemTrackingType ?? "Inventory";++ // Default shippedQuantity to 0 if not defined or NaN+ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ if (itemTrackingType === "Inventory") {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-shippedQuantity),+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipmentHeader.id ?? undefined,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });+ }++ if (shipmentLine.requiresBatchTracking) {+ const batchId = shipmentLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ )?.id;+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-shippedQuantity),+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: sourceBin(+ batchId,+ shipmentLine.locationId ?? locationId,+ shippedQuantity+ ),+ entryType: "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipmentHeader.id ?? undefined,+ trackedEntityId: batchId,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });+ }++ if (shipmentLine.requiresSerialTracking) {+ const lineTracking = shipmentLineTracking.data?.filter(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ );++ lineTracking?.forEach((tracking) => {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -1,+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: sourceBin(+ tracking.id,+ shipmentLine.locationId ?? locationId,+ 1+ ),+ entryType: "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipmentHeader.id ?? undefined,+ trackedEntityId: tracking.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });++ if (tracking.id) {+ serialNumbersConsumed.push(tracking.id);+ }+ });+ }++ journalShipmentLines.push({+ shipmentLineId: shipmentLine.id,+ itemId: shipmentLine.itemId,+ shippedQuantity,+ itemTrackingType,+ replenishmentSystem:+ shipmentLineItem?.replenishmentSystem ?? null,+ itemPostingGroupId:+ itemCosts.data.find(+ (cost) => cost.itemId === shipmentLine.itemId+ )?.itemPostingGroupId ?? null,+ locationId: shipmentLine.locationId ?? locationId ?? null+ });+ }++ const shipmentLinesBySalesOrderLineId = shipmentLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["shipmentLine"]["Row"][]+ >+ >((acc, shipmentLine) => {+ if (shipmentLine.lineId) {+ acc[shipmentLine.lineId] = [+ ...(acc[shipmentLine.lineId] ?? []),+ shipmentLine+ ];+ }+ return acc;+ }, {});++ const salesOrderLineUpdates = salesOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ >+ >((acc, salesOrderLine) => {+ const shipmentLines =+ shipmentLinesBySalesOrderLineId[salesOrderLine.id];+ if (+ shipmentLines &&+ shipmentLines.length > 0 &&+ salesOrderLine.saleQuantity &&+ salesOrderLine.saleQuantity > 0+ ) {+ const shippedQuantity = shipmentLines.reduce(+ (acc, shipmentLine) => {+ const safeShippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ return acc + safeShippedQuantity;+ },+ 0+ );++ const newQuantitySent =+ (salesOrderLine.quantitySent ?? 0) + shippedQuantity;++ const sentComplete =+ salesOrderLine.sentComplete ||+ newQuantitySent >= salesOrderLine.saleQuantity;++ const updates: Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ > = {+ ...acc,+ [salesOrderLine.id]: {+ quantitySent: newQuantitySent,+ sentComplete+ }+ };++ if (sentComplete && !salesOrderLine.sentDate) {+ updates[salesOrderLine.id]!.sentDate = today;+ }++ return updates;+ }++ return acc;+ }, {});++ // Process Fixed Asset SO lines (no shipment lines — handled directly from SO)+ const { data: shipmentFaLines } = await many(+ db,+ "shipmentFixedAssetLine",+ { shipmentId, shipped: true, companyId },+ { columns: ["salesOrderLineId", "serialNumber"] }+ );+ const shippedFaSoLineIds = new Set(+ (shipmentFaLines ?? [])+ .filter((r) => r.salesOrderLineId !== null)+ .map((r) => r.salesOrderLineId)+ );++ const faSalesOrderLines = salesOrderLines.data.filter(+ (sol) =>+ sol.salesOrderLineType === "Fixed Asset" &&+ sol.assetId &&+ !sol.sentComplete &&+ sol.saleQuantity &&+ sol.saleQuantity > 0 &&+ shippedFaSoLineIds.has(sol.id)+ );++ for (const faSoLine of faSalesOrderLines) {+ const assetRecord = await single<+ "fixedAsset",+ Pick<+ Tables["fixedAsset"]["Row"],+ | "id"+ | "status"+ | "acquisitionCost"+ | "accumulatedDepreciation"+ | "locationId"+ | "fixedAssetClassId"+ > & {+ fixedAssetClass: Pick<+ Tables["fixedAssetClass"]["Row"],+ | "assetAccountId"+ | "accumulatedDepreciationAccountId"+ | "writeOffAccountId"+ > | null;+ }+ >(+ db,+ "fixedAsset",+ { companyId, id: faSoLine.assetId! },+ {+ columns: [+ "id",+ "status",+ "acquisitionCost",+ "accumulatedDepreciation",+ "locationId",+ "fixedAssetClassId"+ ],+ embed: {+ fixedAssetClass: {+ table: "fixedAssetClass",+ via: "fixedAssetClassId",+ columns: [+ "assetAccountId",+ "accumulatedDepreciationAccountId",+ "writeOffAccountId"+ ]+ }+ }+ }+ );++ if (assetRecord.error)+ throw new Error("Failed to fetch fixed asset for disposal");+ fixedAssetWrites.overlay(faSoLine.assetId!, assetRecord.data);++ const assetClass = assetRecord.data.fixedAssetClass!;+ const fixedAssetSale: FixedAssetSale = {+ salesOrderLineId: faSoLine.id,+ acquisitionCost: Number(assetRecord.data.acquisitionCost),+ accumulatedDepreciation: Number(+ assetRecord.data.accumulatedDepreciation+ ),+ assetAccountId: assetClass.assetAccountId,+ accumulatedDepreciationAccountId:+ assetClass.accumulatedDepreciationAccountId,+ writeOffAccountId: assetClass.writeOffAccountId,+ locationId: locationId ?? assetRecord.data.locationId ?? null,+ fixedAssetClassId: assetRecord.data.fixedAssetClassId ?? null+ };+ fixedAssetSales.push(fixedAssetSale);+ const nbv = netBookValue(fixedAssetSale);++ fixedAssetWrites.patch(faSoLine.assetId!, {+ status: "Disposed",+ disposalDate: today,+ disposalMethod: "Sale",+ updatedBy: userId+ });++ const disposal: Database["public"]["Tables"]["fixedAssetDisposal"]["Insert"] =+ {+ fixedAssetId: faSoLine.assetId!,+ disposalMethod: "Sale",+ disposalDate: today,+ saleProceeds: 0,+ netBookValueAtDisposal: nbv,+ // Gain/loss is unknown until proceeds are invoiced; the NBV is+ // held in the disposal clearing account, not expensed, so we+ // record 0 here (the invoice sets the real gain/loss).+ gainLoss: 0,+ companyId,+ createdBy: userId+ };+ fixedAssetWrites.defer((trx) =>+ insertRows(trx, "fixedAssetDisposal", disposal)+ );++ salesOrderLineUpdates[faSoLine.id] = {+ quantitySent: faSoLine.saleQuantity,+ sentComplete: true,+ sentDate: today+ };+ }++ const trackedEntitySplits: Record<+ string,+ {+ originalEntityId: string;+ originalQuantity: number;+ shippedQuantity: number;+ remainingQuantity: number;+ readableId: string | null;+ attributes: TrackedEntityAttributes;+ sourceDocument: string;+ sourceDocumentId: string;+ sourceDocumentReadableId: string | null;+ companyId: string;+ itemId: string | null;+ expirationDate: string | null;+ }+ > = {};++ const trackedEntityUpdates =+ shipmentLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ const shipmentLine = shipmentLines.data?.find(+ (shipmentLine) =>+ shipmentLine.id ===+ (trackedEntity.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ );++ // Round both, then ask isFullDraw first: a residue lot+ // (holding 0.020000000000000018 after an earlier split)+ // shipped in full reads as `shipped < quantity` on a raw+ // compare, and the split loop below then throws the builder's+ // `draw >= parentQty` guard on a legitimate full shipment.+ const entityQuantity = round(Number(trackedEntity.quantity));+ const shippedQuantity = round(+ Number(shipmentLine?.shippedQuantity)+ );+ if (+ shipmentLine?.shippedQuantity !== undefined &&+ trackedEntity.quantity !== undefined &&+ !isFullDraw(entityQuantity, shippedQuantity) &&+ shippedQuantity < entityQuantity+ ) {+ // Partial shipment → split. The shelf entity keeps its id+ // and is only decremented (split loop below); the SHIPPED+ // portion departs as a new Consumed child. No Consumed+ // update on the parent here.+ trackedEntitySplits[trackedEntity.id] = {+ originalEntityId: trackedEntity.id,+ originalQuantity: entityQuantity,+ shippedQuantity,+ remainingQuantity: round(entityQuantity - shippedQuantity),+ readableId: trackedEntity.readableId,+ attributes:+ trackedEntity.attributes as TrackedEntityAttributes,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ companyId: trackedEntity.companyId,+ itemId: trackedEntity.itemId ?? null,+ expirationDate: trackedEntity.expirationDate ?? null+ };+ return acc;+ }++ acc[trackedEntity.id] = {+ status: "Consumed",+ // Keep the ?? fallback exactly as it was and just round it:+ // a null shippedQuantity must still fall through to the+ // entity's own quantity, which `!== undefined` would not do.+ quantity: round(+ Number(+ shipmentLine?.shippedQuantity ?? trackedEntity.quantity+ )+ )+ };++ return acc;+ }, {}) ?? {};++ // Resolve accounting period BEFORE opening the Kysely transaction.+ // getCurrentAccountingPeriod uses the Supabase REST client; calling+ // it mid-transaction parks the pg connection in idle-in-transaction+ // (ClientRead) while the REST hop runs, and any hang there leaves+ // an orphan that exhausts the pool (size 1) for every subsequent+ // post-shipment invocation. A Provisional journal has no+ // accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ await fixedAssetWrites.apply(trx, companyId);+ for await (const [salesOrderLineId, update] of Object.entries(+ salesOrderLineUpdates+ )) {+ await trx+ .updateTable("salesOrderLine")+ .set(update)+ .where("id", "=", salesOrderLineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ const salesOrderLines = await trx+ .selectFrom("salesOrderLine")+ .select([+ "id",+ "salesOrderLineType",+ "invoicedComplete",+ "sentComplete"+ ])+ .where("salesOrderId", "=", salesOrder.data.id)+ .execute();++ const areAllLinesInvoiced = salesOrderLines.every(+ (line) =>+ line.salesOrderLineType === "Comment" || line.invoicedComplete+ );++ const areAllLinesShipped = salesOrderLines.every(+ (line) =>+ line.salesOrderLineType === "Comment" ||+ line.salesOrderLineType === "Service" ||+ line.sentComplete+ );++ let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =+ "To Ship and Invoice";+ if (areAllLinesInvoiced && areAllLinesShipped) {+ status = "Completed";+ } else if (areAllLinesShipped) {+ status = "To Invoice";+ } else if (areAllLinesInvoiced) {+ status = "To Ship";+ }++ await trx+ .updateTable("salesOrder")+ .set({+ status+ })+ .where("id", "=", salesOrder.data.id)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .updateTable("shipment")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();++ if (+ Object.keys(trackedEntityUpdates).length > 0 ||+ Object.keys(trackedEntitySplits).length > 0+ ) {+ const trackedActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ attributes: {+ Shipment: shipmentId,+ "Sales Order": salesOrder.data.id+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();++ const trackedActivityId = trackedActivity[0]!.id;++ // Handle batch splits first: the shelf entity keeps its id+ // and is decremented; the SHIPPED portion departs as a new+ // Consumed child carrying the shipment attributes.+ for await (const splitInfo of Object.values(+ trackedEntitySplits+ )) {+ const shipmentLine = shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ );++ const shippedChildId = nanoid();+ const parentAttributes = (splitInfo.attributes ??+ {}) as Record<string, unknown>;++ const split = buildBatchSplitRecords({+ parent: {+ id: splitInfo.originalEntityId,+ readableId: splitInfo.readableId,+ quantity: splitInfo.originalQuantity,+ sourceDocument: splitInfo.sourceDocument,+ sourceDocumentId: splitInfo.sourceDocumentId,+ sourceDocumentReadableId:+ splitInfo.sourceDocumentReadableId,+ itemId: splitInfo.itemId,+ expirationDate: splitInfo.expirationDate,+ attributes: parentAttributes+ },+ drawQuantity: splitInfo.shippedQuantity,+ childId: shippedChildId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Shipment",+ activitySourceDocumentId: shipmentId,+ // The same bin the shipment's own row draws from.+ bin: {+ storageUnitId: sourceBin(+ splitInfo.originalEntityId,+ shipmentLine?.locationId ?? locationId,+ splitInfo.shippedQuantity+ ),+ locationId+ },+ itemLedgerItemId: shipmentLine?.itemId ?? null,+ companyId: splitInfo.companyId,+ userId,+ postingDate: today,+ childStatus: "Consumed"+ });++ await trx+ .insertInto("trackedActivity")+ .values({+ ...split.activityInsert,+ attributes: split.activityInsert+ .attributes as unknown as Json,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ createdAt: today+ })+ .execute();++ await trx+ .insertInto("trackedEntity")+ .values({+ ...split.childEntityInsert,+ attributes: split.childEntityInsert+ .attributes as unknown as Json,+ createdAt: today+ } as Insertable<KyselyDatabase["trackedEntity"]>)+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values({+ ...split.activityInputInsert,+ createdAt: today+ })+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values({+ ...split.activityOutputInsert,+ createdAt: today+ })+ .execute();++ // The retained parent is only decremented and LOSES the+ // shipment attributes — they belong to the shipped child.+ const retainedAttributes = { ...parentAttributes };+ delete retainedAttributes.Shipment;+ delete retainedAttributes["Shipment Line"];+ delete retainedAttributes["Shipment Line Index"];++ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: split.parentUpdate.quantity,+ attributes: retainedAttributes as unknown as Json+ })+ .where("id", "=", splitInfo.originalEntityId)+ .where("companyId", "=", companyId)+ .execute();++ itemLedgerInserts.push(+ ...(split.ledgerInserts.map((ledgerRow) => ({+ ...ledgerRow,+ quantity: round(ledgerRow.quantity)+ })) as typeof itemLedgerInserts)+ );++ // The shipment's own ledger rows (built per line above)+ // and its activity input book against the shipped child.+ for (const ledger of itemLedgerInserts) {+ if (+ ledger.documentType === "Sales Shipment" &&+ ledger.trackedEntityId === splitInfo.originalEntityId+ ) {+ ledger.trackedEntityId = shippedChildId;+ }+ }++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId,+ trackedEntityId: shippedChildId,+ quantity: splitInfo.shippedQuantity,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }++ // Auto-print/labels retarget to the RETAINED parent (its+ // quantity changed); the shipped child needs no label.+ splitEntityIds.push(splitInfo.originalEntityId);+ }++ // Now handle the shipment consumption (full-quantity lots)+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ if (Object.keys(jobUpdates).length > 0) {+ logger.info("Final job updates to be applied:", jobUpdates);+ for await (const [jobId, update] of Object.entries(+ jobUpdates+ )) {+ logger.info(`Updating job ${jobId} with:`, update);+ await trx+ .updateTable("job")+ .set(update)+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Relieve each item's cost, then write the journal.+ const relievedCostByItem = new Map<string, number>();+ for (const [itemId, quantity] of shippedQuantityByItem(+ journalShipmentLines+ )) {+ const cogsResult = await calculateCOGS(trx, {+ itemId,+ quantity,+ companyId,+ trackedEntityIds: leavingTrackedEntityIds(+ itemLedgerInserts,+ itemId+ )+ });+ relievedCostByItem.set(itemId, cogsResult.totalCost);++ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: "Sale",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Sales Shipment",+ documentId: shipmentHeader.id ?? "",+ itemId,+ quantity: round(-quantity),+ cost: round(-cogsResult.totalCost),+ remainingQuantity: 0,+ companyId,+ postingDate: today+ })+ .execute();+ }++ const journal = buildSalesShipmentJournal({+ shipmentId: shipmentHeader.id,+ shipmentReadableId: shipmentHeader.shipmentId,+ externalDocumentId: salesOrder.data.customerReference,+ customerId: salesOrder.data.customerId,+ customerTypeId: customer.data.customerTypeId ?? null,+ defaults: accountDefaults.data,+ lines: journalShipmentLines,+ relievedCostByItem,+ fixedAssetSales+ });+ if (journal.lines.length > 0) {+ await insertShipmentJournal(trx, {+ journal,+ accountingPeriodId,+ postingDate: today,+ postingStatus,+ dimensionIdByEntity: dimensionMap,+ companyId,+ userId+ });+ }+ });+ break;+ }+ case "Purchase Order": {+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [purchaseOrder, purchaseOrderLines] = await inOrder([+ () =>+ single(db, "purchaseOrder", {+ id: shipmentHeader.sourceDocumentId+ }),+ () =>+ many(db, "purchaseOrderLine", {+ purchaseOrderId: shipmentHeader.sourceDocumentId+ })+ ]);+ if (purchaseOrder.error)+ throw new Error("Failed to fetch purchase order");+ if (purchaseOrderLines.error)+ throw new Error("Failed to fetch purchase order lines");++ const supplier = await single(db, "supplier", {+ id: purchaseOrder.data.supplierId,+ companyId+ });+ if (supplier.error) throw new Error("Failed to fetch supplier");++ const jobOperationsUpdates: Record<+ string,+ Database["public"]["Tables"]["jobOperation"]["Update"]+ > = {};++ for await (const shipmentLine of shipmentLines.data) {+ const purchaseOrderLine = purchaseOrderLines.data.find(+ (pol) => pol.id === shipmentLine.lineId+ );++ if (+ purchaseOrderLine?.jobId &&+ purchaseOrderLine.jobOperationId+ ) {+ // Update quantity shipped on job, accumulating totals from multiple shipments+ const jobOperationId = purchaseOrderLine.jobOperationId;++ jobOperationsUpdates[jobOperationId] = {+ status: "In Progress"+ };+ continue;+ }+ }++ const shipmentLinesByPurchaseOrderLineId =+ shipmentLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["shipmentLine"]["Row"][]+ >+ >((acc, shipmentLine) => {+ if (shipmentLine.lineId) {+ acc[shipmentLine.lineId] = [+ ...(acc[shipmentLine.lineId] ?? []),+ shipmentLine+ ];+ }+ return acc;+ }, {});++ const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ >+ >((acc, purchaseOrderLine) => {+ const shipmentLines =+ shipmentLinesByPurchaseOrderLineId[purchaseOrderLine.id];+ if (+ shipmentLines &&+ shipmentLines.length > 0 &&+ purchaseOrderLine.purchaseQuantity &&+ purchaseOrderLine.purchaseQuantity > 0+ ) {+ const shippedQuantity = shipmentLines.reduce(+ (acc, shipmentLine) => {+ const safeShippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ return acc + safeShippedQuantity;+ },+ 0+ );++ const newQuantityShipped =+ (purchaseOrderLine.quantityShipped ?? 0) + shippedQuantity;++ const updates: Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ > = {+ ...acc,+ [purchaseOrderLine.id]: {+ quantityShipped: newQuantityShipped+ }+ };++ return updates;+ }++ return acc;+ }, {});++ const trackedEntitySplits: Record<+ string,+ {+ originalEntityId: string;+ originalQuantity: number;+ shippedQuantity: number;+ remainingQuantity: number;+ readableId: string | null;+ attributes: TrackedEntityAttributes;+ sourceDocument: string;+ sourceDocumentId: string;+ sourceDocumentReadableId: string | null;+ companyId: string;+ itemId: string | null;+ expirationDate: string | null;+ }+ > = {};++ const trackedEntityUpdates =+ shipmentLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ const shipmentLine = shipmentLines.data?.find(+ (shipmentLine) =>+ shipmentLine.id ===+ (trackedEntity.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ );++ // Round both, then ask isFullDraw first: a residue lot+ // (holding 0.020000000000000018 after an earlier split)+ // shipped in full reads as `shipped < quantity` on a raw+ // compare, and the split loop below then throws the builder's+ // `draw >= parentQty` guard on a legitimate full shipment.+ const entityQuantity = round(Number(trackedEntity.quantity));+ const shippedQuantity = round(+ Number(shipmentLine?.shippedQuantity)+ );+ if (+ shipmentLine?.shippedQuantity !== undefined &&+ trackedEntity.quantity !== undefined &&+ !isFullDraw(entityQuantity, shippedQuantity) &&+ shippedQuantity < entityQuantity+ ) {+ // Partial shipment → split. The shelf entity keeps its id+ // and is only decremented (split loop below); the SHIPPED+ // portion departs as a new Consumed child. No update on+ // the parent here.+ trackedEntitySplits[trackedEntity.id] = {+ originalEntityId: trackedEntity.id,+ originalQuantity: entityQuantity,+ shippedQuantity,+ remainingQuantity: round(entityQuantity - shippedQuantity),+ readableId: trackedEntity.readableId,+ attributes:+ trackedEntity.attributes as TrackedEntityAttributes,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ companyId: trackedEntity.companyId,+ itemId: trackedEntity.itemId ?? null,+ expirationDate: trackedEntity.expirationDate ?? null+ };+ return acc;+ }++ acc[trackedEntity.id] = {+ // Keep the ?? fallback exactly as it was and just round it:+ // a null shippedQuantity must still fall through to the+ // entity's own quantity, which `!== undefined` would not do.+ quantity: round(+ Number(+ shipmentLine?.shippedQuantity ?? trackedEntity.quantity+ )+ )+ };++ return acc;+ }, {}) ?? {};++ await db.transaction().execute(async (trx) => {+ for await (const [purchaseOrderLineId, update] of Object.entries(+ purchaseOrderLineUpdates+ )) {+ await trx+ .updateTable("purchaseOrderLine")+ .set(update)+ .where("id", "=", purchaseOrderLineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ await trx+ .updateTable("shipment")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();++ if (+ Object.keys(trackedEntityUpdates).length > 0 ||+ Object.keys(trackedEntitySplits).length > 0+ ) {+ const trackedActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ attributes: {+ Shipment: shipmentId,+ "Purchase Order": purchaseOrder.data.id+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();++ const trackedActivityId = trackedActivity[0]!.id;++ // Handle batch splits first: the shelf entity keeps its id+ // and is decremented; the SHIPPED portion departs as a new+ // Consumed child carrying the shipment attributes. This PO-+ // sourced path posts NO itemLedger for the split (matching the+ // pre-flip behavior — a PO/subcontract shipment's inventory+ // movement is not booked here); only genealogy + quantities.+ for await (const splitInfo of Object.values(+ trackedEntitySplits+ )) {+ const shipmentLine = shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ );++ const shippedChildId = nanoid();+ const parentAttributes = (splitInfo.attributes ??+ {}) as Record<string, unknown>;++ const split = buildBatchSplitRecords({+ parent: {+ id: splitInfo.originalEntityId,+ readableId: splitInfo.readableId,+ quantity: splitInfo.originalQuantity,+ sourceDocument: splitInfo.sourceDocument,+ sourceDocumentId: splitInfo.sourceDocumentId,+ sourceDocumentReadableId:+ splitInfo.sourceDocumentReadableId,+ itemId: splitInfo.itemId,+ expirationDate: splitInfo.expirationDate,+ attributes: parentAttributes+ },+ drawQuantity: splitInfo.shippedQuantity,+ childId: shippedChildId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Shipment",+ activitySourceDocumentId: shipmentId,+ bin: {+ storageUnitId: shipmentLine?.storageUnitId ?? null,+ locationId: shipmentHeader.locationId+ },+ itemLedgerItemId: shipmentLine?.itemId ?? null,+ companyId: splitInfo.companyId,+ userId,+ postingDate: today,+ childStatus: "Consumed"+ });++ await trx+ .insertInto("trackedActivity")+ .values({+ ...split.activityInsert,+ attributes: split.activityInsert+ .attributes as unknown as Json,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ createdAt: today+ })+ .execute();++ await trx+ .insertInto("trackedEntity")+ .values({+ ...split.childEntityInsert,+ attributes: split.childEntityInsert+ .attributes as unknown as Json,+ createdAt: today+ } as Insertable<KyselyDatabase["trackedEntity"]>)+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values({+ ...split.activityInputInsert,+ createdAt: today+ })+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values({+ ...split.activityOutputInsert,+ createdAt: today+ })+ .execute();++ // The retained parent is only decremented and LOSES the+ // shipment attributes — they belong to the shipped child.+ const retainedAttributes = { ...parentAttributes };+ delete retainedAttributes.Shipment;+ delete retainedAttributes["Shipment Line"];+ delete retainedAttributes["Shipment Line Index"];++ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: split.parentUpdate.quantity,+ attributes: retainedAttributes as unknown as Json+ })+ .where("id", "=", splitInfo.originalEntityId)+ .where("companyId", "=", companyId)+ .execute();++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId,+ trackedEntityId: shippedChildId,+ quantity: splitInfo.shippedQuantity,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }++ // Auto-print/labels retarget to the RETAINED parent (its+ // quantity changed); the shipped child needs no label.+ splitEntityIds.push(splitInfo.originalEntityId);+ }++ // Now handle the shipment consumption (full-quantity lots)+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }++ if (Object.keys(jobOperationsUpdates).length > 0) {+ logger.info(+ "Final job updates to be applied:",+ jobOperationsUpdates+ );+ for await (const [jobOperationId, update] of Object.entries(+ jobOperationsUpdates+ )) {+ logger.info(+ `Updating job operation ${jobOperationId} with:`,+ update+ );+ await trx+ .updateTable("jobOperation")+ .set(update)+ .where("id", "=", jobOperationId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ });+ break;+ }+ case "Outbound Transfer": {+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [warehouseTransfer, warehouseTransferLines] = await inOrder([+ () =>+ single(db, "warehouseTransfer", {+ id: shipmentHeader.sourceDocumentId+ }),+ () =>+ many(db, "warehouseTransferLine", {+ transferId: shipmentHeader.sourceDocumentId+ })+ ]);++ if (warehouseTransfer.error)+ throw new Error("Failed to fetch warehouse transfer");+ if (warehouseTransferLines.error)+ throw new Error("Failed to fetch warehouse transfer lines");++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const warehouseTransferLineUpdates: Record<+ string,+ Database["public"]["Tables"]["warehouseTransferLine"]["Update"]+ > = {};++ // Process each shipment line+ for await (const shipmentLine of shipmentLines.data) {+ const warehouseTransferLine = warehouseTransferLines.data.find(+ (line) => line.id === shipmentLine.lineId+ );++ if (!warehouseTransferLine) continue;++ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ // Update warehouse transfer line shipped quantity+ const newShippedQuantity =+ (warehouseTransferLine.shippedQuantity ?? 0) + shippedQuantity;++ warehouseTransferLineUpdates[warehouseTransferLine.id] = {+ shippedQuantity: newShippedQuantity+ };++ // Create item ledger entry for negative adjustment at source+ if (shippedQuantity !== 0) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-shippedQuantity), // Negative for outbound transfer+ locationId: shipmentLine.locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Transfer",+ documentType: "Transfer Shipment",+ documentId: warehouseTransfer.data?.transferId,+ externalDocumentId:+ shipmentHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ }+ }++ // Check if all lines are fully shipped+ const allLinesFullyShipped = warehouseTransferLines.data.every(+ (line) => {+ const updates = warehouseTransferLineUpdates[line.id];+ const shippedQty =+ updates?.shippedQuantity ?? line.shippedQuantity ?? 0;+ return shippedQty >= (line.quantity ?? 0);+ }+ );++ // Check if all lines are fully received+ const allLinesFullyReceived = warehouseTransferLines.data.every(+ (line) => {+ const receivedQty = line.receivedQuantity ?? 0;+ return receivedQty >= (line.quantity ?? 0);+ }+ );++ // Determine new warehouse transfer status+ let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =+ warehouseTransfer.data.status;++ if (allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "Completed";+ } else if (allLinesFullyShipped && !allLinesFullyReceived) {+ newStatus = "To Receive";+ } else if (!allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "To Ship";+ }++ await db.transaction().execute(async (trx) => {+ // Update warehouse transfer lines+ for await (const [lineId, update] of Object.entries(+ warehouseTransferLineUpdates+ )) {+ await trx+ .updateTable("warehouseTransferLine")+ .set(update)+ .where("id", "=", lineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Update warehouse transfer status+ await trx+ .updateTable("warehouseTransfer")+ .set({+ status: newStatus,+ transferDate: today,+ updatedBy: userId+ })+ .where("id", "=", warehouseTransfer.data.id)+ .where("companyId", "=", companyId)+ .execute();++ // Create item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update shipment status+ await trx+ .updateTable("shipment")+ .set({+ status: "Posted",+ postedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "Sales Return Order": {+ // Return-to-customer: ships rejected-claim goods back out of the+ // returned (On Hold) stock at carried cost. Dr COGS / Cr Inventory.+ // No RMA quantity bumps — dispositions carry the line state.+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");+ const salesReturnOrderId = shipmentHeader.sourceDocumentId;++ const salesReturnOrder = await single(db, "salesReturnOrder", {+ id: salesReturnOrderId,+ companyId+ });+ if (salesReturnOrder.error)+ throw new Error("Failed to fetch sales return order");+ // Same allowlist as the create server function: goods can only ship+ // back once they came in. A Draft RMA has never had its caps+ // validated; Cancelled cannot ship.+ if (+ !["To Receive", "Completed"].includes(+ salesReturnOrder.data.status+ )+ )+ throw new Error(+ `Cannot ship against a return order in ${salesReturnOrder.data.status} status`+ );++ // Every shipment posts its journal: Provisional before the+ // company's accounting cutover, Posted after it. Read here to+ // decide whether to resolve a period, and again inside the+ // transaction.+ const postingStatus = await journalPostingStatus(db, companyId);++ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ // GL dimensions for the return shipment journal (item, item group,+ // customer, customer type, location).+ const [company, customer] = await inOrder([+ () =>+ single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ ),+ () =>+ single(+ db,+ "customer",+ { id: salesReturnOrder.data.customerId, companyId },+ { columns: ["id", "customerTypeId"] }+ )+ ]);+ const dimensions = company?.data?.companyGroupId+ ? await many(+ db,+ "dimension",+ {+ companyGroupId: company.data.companyGroupId,+ active: true,+ entityType: [+ "CustomerType",+ "Customer",+ "ItemPostingGroup",+ "Item",+ "Location"+ ]+ },+ { columns: ["id", "entityType"] }+ )+ : null;+ const dimensionMap = new Map<string, string>();+ for (const dim of dimensions?.data ?? []) {+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);+ }+ const customerTypeId = customer?.data?.customerTypeId ?? null;++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const trackedEntityUpdates: Record<+ string,+ {+ status: Database["public"]["Tables"]["trackedEntity"]["Row"]["status"];+ quantity: number;+ }+ > = {};+ const itemShipmentQuantities: Record<string, number> = {};++ for (const shipmentLine of shipmentLines.data) {+ if (!shipmentLine.itemId) continue;+ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ if (shippedQuantity <= 0) continue;++ const itemTrackingType =+ items.data.find((i) => i.id === shipmentLine.itemId)+ ?.itemTrackingType ?? "Inventory";++ // Non-Inventory lines have no stock and no carried cost —+ // posting them would book COGS/costLedger with zero inventory+ // movement (the Sales Order branch excludes them the same way).+ if (itemTrackingType === "Non-Inventory") continue;++ const lineEntities = (shipmentLineTracking.data ?? []).filter(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ );++ if (itemTrackingType === "Inventory") {+ itemShipmentQuantities[shipmentLine.itemId] =+ (itemShipmentQuantities[shipmentLine.itemId] ?? 0) ++ shippedQuantity;+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-shippedQuantity),+ locationId: shipmentLine.locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Sales Return Shipment",+ documentId: shipmentHeader.id ?? undefined,+ externalDocumentId:+ shipmentHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ } else {+ // Whole-entity shipping (v1: return shipments do not split+ // partial batches — the picker picks whole entities). The+ // ledger writes one row per entity, so the entities must+ // account for the full shipped quantity — otherwise cost and+ // stock relief would diverge from what the line claims.+ const entitySum = lineEntities.reduce(+ (sum, entity) => sum + Number(entity.quantity ?? 0),+ 0+ );+ if (Math.abs(entitySum - shippedQuantity) > 0.00001) {+ throw new Error(+ `Shipment line ${shipmentLine.id}: tracked entities account for ${entitySum} of ${shippedQuantity} shipped — assign tracking before posting`+ );+ }+ itemShipmentQuantities[shipmentLine.itemId] =+ (itemShipmentQuantities[shipmentLine.itemId] ?? 0) ++ entitySum;+ for (const entity of lineEntities) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-(entity.quantity ?? 0)),+ locationId: shipmentLine.locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Sales Return Shipment",+ documentId: shipmentHeader.id ?? undefined,+ trackedEntityId: entity.id,+ externalDocumentId:+ shipmentHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ trackedEntityUpdates[entity.id] = {+ status: "Consumed",+ quantity: entity.quantity ?? 0+ };+ }+ }+ }++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ // Double-post guard: serialize on the shipment row — a second+ // concurrent post waits here, then sees Posted and aborts, so+ // ledger rows and journals can never double.+ const lockedShipment = await trx+ .selectFrom("shipment")+ .select(["status"])+ .where("id", "=", shipmentId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (+ lockedShipment.status === "Posted" ||+ lockedShipment.status === "Voided"+ ) {+ throw new Error(`Shipment is already ${lockedShipment.status}`);+ }++ await assertPostingStatusUnchanged(trx, companyId, postingStatus);++ const returnedItems: ReturnShipmentItem[] = [];+ for (const [itemId, quantity] of Object.entries(+ itemShipmentQuantities+ )) {+ const cogsResult = await calculateCOGS(trx, {+ itemId,+ quantity,+ companyId,+ trackedEntityIds: leavingTrackedEntityIds(+ itemLedgerInserts,+ itemId+ )+ });++ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: "Sale",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Sales Return Shipment",+ documentId: shipmentHeader.id ?? undefined,+ externalDocumentId:+ shipmentHeader.externalDocumentId ?? undefined,+ itemId,+ quantity: round(-quantity),+ cost: round(-cogsResult.totalCost),+ nominalCost: round(-cogsResult.totalCost),+ remainingQuantity: 0,+ companyId,+ postingDate: today+ })+ .execute();++ returnedItems.push({+ itemId,+ quantity,+ cost: cogsResult.totalCost,+ replenishmentSystem:+ items.data.find((i) => i.id === itemId)+ ?.replenishmentSystem ?? null,+ itemPostingGroupId:+ itemCosts.data.find((c) => c.itemId === itemId)+ ?.itemPostingGroupId ?? null+ });+ }++ const journal = buildReturnShipmentJournal({+ sourceDocument: "Sales Return Order",+ shipmentId: shipmentHeader.id,+ shipmentReadableId: shipmentHeader.shipmentId,+ locationId: shipmentHeader.locationId,+ partyId: salesReturnOrder.data.customerId,+ partyTypeId: customerTypeId,+ defaults: accountDefaults.data,+ items: returnedItems+ });+ if (journal.lines.length > 0) {+ await insertShipmentJournal(trx, {+ journal,+ accountingPeriodId,+ postingDate: today,+ postingStatus,+ dimensionIdByEntity: dimensionMap,+ companyId,+ userId+ });+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ if (Object.keys(trackedEntityUpdates).length > 0) {+ const activity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Return Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ attributes: {+ "Sales Return Order": salesReturnOrderId,+ Shipment: shipmentId,+ Employee: userId+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();+ const activityId = activity[0]?.id;+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ if (activityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }++ await trx+ .updateTable("shipment")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "Purchase Return Order": {+ // Supplier return: relieves inventory at carried cost against+ // GRNI (reverses the receipt posting). Cr Inventory / Dr GRNI.+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");+ const purchaseReturnOrderId = shipmentHeader.sourceDocumentId;++ const [purchaseReturnOrder, purchaseReturnOrderLines] =+ await inOrder([+ () =>+ single(db, "purchaseReturnOrder", {+ id: purchaseReturnOrderId,+ companyId+ }),+ () =>+ many(db, "purchaseReturnOrderLine", {+ purchaseReturnOrderId,+ companyId+ })+ ]);+ if (purchaseReturnOrder.error)+ throw new Error("Failed to fetch purchase return order");+ if (purchaseReturnOrderLines.error)+ throw new Error("Failed to fetch purchase return order lines");+ if (purchaseReturnOrder.data.status !== "To Ship")+ throw new Error(+ `Cannot ship against a return order in ${purchaseReturnOrder.data.status} status`+ );++ // Every shipment posts its journal: Provisional before the+ // company's accounting cutover, Posted after it. Read here to+ // decide whether to resolve a period, and again inside the+ // transaction.+ const postingStatus = await journalPostingStatus(db, companyId);++ const returnLineById = new Map(+ (purchaseReturnOrderLines.data ?? []).map((l) => [l.id, l])+ );++ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ // GL dimensions for the return shipment journal (item, item group,+ // supplier, supplier type, location).+ const [company, supplier] = await inOrder([+ () =>+ single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ ),+ () =>+ single(+ db,+ "supplier",+ { id: purchaseReturnOrder.data.supplierId, companyId },+ { columns: ["id", "supplierTypeId"] }+ )+ ]);+ const dimensions = company?.data?.companyGroupId+ ? await many(+ db,+ "dimension",+ {+ companyGroupId: company.data.companyGroupId,+ active: true,+ entityType: [+ "SupplierType",+ "Supplier",+ "ItemPostingGroup",+ "Item",+ "Location"+ ]+ },+ { columns: ["id", "entityType"] }+ )+ : null;+ const dimensionMap = new Map<string, string>();+ for (const dim of dimensions?.data ?? []) {+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);+ }+ const supplierTypeId = supplier?.data?.supplierTypeId ?? null;++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const trackedEntityUpdates: Record<+ string,+ {+ status: Database["public"]["Tables"]["trackedEntity"]["Row"]["status"];+ quantity: number;+ }+ > = {};+ const itemShipmentQuantities: Record<string, number> = {};+ const returnLineUpdates: Record<+ string,+ { quantityShipped: number; updatedBy: string }+ > = {};+ // A batch returned in part is split at post: the shelf entity keeps+ // its id and is decremented, the shipped portion departs as a new+ // Consumed child (mirrors the Sales Order path).+ const trackedEntitySplits: {+ entity: NonNullable<typeof shipmentLineTracking.data>[number];+ drawQuantity: number;+ storageUnitId: string | null;+ itemId: string | null;+ ledgerIndex: number;+ }[] = [];+ const splitChildEdges: { childId: string; quantity: number }[] = [];++ for (const shipmentLine of shipmentLines.data) {+ if (!shipmentLine.itemId || !shipmentLine.lineId) continue;+ const returnLine = returnLineById.get(shipmentLine.lineId);+ if (!returnLine)+ throw new Error(+ `Shipment line ${shipmentLine.id} does not map to a return order line`+ );+ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ if (shippedQuantity <= 0) continue;++ const itemTrackingType =+ items.data.find((i) => i.id === shipmentLine.itemId)+ ?.itemTrackingType ?? "Inventory";++ const existingUpdate = returnLineUpdates[returnLine.id];+ returnLineUpdates[returnLine.id] = {+ quantityShipped:+ (existingUpdate?.quantityShipped ??+ Number(returnLine.quantityShipped ?? 0)) + shippedQuantity,+ updatedBy: userId+ };++ // Non-Inventory lines still advance the return line (so the+ // order can settle) but post no ledger, cost, or GL — there is+ // no stock or carried cost to relieve, and booking GRNI against+ // nothing diverges the books from stock.+ if (itemTrackingType === "Non-Inventory") continue;++ const lineEntities = (shipmentLineTracking.data ?? []).filter(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ );++ if (itemTrackingType === "Inventory") {+ itemShipmentQuantities[shipmentLine.itemId] =+ (itemShipmentQuantities[shipmentLine.itemId] ?? 0) ++ shippedQuantity;+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-shippedQuantity),+ locationId: shipmentLine.locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Purchase Return Shipment",+ documentId: shipmentHeader.id ?? undefined,+ externalDocumentId:+ shipmentHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ } else {+ // Draw the shipped quantity from the linked entities. A fully+ // drawn entity is Consumed whole; a batch drawn in part is+ // split (below, in the transaction). The linked entities must+ // be able to cover the shipped quantity.+ const entitySum = lineEntities.reduce(+ (sum, entity) => sum + Number(entity.quantity ?? 0),+ 0+ );+ if (entitySum + 0.00001 < shippedQuantity) {+ throw new Error(+ `Shipment line ${shipmentLine.id}: tracked entities account for ${entitySum} of ${shippedQuantity} shipped — assign tracking before posting`+ );+ }+ let remaining = shippedQuantity;+ for (const entity of lineEntities) {+ if (remaining <= 0.00001) break;+ const entityQty = Number(entity.quantity ?? 0);+ const draw = Math.min(entityQty, remaining);+ remaining -= draw;+ itemShipmentQuantities[shipmentLine.itemId] =+ (itemShipmentQuantities[shipmentLine.itemId] ?? 0) + draw;+ const ledgerIndex = itemLedgerInserts.length;+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-draw),+ locationId: shipmentLine.locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Purchase Return Shipment",+ documentId: shipmentHeader.id ?? undefined,+ trackedEntityId: entity.id,+ externalDocumentId:+ shipmentHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ if (isFullDraw(entityQty, draw)) {+ trackedEntityUpdates[entity.id] = {+ status: "Consumed",+ quantity: round(entityQty)+ };+ } else {+ // Partial → split at post; the negative ledger row above is+ // retargeted to the departing child in the transaction.+ trackedEntitySplits.push({+ entity,+ drawQuantity: round(draw),+ storageUnitId: shipmentLine.storageUnitId,+ itemId: shipmentLine.itemId,+ ledgerIndex+ });+ }+ }+ }+ }++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ // Double-post guard: serialize on the shipment row — a second+ // concurrent post waits here, then sees Posted and aborts, so+ // ledger rows, journals, and quantityShipped can never double.+ const lockedShipment = await trx+ .selectFrom("shipment")+ .select(["status"])+ .where("id", "=", shipmentId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (+ lockedShipment.status === "Posted" ||+ lockedShipment.status === "Voided"+ ) {+ throw new Error(`Shipment is already ${lockedShipment.status}`);+ }++ await assertPostingStatusUnchanged(trx, companyId, postingStatus);++ // cancelPurchaseReturnOrder locks this same order row — re-check+ // the status under the lock so a cancel committed after our+ // pre-transaction read cannot be posted over.+ const lockedOrder = await trx+ .selectFrom("purchaseReturnOrder")+ .select(["status"])+ .where("id", "=", purchaseReturnOrderId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (lockedOrder.status !== "To Ship") {+ throw new Error(+ `Cannot ship against a return order in ${lockedOrder.status} status`+ );+ }++ // Split any batch returned in part: keep the shelf entity's id+ // (decremented), depart the shipped portion as a new Consumed+ // child, and retarget the negative Purchase Return Shipment+ // ledger row onto that child.+ for (const split of trackedEntitySplits) {+ const parent = split.entity;+ const parentAttributes =+ (parent.attributes as TrackedEntityAttributes | null) ?? {};+ const childId = nanoid();+ const built = buildBatchSplitRecords({+ parent: {+ id: parent.id,+ readableId: parent.readableId,+ quantity: Number(parent.quantity ?? 0),+ sourceDocument: parent.sourceDocument,+ sourceDocumentId: parent.sourceDocumentId,+ sourceDocumentReadableId: parent.sourceDocumentReadableId,+ itemId: parent.itemId ?? null,+ expirationDate: parent.expirationDate ?? null,+ attributes: parentAttributes as Record<string, unknown>+ },+ drawQuantity: split.drawQuantity,+ childId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Shipment",+ activitySourceDocumentId: shipmentId,+ bin: {+ storageUnitId: split.storageUnitId,+ locationId: shipmentHeader.locationId+ },+ itemLedgerItemId: split.itemId,+ companyId,+ userId,+ postingDate: today,+ childStatus: "Consumed"+ });++ await trx+ .insertInto("trackedActivity")+ .values({+ ...built.activityInsert,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ createdAt: today+ } as Insertable<KyselyDatabase["trackedActivity"]>)+ .execute();+ await trx+ .insertInto("trackedEntity")+ .values(+ built.childEntityInsert as Insertable<+ KyselyDatabase["trackedEntity"]+ >+ )+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values(built.activityInputInsert)+ .execute();+ await trx+ .insertInto("trackedActivityOutput")+ .values(built.activityOutputInsert)+ .execute();++ const retainedAttributes = {+ ...parentAttributes+ } as Record<string, unknown>;+ delete retainedAttributes.Shipment;+ delete retainedAttributes["Shipment Line"];+ delete retainedAttributes["Shipment Line Index"];+ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: built.parentUpdate.quantity,+ attributes: retainedAttributes as Json+ })+ .where("id", "=", parent.id)+ .where("companyId", "=", companyId)+ .execute();++ itemLedgerInserts.push(+ ...(built.ledgerInserts.map((ledger) => ({+ ...ledger,+ quantity: round(ledger.quantity)+ })) as typeof itemLedgerInserts)+ );+ itemLedgerInserts[split.ledgerIndex]!.trackedEntityId = childId;+ splitChildEdges.push({+ childId,+ quantity: split.drawQuantity+ });+ }++ const returnedItems: ReturnShipmentItem[] = [];+ for (const [itemId, quantity] of Object.entries(+ itemShipmentQuantities+ )) {+ const cogsResult = await calculateCOGS(trx, {+ itemId,+ quantity,+ companyId,+ trackedEntityIds: leavingTrackedEntityIds(+ itemLedgerInserts,+ itemId+ )+ });++ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Return Shipment",+ documentId: shipmentHeader.id ?? undefined,+ externalDocumentId:+ shipmentHeader.externalDocumentId ?? undefined,+ itemId,+ quantity: round(-quantity),+ cost: round(-cogsResult.totalCost),+ nominalCost: round(-cogsResult.totalCost),+ remainingQuantity: 0,+ companyId,+ postingDate: today+ })+ .execute();++ returnedItems.push({+ itemId,+ quantity,+ cost: cogsResult.totalCost,+ replenishmentSystem:+ items.data.find((i) => i.id === itemId)+ ?.replenishmentSystem ?? null,+ itemPostingGroupId:+ itemCosts.data.find((c) => c.itemId === itemId)+ ?.itemPostingGroupId ?? null+ });+ }++ const journal = buildReturnShipmentJournal({+ sourceDocument: "Purchase Return Order",+ shipmentId: shipmentHeader.id,+ shipmentReadableId: shipmentHeader.shipmentId,+ locationId: shipmentHeader.locationId,+ partyId: purchaseReturnOrder.data.supplierId,+ partyTypeId: supplierTypeId,+ defaults: accountDefaults.data,+ items: returnedItems+ });+ if (journal.lines.length > 0) {+ await insertShipmentJournal(trx, {+ journal,+ accountingPeriodId,+ postingDate: today,+ postingStatus,+ dimensionIdByEntity: dimensionMap,+ companyId,+ userId+ });+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ for await (const [lineId, update] of Object.entries(+ returnLineUpdates+ )) {+ await trx+ .updateTable("purchaseReturnOrderLine")+ .set(update)+ .where("id", "=", lineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Derived status (mirrors getPurchaseReturnOrderStatus): the+ // return is Completed once every line has shipped its authorized+ // quantity or been short-closed, otherwise it stays To Ship.+ const allLines = await trx+ .selectFrom("purchaseReturnOrderLine")+ .select(["quantity", "quantityShipped", "closedComplete"])+ .where("purchaseReturnOrderId", "=", purchaseReturnOrderId)+ .execute();+ const allShipped =+ allLines.length > 0 &&+ allLines.every(+ (l) =>+ l.closedComplete ||+ Number(l.quantityShipped) >= Number(l.quantity)+ );+ const returnStatus = allShipped+ ? ("Completed" as const)+ : ("To Ship" as const);+ await trx+ .updateTable("purchaseReturnOrder")+ .set({ status: returnStatus, updatedBy: userId })+ .where("id", "=", purchaseReturnOrderId)+ .where("companyId", "=", companyId)+ .execute();++ if (+ Object.keys(trackedEntityUpdates).length > 0 ||+ splitChildEdges.length > 0+ ) {+ const activity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Return Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ attributes: {+ "Purchase Return Order": purchaseReturnOrderId,+ Shipment: shipmentId,+ Employee: userId+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();+ const activityId = activity[0]?.id;+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ if (activityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ // The Consumed children departed by a split relieve on this+ // same Return Shipment activity.+ if (activityId) {+ for (const edge of splitChildEdges) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: edge.childId,+ quantity: edge.quantity,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }++ await trx+ .updateTable("shipment")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "Rental Agreement": {+ await postRentalShipment(db, {+ shipmentId,+ companyId,+ userId,+ today,+ postingDate+ });+ break;+ }++ default: {+ throw new Error(+ `Invalid source document type: ${shipmentHeader.sourceDocument}`+ );+ }+ }+ break;+ }+ case "void": {+ // A void replays quantity rollbacks — voiding a shipment that is not+ // Posted (e.g. already Voided) would subtract them a second time.+ if (shipmentHeader.status !== "Posted") {+ throw new Error(+ `Cannot void a shipment in ${shipmentHeader.status} status`+ );+ }+ // The enable reset the cost layers this shipment relieved.+ await refuseVoidBeforeCutover(+ db,+ companyId,+ shipmentHeader.postingDate,+ INVENTORY_VOID_BEFORE_CUTOVER_ERROR+ );+ switch (shipmentHeader.sourceDocument) {+ case "Sales Order": {+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [salesOrder, salesOrderLines, originalJournalLines] =+ await inOrder([+ () =>+ single(db, "salesOrder", {+ id: shipmentHeader.sourceDocumentId+ }),+ () =>+ many(db, "salesOrderLine", {+ salesOrderId: shipmentHeader.sourceDocumentId+ }),+ () =>+ documentJournalLines(db, companyId, {+ documentId: shipmentId,+ documentType: "Sales Shipment"+ })+ ]);+ if (salesOrder.error)+ throw new Error("Failed to fetch sales order");+ if (salesOrderLines.error)+ throw new Error("Failed to fetch sales order lines");++ // Every void posts its reversal: Provisional before the+ // company's accounting cutover, Posted after it. Read here to+ // decide whether to resolve a period, and again inside the+ // transaction.+ const postingStatus = await journalPostingStatus(db, companyId);++ const reversingJournalLines: Omit<+ Database["public"]["Tables"]["journalLine"]["Insert"],+ "journalId"+ >[] = originalJournalLines.map((entry) => ({+ accountId: entry.accountId,+ accrual: entry.accrual,+ description: `VOID: ${entry.description}`,+ // A reversal is a sign flip of an already-posted value, which+ // is exact — no rounding to do.+ amount: -entry.amount,+ quantity: -entry.quantity,+ documentType: entry.documentType,+ documentId: entry.documentId,+ externalDocumentId: entry.externalDocumentId,+ documentLineReference: entry.documentLineReference,+ journalLineReference: entry.journalLineReference,+ companyId+ }));++ const customer = await single(db, "customer", {+ id: salesOrder.data.customerId,+ companyId+ });+ if (customer.error) throw new Error("Failed to fetch customer");++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ const jobUpdates: Record<+ string,+ Database["public"]["Tables"]["job"]["Update"]+ > = {};++ // Put each serial or batch back in the bin its posting took it+ // from, which is not always the line's bin.+ const postedTrackedRows = await db+ .selectFrom("itemLedger")+ .where("documentId", "=", shipmentHeader.id)+ .where("documentType", "=", "Sales Shipment")+ .where("companyId", "=", companyId)+ .where("trackedEntityId", "is not", null)+ .where("quantity", "<", 0)+ .select(["trackedEntityId", "storageUnitId"])+ .execute();+ const postedTrackedBins = new Map<string, string | null>(+ postedTrackedRows.map((row) => [+ row.trackedEntityId as string,+ row.storageUnitId ?? null+ ])+ );+ const restoreBin = (+ trackedEntityId: string | undefined,+ lineStorageUnitId: string | null+ ) =>+ trackedEntityId && postedTrackedBins.has(trackedEntityId)+ ? (postedTrackedBins.get(trackedEntityId) ?? null)+ : lineStorageUnitId;++ const locationId = shipmentHeader.locationId;+ for await (const shipmentLine of shipmentLines.data) {+ if (+ shipmentLine.fulfillment?.type === "Job" &&+ shipmentLine.fulfillment?.jobId+ ) {+ // Reverse job quantities for void shipment+ const jobId = shipmentLine.fulfillment.jobId;+ const currentJob = jobs.data.find((j) => j.id === jobId);++ logger.info("Processing job void:", {+ jobId,+ currentJob: currentJob+ ? {+ id: currentJob.id,+ quantity: currentJob.quantity,+ quantityShipped: currentJob.quantityShipped,+ quantityComplete: currentJob.quantityComplete,+ status: currentJob.status+ }+ : null,+ shipmentLine: {+ id: shipmentLine.id,+ shippedQuantity: shipmentLine.shippedQuantity,+ shippedQuantityType: typeof shipmentLine.shippedQuantity+ }+ });++ const currentQuantityShipped = currentJob?.quantityShipped ?? 0;++ // Ensure shippedQuantity is a valid number+ const shippedQuantity =+ typeof shipmentLine.shippedQuantity === "number" &&+ !isNaN(shipmentLine.shippedQuantity)+ ? shipmentLine.shippedQuantity+ : 0;++ logger.info("Calculated values for void:", {+ currentQuantityShipped,+ shippedQuantity,+ newTotal: currentQuantityShipped - shippedQuantity,+ jobQuantity: currentJob?.quantity+ });++ // Reduce shipped quantity (reverse of posting)+ const newQuantityShipped = Math.max(+ 0,+ currentQuantityShipped - shippedQuantity+ );+ const newQuantityComplete = Math.max(+ currentJob?.quantityComplete ?? 0,+ shippedQuantity+ );++ // Update status based on new quantities+ let newStatus = currentJob?.status;+ if (+ currentJob?.status === "Completed" &&+ newQuantityShipped < (currentJob?.quantity ?? 0)+ ) {+ newStatus = "In Progress";+ }++ jobUpdates[jobId] = {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped+ };+ }++ const itemTrackingType =+ items.data.find((item) => item.id === shipmentLine.itemId)+ ?.itemTrackingType ?? "Inventory";++ // Default shippedQuantity to 0 if not defined or NaN+ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ if (itemTrackingType === "Inventory") {+ // Create positive adjustment to restore inventory+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(shippedQuantity), // Positive to restore inventory+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipmentHeader.id ?? undefined,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });+ }++ if (shipmentLine.requiresBatchTracking) {+ const batchId = shipmentLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ )?.id;+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(shippedQuantity), // Positive to restore inventory+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: restoreBin(+ batchId,+ shipmentLine.storageUnitId+ ),+ entryType: "Positive Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipmentHeader.id ?? undefined,+ trackedEntityId: batchId,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });+ }++ if (shipmentLine.requiresSerialTracking) {+ const lineTracking = shipmentLineTracking.data?.filter(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ );++ lineTracking?.forEach((tracking) => {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: 1, // Positive to restore inventory+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: restoreBin(+ tracking.id,+ shipmentLine.storageUnitId+ ),+ entryType: "Positive Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipmentHeader.id ?? undefined,+ trackedEntityId: tracking.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });+ });+ }+ }++ const shipmentLinesBySalesOrderLineId = shipmentLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["shipmentLine"]["Row"][]+ >+ >((acc, shipmentLine) => {+ if (shipmentLine.lineId) {+ acc[shipmentLine.lineId] = [+ ...(acc[shipmentLine.lineId] ?? []),+ shipmentLine+ ];+ }+ return acc;+ }, {});++ // Reverse sales order line updates+ const salesOrderLineUpdates = salesOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ >+ >((acc, salesOrderLine) => {+ const shipmentLines =+ shipmentLinesBySalesOrderLineId[salesOrderLine.id];+ if (+ shipmentLines &&+ shipmentLines.length > 0 &&+ salesOrderLine.saleQuantity &&+ salesOrderLine.saleQuantity > 0+ ) {+ const shippedQuantity = shipmentLines.reduce(+ (acc, shipmentLine) => {+ const safeShippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ return acc + safeShippedQuantity;+ },+ 0+ );++ // Reduce shipped quantity (reverse of posting)+ const newQuantitySent = Math.max(+ 0,+ (salesOrderLine.quantitySent ?? 0) - shippedQuantity+ );++ const sentComplete =+ newQuantitySent >= salesOrderLine.saleQuantity;++ const updates: Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ > = {+ ...acc,+ [salesOrderLine.id]: {+ quantitySent: newQuantitySent,+ sentComplete+ }+ };++ // Clear sent date if no longer complete+ if (!sentComplete && salesOrderLine.sentDate) {+ updates[salesOrderLine.id]!.sentDate = null;+ }++ return updates;+ }++ return acc;+ }, {});++ // Reverse FA SO line disposals on void+ const faSoLinesForVoid = salesOrderLines.data.filter(+ (sol) =>+ sol.salesOrderLineType === "Fixed Asset" &&+ sol.assetId &&+ sol.sentComplete+ );++ for (const faSoLine of faSoLinesForVoid) {+ const hasShipmentEntries = originalJournalLines.some(+ (jl) =>+ jl.documentLineReference ===+ journalReference.to.shipment(faSoLine.id)+ );++ if (hasShipmentEntries) {+ salesOrderLineUpdates[faSoLine.id] = {+ quantitySent: 0,+ sentComplete: false,+ sentDate: null+ };++ fixedAssetWrites.patch(faSoLine.assetId!, {+ status: "Active",+ disposalDate: null,+ disposalMethod: null,+ updatedBy: userId+ });++ const assetId = faSoLine.assetId!;+ fixedAssetWrites.defer((trx) =>+ deleteRows(trx, "fixedAssetDisposal", {+ fixedAssetId: assetId,+ companyId+ })+ );+ }+ }++ // Restore tracked entities to available status+ const trackedEntityUpdates =+ shipmentLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ // Restore original quantity and set to available+ acc[trackedEntity.id] = {+ status: "Available",+ quantity: trackedEntity.quantity // Restore original quantity+ };++ return acc;+ }, {}) ?? {};++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted" && reversingJournalLines.length > 0+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ await fixedAssetWrites.apply(trx, companyId);+ // Update sales order lines to reverse shipped quantities+ for await (const [salesOrderLineId, update] of Object.entries(+ salesOrderLineUpdates+ )) {+ await trx+ .updateTable("salesOrderLine")+ .set(update)+ .where("id", "=", salesOrderLineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ const salesOrderLines = await trx+ .selectFrom("salesOrderLine")+ .select([+ "id",+ "salesOrderLineType",+ "invoicedComplete",+ "sentComplete"+ ])+ .where("salesOrderId", "=", salesOrder.data.id)+ .execute();++ const areAllLinesInvoiced = salesOrderLines.every(+ (line) =>+ line.salesOrderLineType === "Comment" || line.invoicedComplete+ );++ const areAllLinesShipped = salesOrderLines.every(+ (line) =>+ line.salesOrderLineType === "Comment" ||+ line.salesOrderLineType === "Service" ||+ line.sentComplete+ );++ let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =+ "To Ship and Invoice";+ if (areAllLinesInvoiced && areAllLinesShipped) {+ status = "Completed";+ } else if (areAllLinesShipped) {+ status = "To Invoice";+ } else if (areAllLinesInvoiced) {+ status = "To Ship";+ }++ await trx+ .updateTable("salesOrder")+ .set({+ status+ })+ .where("id", "=", salesOrder.data.id)+ .where("companyId", "=", companyId)+ .execute();++ // Update shipment status to Voided+ await trx+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();++ // Restore tracked entities to available status+ if (Object.keys(trackedEntityUpdates).length > 0) {+ const voidActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Void Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ attributes: {+ Shipment: shipmentId,+ "Sales Order": salesOrder.data.id+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();++ const voidActivityId = voidActivity[0]!.id;++ // Restore tracked entities+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ if (voidActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: voidActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }++ // Create reversing item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update jobs to reverse shipped quantities+ if (Object.keys(jobUpdates).length > 0) {+ logger.info(+ "Final job void updates to be applied:",+ jobUpdates+ );+ for await (const [jobId, update] of Object.entries(+ jobUpdates+ )) {+ logger.info(`Voiding job ${jobId} with:`, update);+ await trx+ .updateTable("job")+ .set(update)+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Create reversing journal entries+ if (reversingJournalLines.length > 0) {+ const voidJournalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const voidJournalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId: voidJournalEntryId,+ accountingPeriodId,+ description: `VOID: Sales Shipment ${shipmentHeader.shipmentId}`,+ postingDate: today,+ companyId,+ sourceType: "Sales Shipment",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ await trx+ .insertInto("journalLine")+ .values(+ reversingJournalLines.map((line) => ({+ ...line,+ journalId: voidJournalResult.id+ }))+ )+ .execute();+ }+ });+ break;+ }+ case "Purchase Order": {+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [purchaseOrder, purchaseOrderLines] = await inOrder([+ () =>+ single(db, "purchaseOrder", {+ id: shipmentHeader.sourceDocumentId+ }),+ () =>+ many(db, "purchaseOrderLine", {+ purchaseOrderId: shipmentHeader.sourceDocumentId+ })+ ]);+ if (purchaseOrder.error)+ throw new Error("Failed to fetch purchase order");+ if (purchaseOrderLines.error)+ throw new Error("Failed to fetch purchase order lines");++ const supplier = await single(db, "supplier", {+ id: purchaseOrder.data.supplierId,+ companyId+ });+ if (supplier.error) throw new Error("Failed to fetch supplier");++ const jobOperationsUpdates: Record<+ string,+ Database["public"]["Tables"]["jobOperation"]["Update"]+ > = {};++ for await (const shipmentLine of shipmentLines.data) {+ const purchaseOrderLine = purchaseOrderLines.data.find(+ (pol) => pol.id === shipmentLine.lineId+ );++ if (+ purchaseOrderLine?.jobId &&+ purchaseOrderLine.jobOperationId+ ) {+ // Reset job operation status when voiding+ const jobOperationId = purchaseOrderLine.jobOperationId;++ jobOperationsUpdates[jobOperationId] = {+ status: "Ready"+ };+ continue;+ }+ }++ const shipmentLinesByPurchaseOrderLineId =+ shipmentLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["shipmentLine"]["Row"][]+ >+ >((acc, shipmentLine) => {+ if (shipmentLine.lineId) {+ acc[shipmentLine.lineId] = [+ ...(acc[shipmentLine.lineId] ?? []),+ shipmentLine+ ];+ }+ return acc;+ }, {});++ // Reverse purchase order line updates+ const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ >+ >((acc, purchaseOrderLine) => {+ const shipmentLines =+ shipmentLinesByPurchaseOrderLineId[purchaseOrderLine.id];+ if (+ shipmentLines &&+ shipmentLines.length > 0 &&+ purchaseOrderLine.purchaseQuantity &&+ purchaseOrderLine.purchaseQuantity > 0+ ) {+ const shippedQuantity = shipmentLines.reduce(+ (acc, shipmentLine) => {+ const safeShippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ return acc + safeShippedQuantity;+ },+ 0+ );++ // Reduce shipped quantity (reverse of posting)+ const newQuantityShipped = Math.max(+ 0,+ (purchaseOrderLine.quantityShipped ?? 0) - shippedQuantity+ );++ const updates: Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ > = {+ ...acc,+ [purchaseOrderLine.id]: {+ quantityShipped: newQuantityShipped+ }+ };++ return updates;+ }++ return acc;+ }, {});++ // Restore tracked entities to available status+ const trackedEntityUpdates =+ shipmentLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ // Restore original quantity and set to available+ acc[trackedEntity.id] = {+ status: "Available",+ quantity: trackedEntity.quantity+ };++ return acc;+ }, {}) ?? {};++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const locationId = shipmentHeader.locationId;++ // Create reversing item ledger entries for purchase order void+ for await (const shipmentLine of shipmentLines.data) {+ const itemTrackingType =+ items.data.find((item) => item.id === shipmentLine.itemId)+ ?.itemTrackingType ?? "Inventory";++ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ if (itemTrackingType === "Inventory" && shippedQuantity !== 0) {+ // Create negative adjustment to remove inventory that was added during posting+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-shippedQuantity), // Negative to remove inventory+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Purchase Receipt",+ documentId: shipmentHeader.id ?? undefined,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });+ }++ if (shipmentLine.requiresBatchTracking) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(-shippedQuantity), // Negative to remove inventory+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Purchase Receipt",+ documentId: shipmentHeader.id ?? undefined,+ trackedEntityId: shipmentLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as+ | TrackedEntityAttributes+ | undefined+ )?.["Shipment Line"] === shipmentLine.id+ )?.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });+ }++ if (shipmentLine.requiresSerialTracking) {+ const lineTracking = shipmentLineTracking.data?.filter(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ );++ lineTracking?.forEach((tracking) => {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -1, // Negative to remove inventory+ locationId: shipmentLine.locationId ?? locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Purchase Receipt",+ documentId: shipmentHeader.id ?? undefined,+ trackedEntityId: tracking.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId+ });+ });+ }+ }++ await db.transaction().execute(async (trx) => {+ // Update purchase order lines to reverse shipped quantities+ for await (const [purchaseOrderLineId, update] of Object.entries(+ purchaseOrderLineUpdates+ )) {+ await trx+ .updateTable("purchaseOrderLine")+ .set(update)+ .where("id", "=", purchaseOrderLineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Create reversing item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update shipment status to Voided+ await trx+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();++ // Restore tracked entities+ if (Object.keys(trackedEntityUpdates).length > 0) {+ const voidActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Void Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ attributes: {+ Shipment: shipmentId,+ "Purchase Order": purchaseOrder.data.id+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();++ const voidActivityId = voidActivity[0]!.id;++ // Restore tracked entities+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ if (voidActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: voidActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }+ }++ // Update job operations to reset status+ if (Object.keys(jobOperationsUpdates).length > 0) {+ logger.info(+ "Final job operation void updates to be applied:",+ jobOperationsUpdates+ );+ for await (const [jobOperationId, update] of Object.entries(+ jobOperationsUpdates+ )) {+ logger.info(+ `Voiding job operation ${jobOperationId} with:`,+ update+ );+ await trx+ .updateTable("jobOperation")+ .set(update)+ .where("id", "=", jobOperationId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ });+ break;+ }+ case "Outbound Transfer": {+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [warehouseTransfer, warehouseTransferLines] = await inOrder([+ () =>+ single(db, "warehouseTransfer", {+ id: shipmentHeader.sourceDocumentId+ }),+ () =>+ many(db, "warehouseTransferLine", {+ transferId: shipmentHeader.sourceDocumentId+ })+ ]);++ if (warehouseTransfer.error)+ throw new Error("Failed to fetch warehouse transfer");+ if (warehouseTransferLines.error)+ throw new Error("Failed to fetch warehouse transfer lines");++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const warehouseTransferLineUpdates: Record<+ string,+ Database["public"]["Tables"]["warehouseTransferLine"]["Update"]+ > = {};++ // Process each shipment line+ for await (const shipmentLine of shipmentLines.data) {+ const warehouseTransferLine = warehouseTransferLines.data.find(+ (line) => line.id === shipmentLine.lineId+ );++ if (!warehouseTransferLine) continue;++ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ // Reverse warehouse transfer line shipped quantity+ const newShippedQuantity = Math.max(+ 0,+ (warehouseTransferLine.shippedQuantity ?? 0) - shippedQuantity+ );++ warehouseTransferLineUpdates[warehouseTransferLine.id] = {+ shippedQuantity: newShippedQuantity+ };++ // Create item ledger entry to restore inventory at source+ if (shippedQuantity !== 0) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: round(shippedQuantity), // Positive to restore inventory+ locationId: shipmentLine.locationId,+ storageUnitId: shipmentLine.storageUnitId,+ entryType: "Transfer",+ documentType: "Transfer Shipment",+ documentId: warehouseTransfer.data?.transferId,+ externalDocumentId:+ shipmentHeader.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId+ });+ }+ }++ // Check if all lines are fully shipped after void+ const allLinesFullyShipped = warehouseTransferLines.data.every(+ (line) => {+ const updates = warehouseTransferLineUpdates[line.id];+ const shippedQty =+ updates?.shippedQuantity ?? line.shippedQuantity ?? 0;+ return shippedQty >= (line.quantity ?? 0);+ }+ );++ // Check if all lines are fully received+ const allLinesFullyReceived = warehouseTransferLines.data.every(+ (line) => {+ const receivedQty = line.receivedQuantity ?? 0;+ return receivedQty >= (line.quantity ?? 0);+ }+ );++ // Determine new warehouse transfer status+ let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =+ warehouseTransfer.data.status;++ if (allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "Completed";+ } else if (allLinesFullyShipped && !allLinesFullyReceived) {+ newStatus = "To Receive";+ } else if (!allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "To Ship";+ } else {+ newStatus = "Draft";+ }++ await db.transaction().execute(async (trx) => {+ // Update warehouse transfer lines+ for await (const [lineId, update] of Object.entries(+ warehouseTransferLineUpdates+ )) {+ await trx+ .updateTable("warehouseTransferLine")+ .set(update)+ .where("id", "=", lineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Update warehouse transfer status+ await trx+ .updateTable("warehouseTransfer")+ .set({+ status: newStatus,+ updatedBy: userId+ })+ .where("id", "=", warehouseTransfer.data.id)+ .where("companyId", "=", companyId)+ .execute();++ // Create reversing item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update shipment status to Voided+ await trx+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "Sales Return Order": {+ // Void a return-to-customer shipment: rebuild positive ledger,+ // sign-flip journal, entities back On Hold (their RMA state).+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ // Every void posts its reversal: Provisional before the+ // company's accounting cutover, Posted after it. Read here to+ // decide whether to resolve a period, and again inside the+ // transaction.+ const postingStatus = await journalPostingStatus(db, companyId);++ const [originalJournalLines, originalItemLedger, originalCostRows] =+ await inOrder([+ () =>+ documentJournalLines(db, companyId, {+ documentId: shipmentId,+ documentType: "Return Order"+ }),+ () =>+ many(db, "itemLedger", {+ documentId: shipmentId,+ documentType: "Sales Return Shipment",+ companyId+ }),+ () =>+ many(db, "costLedger", {+ documentId: shipmentId,+ documentType: "Sales Return Shipment",+ companyId+ })+ ]);+ // A failed read here must abort: treating data:null as "nothing+ // to reverse" would mark the shipment Voided while its journal+ // and ledger rows stand.+ if (originalItemLedger.error)+ throw new Error("Failed to fetch item ledger rows to reverse");+ if (originalCostRows.error)+ throw new Error("Failed to fetch cost ledger rows to reverse");++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted" && originalJournalLines.length > 0+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ const reversingItemLedger = (originalItemLedger.data ?? []).map(+ (entry) => ({+ postingDate: today,+ itemId: entry.itemId,+ quantity: -entry.quantity,+ locationId: entry.locationId,+ storageUnitId: entry.storageUnitId,+ entryType: "Positive Adjmt." as const,+ documentType: "Sales Return Shipment" as const,+ documentId: entry.documentId,+ externalDocumentId: entry.externalDocumentId,+ trackedEntityId: entry.trackedEntityId,+ createdBy: userId,+ companyId+ })+ );+ if (reversingItemLedger.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(reversingItemLedger)+ .execute();+ }++ // Restore inventory VALUE, not just quantity: posting consumed+ // FIFO layers via calculateCOGS; without an offsetting layer+ // the voided stock re-enters at zero value and inventory is+ // permanently understated.+ for (const row of (originalCostRows.data ?? []).filter(+ (r) => Number(r.quantity) < 0+ )) {+ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: row.itemLedgerType,+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Sales Return Shipment",+ documentId: row.documentId,+ externalDocumentId: row.externalDocumentId ?? undefined,+ itemId: row.itemId,+ quantity: round(-Number(row.quantity)),+ cost: round(-Number(row.cost)),+ nominalCost: round(-Number(row.nominalCost)),+ remainingQuantity: round(-Number(row.quantity)),+ companyId,+ postingDate: today+ })+ .execute();+ }++ if (originalJournalLines.length > 0) {+ const originalLines = originalJournalLines;+ // Carry the original lines' GL dimensions onto the reversing+ // lines so the void mirrors the posting.+ const originalDimensions = await many(+ trx,+ "journalLineDimension",+ {+ journalLineId: originalLines.map((l) => l.id),+ companyId+ },+ { columns: ["journalLineId", "dimensionId", "valueId"] }+ );+ const dimensionsByLine = new Map<+ string,+ { dimensionId: string; valueId: string }[]+ >();+ for (const dim of originalDimensions.data ?? []) {+ const list = dimensionsByLine.get(dim.journalLineId) ?? [];+ list.push({+ dimensionId: dim.dimensionId,+ valueId: dim.valueId+ });+ dimensionsByLine.set(dim.journalLineId, list);+ }++ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );+ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `VOID Return Shipment ${shipmentHeader.shipmentId}`,+ postingDate: today,+ companyId,+ sourceType: "Sales Return Shipment",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ originalLines.map((line) => ({+ accountId: line.accountId,+ description: `VOID: ${line.description ?? ""}`,+ amount: -line.amount,+ quantity:+ line.quantity == null ? undefined : -line.quantity,+ documentType: line.documentType,+ documentId: line.documentId,+ externalDocumentId: line.externalDocumentId ?? undefined,+ documentLineReference:+ line.documentLineReference ?? undefined,+ journalLineReference: line.journalLineReference,+ journalId: journalResult.id,+ companyId+ }))+ )+ .returning(["id"])+ .execute();++ const voidDimensionInserts: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];+ journalLineResults.forEach((jl, index) => {+ const originalId = originalLines[index]?.id;+ if (!originalId) return;+ for (const dim of dimensionsByLine.get(originalId) ?? []) {+ voidDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dim.dimensionId,+ valueId: dim.valueId,+ companyId+ });+ }+ });+ if (voidDimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(voidDimensionInserts)+ .execute();+ }+ }++ const voidActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Void Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ attributes: {+ "Sales Return Order": shipmentHeader.sourceDocumentId,+ Shipment: shipmentId,+ Employee: userId+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();+ const voidActivityId = voidActivity[0]?.id;++ for await (const entity of shipmentLineTracking.data ?? []) {+ await trx+ .updateTable("trackedEntity")+ .set({ status: "On Hold" })+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();+ if (voidActivityId) {+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: voidActivityId,+ trackedEntityId: entity.id,+ quantity: entity.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }++ await trx+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "Purchase Return Order": {+ // Void a supplier-return shipment: rebuild positive ledger,+ // sign-flip journal, roll back quantityShipped + ladder,+ // entities back to Available (their pre-shipment state).+ if (!shipmentHeader.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");+ const purchaseReturnOrderId = shipmentHeader.sourceDocumentId;++ // Mirror of the sales-side guard in post-receipt: voiding after a+ // debit memo exists would leave quantityCredited > quantityShipped+ // with no path to reconcile. Worse here than on the sales side —+ // post-memo recovers the GRNI clearing amount from THIS shipment's+ // costLedger rows, so a void afterwards strands that clearing and+ // leaves GRNI permanently out by the carried cost.+ const debitMemos = await many(+ db,+ "memo",+ { purchaseReturnOrderId, companyId, status: neq("Voided") },+ { columns: ["id", "status"] }+ );+ if (debitMemos.error)+ throw new Error("Failed to check for debit memos");+ if ((debitMemos.data ?? []).length > 0) {+ throw new Error(+ "Cannot void: a debit memo exists for this return order. Void it first."+ );+ }++ // Every void posts its reversal: Provisional before the+ // company's accounting cutover, Posted after it. Read here to+ // decide whether to resolve a period, and again inside the+ // transaction.+ const postingStatus = await journalPostingStatus(db, companyId);++ const [+ originalJournalLines,+ originalItemLedger,+ returnLinesVoid,+ originalCostRows+ ] = await inOrder([+ () =>+ documentJournalLines(db, companyId, {+ documentId: shipmentId,+ documentType: "Return Order"+ }),+ () =>+ many(db, "itemLedger", {+ documentId: shipmentId,+ documentType: "Purchase Return Shipment",+ companyId+ }),+ () =>+ many(db, "purchaseReturnOrderLine", {+ purchaseReturnOrderId,+ companyId+ }),+ () =>+ many(db, "costLedger", {+ documentId: shipmentId,+ documentType: "Purchase Return Shipment",+ companyId+ })+ ]);+ // A failed read here must abort: treating data:null as "nothing+ // to reverse" would mark the shipment Voided while its journal+ // and ledger rows stand.+ if (originalItemLedger.error)+ throw new Error("Failed to fetch item ledger rows to reverse");+ if (returnLinesVoid.error)+ throw new Error("Failed to fetch return order lines");+ if (originalCostRows.error)+ throw new Error("Failed to fetch cost ledger rows to reverse");++ const shippedByLine = new Map<string, number>();+ for (const shipmentLine of shipmentLines.data ?? []) {+ if (!shipmentLine.lineId) continue;+ const qty = Number(shipmentLine.shippedQuantity ?? 0);+ shippedByLine.set(+ shipmentLine.lineId,+ (shippedByLine.get(shipmentLine.lineId) ?? 0) + qty+ );+ }++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted" && originalJournalLines.length > 0+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ const reversingItemLedger = (originalItemLedger.data ?? []).map(+ (entry) => ({+ postingDate: today,+ itemId: entry.itemId,+ quantity: -entry.quantity,+ locationId: entry.locationId,+ storageUnitId: entry.storageUnitId,+ entryType: "Positive Adjmt." as const,+ documentType: "Purchase Return Shipment" as const,+ documentId: entry.documentId,+ externalDocumentId: entry.externalDocumentId,+ trackedEntityId: entry.trackedEntityId,+ createdBy: userId,+ companyId+ })+ );+ if (reversingItemLedger.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(reversingItemLedger)+ .execute();+ }++ // Restore inventory VALUE, not just quantity: posting consumed+ // FIFO layers via calculateCOGS; without an offsetting layer+ // the voided stock re-enters at zero value and inventory is+ // permanently understated.+ for (const row of (originalCostRows.data ?? []).filter(+ (r) => Number(r.quantity) < 0+ )) {+ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: row.itemLedgerType,+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Return Shipment",+ documentId: row.documentId,+ externalDocumentId: row.externalDocumentId ?? undefined,+ itemId: row.itemId,+ quantity: round(-Number(row.quantity)),+ cost: round(-Number(row.cost)),+ nominalCost: round(-Number(row.nominalCost)),+ remainingQuantity: round(-Number(row.quantity)),+ companyId,+ postingDate: today+ })+ .execute();+ }++ if (originalJournalLines.length > 0) {+ const originalLines = originalJournalLines;+ // Carry the original lines' GL dimensions onto the reversing+ // lines so the void mirrors the posting.+ const originalDimensions = await many(+ trx,+ "journalLineDimension",+ {+ journalLineId: originalLines.map((l) => l.id),+ companyId+ },+ { columns: ["journalLineId", "dimensionId", "valueId"] }+ );+ const dimensionsByLine = new Map<+ string,+ { dimensionId: string; valueId: string }[]+ >();+ for (const dim of originalDimensions.data ?? []) {+ const list = dimensionsByLine.get(dim.journalLineId) ?? [];+ list.push({+ dimensionId: dim.dimensionId,+ valueId: dim.valueId+ });+ dimensionsByLine.set(dim.journalLineId, list);+ }++ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );+ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `VOID Purchase Return Shipment ${shipmentHeader.shipmentId}`,+ postingDate: today,+ companyId,+ sourceType: "Purchase Return Shipment",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ originalLines.map((line) => ({+ accountId: line.accountId,+ description: `VOID: ${line.description ?? ""}`,+ amount: -line.amount,+ quantity:+ line.quantity == null ? undefined : -line.quantity,+ documentType: line.documentType,+ documentId: line.documentId,+ externalDocumentId: line.externalDocumentId ?? undefined,+ documentLineReference:+ line.documentLineReference ?? undefined,+ journalLineReference: line.journalLineReference,+ journalId: journalResult.id,+ companyId+ }))+ )+ .returning(["id"])+ .execute();++ const voidDimensionInserts: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];+ journalLineResults.forEach((jl, index) => {+ const originalId = originalLines[index]?.id;+ if (!originalId) return;+ for (const dim of dimensionsByLine.get(originalId) ?? []) {+ voidDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dim.dimensionId,+ valueId: dim.valueId,+ companyId+ });+ }+ });+ if (voidDimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(voidDimensionInserts)+ .execute();+ }+ }++ for await (const [lineId, shipped] of shippedByLine) {+ const line = (returnLinesVoid.data ?? []).find(+ (l) => l.id === lineId+ );+ if (!line) continue;+ await trx+ .updateTable("purchaseReturnOrderLine")+ .set({+ quantityShipped: Math.max(+ 0,+ Number(line.quantityShipped ?? 0) - shipped+ ),+ updatedBy: userId+ })+ .where("id", "=", lineId)+ .where("companyId", "=", companyId)+ .execute();+ }++ const remainingLines = await trx+ .selectFrom("purchaseReturnOrderLine")+ .select(["quantity", "quantityShipped", "closedComplete"])+ .where("purchaseReturnOrderId", "=", purchaseReturnOrderId)+ .execute();+ // Derived status (mirrors getPurchaseReturnOrderStatus): a void+ // that drops shipped quantity below the authorized total returns+ // the order to To Ship; otherwise it stays Completed.+ const allShipped =+ remainingLines.length > 0 &&+ remainingLines.every(+ (l) =>+ l.closedComplete ||+ Number(l.quantityShipped) >= Number(l.quantity)+ );+ const returnStatus = allShipped+ ? ("Completed" as const)+ : ("To Ship" as const);+ await trx+ .updateTable("purchaseReturnOrder")+ .set({ status: returnStatus, updatedBy: userId })+ .where("id", "=", purchaseReturnOrderId)+ .where("companyId", "=", companyId)+ .execute();++ const voidActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Void Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipmentHeader.shipmentId,+ attributes: {+ "Purchase Return Order": purchaseReturnOrderId,+ Shipment: shipmentId,+ Employee: userId+ },+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .returning(["id"])+ .execute();+ const voidActivityId = voidActivity[0]?.id;++ for await (const entity of shipmentLineTracking.data ?? []) {+ await trx+ .updateTable("trackedEntity")+ .set({ status: "Available" })+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();+ if (voidActivityId) {+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: voidActivityId,+ trackedEntityId: entity.id,+ quantity: entity.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today+ })+ .execute();+ }+ }++ await trx+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId+ })+ .where("id", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "Rental Agreement": {+ await voidRentalShipment(db, { shipmentId, companyId, userId });+ break;+ }++ default: {+ throw new Error(+ `Invalid source document type: ${shipmentHeader.sourceDocument}`+ );+ }+ }+ break;+ }+ }++ return {+ success: true,+ splitEntityIds+ };+ } catch (err) {+ // A failed VOID must not touch status: the shipment is still Posted and+ // its ledger/journal rows still stand, so forcing it to Draft would+ // contradict the books and let it be edited and posted a second time.+ if (type !== "void") {+ await updateRows(+ db,+ "shipment",+ { status: "Draft" },+ { id: shipmentId, companyId }+ );+ }+ throw err;+ }+ }++ /** Writes a shipment's journal, its lines and the lines' dimensions. */+ async function insertShipmentJournal(+ trx: KyselyTx,+ {+ journal,+ accountingPeriodId,+ postingDate,+ postingStatus,+ dimensionIdByEntity,+ companyId,+ userId+ }: {+ journal: ShipmentJournal;+ accountingPeriodId: string | null;+ postingDate: string;+ postingStatus: AutomaticJournalStatus;+ dimensionIdByEntity: ReadonlyMap<string, string>;+ companyId: string;+ userId: string;+ }+ ) {+ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );+ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: journal.description,+ postingDate,+ companyId,+ sourceType: journal.sourceType,+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journal.lines.map(({ dimensions: _, ...line }) => ({+ ...line,+ journalId: journalResult.id,+ companyId+ }))+ )+ .returning(["id"])+ .execute();++ const dimensionRows = journalLineDimensionRows({+ journalLineIds: journalLineResults.map((line) => line.id),+ lines: journal.lines,+ dimensionIdByEntity,+ companyId+ });+ if (dimensionRows.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionRows)+ .execute();+ }+ }++ // Pure cost resolver for Unscrap: given the ORIGINAL scrap movement's+ // costLedger rows (linked via costLedger.documentId = the scrap itemLedger id),+ // return the unit cost the restored layer must book at so a scrap→unscrap+ // round trip nets zero P&L (Oracle Return-from-Scrap precedent). Returns null+ // when the rows can't yield a cost — the caller then falls back to current+ // cost.++ export function resolveUnscrapUnitCost(+ rows: Array<{ quantity: number; cost: number }>+ ): number | null {+ if (rows.length === 0) return null;+ let totalQuantity = 0;+ let totalCost = 0;+ for (const row of rows) {+ totalQuantity += Math.abs(Number(row.quantity) || 0);+ totalCost += Math.abs(Number(row.cost) || 0);+ }+ if (totalQuantity === 0) return null;+ return totalCost / totalQuantity;+ }+ // settleQuantity needs the lot's CURRENT status to know whether to preserve it+ // (a Scrapped lot stays Scrapped at zero). get_item_quantities_by_tracking_id+ // doesn't carry status, so read it off the row — one PK lookup inside the open+ // transaction, next to the write it informs.+ //+ // LOCKED: the caller feeds this status straight back through settleQuantity, so+ // an unlocked read is a read-modify-write on `status`. Without the lock a+ // concurrent transaction that Scraps the lot between our read and our update is+ // silently overwritten with the stale `Available` we read.+ async function currentEntityStatus(+ trx: Transaction<KyselyDatabase>,+ trackedEntityId: string,+ companyId: string+ ): Promise<Database["public"]["Enums"]["trackedEntityStatus"]> {+ const row = await trx+ .selectFrom("trackedEntity")+ .select("status")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirstOrThrow();+ return row.status;+ }++ // The single write path for manual inventory adjustments (ERP quantities page,+ // MES shop floor). Ports the former app-side insertManualInventoryAdjustment+ // semantics — Set Quantity resolution, storage-unit transfers, serial/batch+ // stock-target resolution, tracked-entity creation/updates — and books every+ // movement through the shared posting core in ONE transaction: item ledger ++ // cost layers + a balanced journal (Provisional before the accounting+ // cutover, Posted after it) against the inventory adjustment variance account. Storage-unit transfers+ // move value-neutral stock and never post to the GL.+ // Business-validation failures are 400s (InvalidInputError) with the exact+ // message the app routes string-match on; everything else is a 500 so real+ // outages surface in monitoring.++ export const postInventoryAdjustmentPermission = {+ update: "inventory"+ } satisfies PermissionRule<z.output<typeof postInventoryAdjustmentInput>>;++ /** The single write path for manual inventory adjustments; see the note above. */+ export async function postInventoryAdjustment(+ ctx: ServiceContext,+ raw: z.input<typeof postInventoryAdjustmentInput>+ ) {+ const {+ adjustmentType,+ itemId,+ locationId: payloadLocationId,+ storageUnitId,+ trackedEntityId,+ quantity,+ readableId,+ originalStorageUnitId,+ expirationDate: providedExpirationDate,+ comment,+ scrapReasonId,+ unscrapOfItemLedgerId+ } = postInventoryAdjustmentInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ // Unscrap sends no location (resolved from the scrap movement); every+ // other type carries one (app-layer validator enforces it).+ const locationId: string | null = payloadLocationId ?? null;+ // The service-role client proves the caller may act in companyId, not that+ // the ids below belong to it — each lands on this company's ledger rows or+ // journal dimensions, and their single-column FKs accept any company's row.+ await assertCompanyRecords(+ db,+ "location",+ [locationId],+ companyId,+ "Location"+ );+ await assertCompanyRecords(+ db,+ "storageUnit",+ [storageUnitId, originalStorageUnitId],+ companyId,+ "Storage unit"+ );+ await assertCompanyRecords(+ db,+ "scrapReason",+ [scrapReasonId],+ companyId,+ "Scrap reason"+ );+ // A trackedEntityId that exists nowhere is legitimate: the app mints the id+ // (nanoid) for a NEW serial/batch and this function inserts it. One that+ // belongs to another company is not — the paths below would write ledger+ // rows pointing at it (the insert only fails by accident of the id-only PK).+ if (trackedEntityId) {+ const existing = await db+ .selectFrom("trackedEntity")+ .select("companyId")+ .where("id", "=", trackedEntityId)+ .executeTakeFirst();+ if (existing && existing.companyId !== companyId) {+ throw new NotFoundError("Tracked entity not found");+ }+ }++ const today = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();+ const nowIso = datetime.timestamp();++ const [storageUnitQuantities, itemResult, itemCostResult, shelfLife] =+ await inOrder([+ () =>+ rpcRows(db, "get_item_quantities_by_tracking_id", {+ item_id: itemId,+ company_id: companyId,+ location_id: locationId ?? ""+ }),+ () =>+ single(+ db,+ "item",+ { id: itemId, companyId },+ {+ columns: [+ "id",+ "itemTrackingType",+ "replenishmentSystem",+ "readableIdWithRevision"+ ]+ }+ ),+ () =>+ single(+ db,+ "itemCost",+ { itemId, companyId },+ {+ columns: [+ "costingMethod",+ "unitCost",+ "standardCost",+ "itemPostingGroupId"+ ]+ }+ ),+ () =>+ maybeSingle(+ db,+ "itemShelfLife",+ { itemId, companyId },+ { columns: ["mode", "days"] }+ )+ ]);++ if (itemResult.error) throw new Error("Failed to fetch item");+ if (itemCostResult.error) throw new Error("Failed to fetch item cost");+ // Fail closed: a failed quantity read must abort, not read as "no stock" —+ // a Set Quantity against an empty snapshot would post the full target as+ // new stock on top of whatever actually exists.+ if (storageUnitQuantities.error) {+ throw new Error("Failed to fetch current quantities");+ }+ if (shelfLife.error) throw new Error("Failed to fetch item shelf life");+ const item = {+ itemTrackingType: itemResult.data.itemTrackingType,+ replenishmentSystem: itemResult.data.replenishmentSystem,+ itemPostingGroupId: itemCostResult.data.itemPostingGroupId+ };+ const itemCost = itemCostResult.data;++ // Every adjustment that carries value posts a journal: Provisional before+ // the company's accounting cutover, Posted after it. Read here to decide+ // whether to resolve a period, and again inside the transaction.+ const postingStatus = await journalPostingStatus(db, companyId);+ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ // Active dimensions for the company group (post-shipment precedent) —+ // journal lines get Item / ItemPostingGroup / Location tags.+ const dimensionMap: Record<string, string> = {};+ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );+ if (companyRecord.error) throw new Error("Failed to fetch company");+ const dimensions = await many(+ db,+ "dimension",+ {+ companyGroupId: companyRecord.data.companyGroupId!,+ active: true,+ entityType: [+ "Item",+ "ItemPostingGroup",+ "Location",+ "ScrapReason",+ "WorkCenter",+ "Employee"+ ]+ },+ { columns: ["id", "entityType"] }+ );+ // Fail closed: journal lines must not silently lose dimension tags.+ if (dimensions.error) throw new Error("Failed to fetch dimensions");+ for (const dim of dimensions.data ?? []) {+ if (dim.entityType) dimensionMap[dim.entityType] = dim.id;+ }+ // Resolved before the posting transaction opens: given `db`, it runs and+ // commits its own short transaction. A Provisional journal has no period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;+ const accounting = {+ postingStatus,+ accountingPeriodId,+ accountDefaults: {+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,+ inventoryAdjustmentVarianceAccount:+ accountDefaults.data.inventoryAdjustmentVarianceAccount+ },+ description: comment?.trim()+ ? `Inventory Adjustment — ${comment.trim()}`+ : "Inventory Adjustment",+ userId,+ dimensions: dimensionMap+ };++ // get_item_quantities_by_tracking_id rows (scoped to item + location);+ // only the fields this function reads.+ type TrackingQuantityRow = {+ trackedEntityId: string | null;+ storageUnitId: string | null;+ quantity: number | null;+ readableId: string | null;+ };+ const trackingRows = (storageUnitQuantities.data ??+ []) as TrackingQuantityRow[];++ const ledgerBase = {+ postingDate: today,+ itemId,+ locationId,+ storageUnitId: storageUnitId ?? null,+ trackedEntityId: trackedEntityId ?? null,+ documentType: null,+ documentId: null,+ comment: comment || null,+ companyId,+ createdBy: userId+ };++ // null == undefined — loose equality is deliberate (ported behavior).+ const currentQuantity = trackedEntityId+ ? trackingRows.find((q) => q.trackedEntityId == trackedEntityId)+ : trackingRows.find((q) => q.storageUnitId == storageUnitId);+ const currentQuantityOnHand = currentQuantity?.quantity ?? 0;++ // Fixed Duration shelf-life fallback for NEW tracked entities when the+ // user did not type an expiry. Other modes stay NULL (resolved at+ // production/receipt time, not on a manual adjustment).+ const resolveExpirationForNewEntity = (): string | null => {+ if (providedExpirationDate) return providedExpirationDate;+ if (+ !shelfLife.error &&+ shelfLife.data?.mode === "Fixed Duration" &&+ shelfLife.data.days+ ) {+ return parseDate(today)+ .add({ days: Number(shelfLife.data.days) })+ .toString();+ }+ return null;+ };++ // Existing-entity expiry override: only when the user supplied a value+ // that differs from the current one. Ports updateTrackedEntityExpiry —+ // appends to attributes.expiryOverrides so the override is traceable.+ const applyExpirationOverride = async (+ trx: Transaction<KyselyDatabase>,+ targetEntityId: string+ ) => {+ if (!providedExpirationDate) return;+ const existing = await trx+ .selectFrom("trackedEntity")+ .select(["expirationDate", "attributes", "status"])+ .where("id", "=", targetEntityId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!existing || existing.expirationDate === providedExpirationDate) return;+ if (existing.status === "Consumed") {+ throw new InvalidInputError(+ "Cannot edit expiry of a consumed tracked entity"+ );+ }+ const prevAttrs =+ (existing.attributes as Record<string, unknown> | null) ?? {};+ const prevHistory = Array.isArray(prevAttrs.expiryOverrides)+ ? (prevAttrs.expiryOverrides as Record<string, unknown>[])+ : [];+ const nextAttrs = {+ ...prevAttrs,+ expiryOverrides: [+ ...prevHistory,+ {+ previous: existing.expirationDate ?? null,+ next: providedExpirationDate,+ reason: comment?.trim() || "Updated via inventory adjustment",+ source: "Inventory Adjustment",+ userId,+ at: nowIso+ }+ ]+ };+ await trx+ .updateTable("trackedEntity")+ .set({+ expirationDate: providedExpirationDate,+ attributes: nextAttrs as unknown as Json+ })+ .where("id", "=", targetEntityId)+ .where("companyId", "=", companyId)+ .execute();+ };++ let resultLedgerId: string | null = null;++ // Storage-unit transfer for a tracked entity: negative at the original+ // unit, positive at the new one. Value does not move — no GL, no layers.+ const isStorageUnitTransfer =+ trackedEntityId &&+ originalStorageUnitId &&+ originalStorageUnitId !== storageUnitId;++ // Scrap/Unscrap offset to the company's scrapAccount so cost of quality is+ // separable on the P&L; analysis slices by dimension (ScrapReason /+ // Employee + the standard trio) instead of by account. Resolved only for a+ // Scrap or Unscrap. An empty scrapAccount falls back to the variance+ // account.+ const scrapAccountingFor = (description: string) => {+ const scrapAccountId = resolveDefaultAccount(+ accountDefaults.data,+ "scrapAccount",+ postingStatus+ ).accountId;+ return {+ ...accounting,+ offsetAccount: scrapAccountId,+ offsetDescription: "Scrap Account",+ description,+ extraDimensions: [+ ...(scrapReasonId+ ? [{ entityType: "ScrapReason", valueId: scrapReasonId }]+ : []),+ { entityType: "Employee", valueId: userId }+ ]+ };+ };++ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);++ if (adjustmentType === "Scrap") {+ const scrapLedgerBase = {+ ...ledgerBase,+ documentType: "Scrap" as const,+ scrapReasonId,+ entryType: "Negative Adjmt." as const+ };+ const accountingForScrap = scrapAccountingFor(+ comment?.trim() ? `Scrap — ${comment.trim()}` : "Scrap"+ );++ if (trackedEntityId) {+ const entity = await trx+ .selectFrom("trackedEntity")+ .select([+ "id",+ "quantity",+ "status",+ "readableId",+ "sourceDocument",+ "sourceDocumentId",+ "sourceDocumentReadableId",+ "itemId",+ "expirationDate",+ "attributes"+ ])+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!entity) throw new InvalidInputError("Tracked entity not found");+ if (entity.status !== "Available") {+ throw new InvalidInputError(+ "Only available tracked entities can be scrapped"+ );+ }+ const entityQuantity = round(Number(entity.quantity) || 0);+ // quantity 0 ⇒ scrap the whole entity (serial UIs don't send a qty)+ const scrapQuantity = quantity > 0 ? round(quantity) : entityQuantity;+ if (scrapQuantity > entityQuantity) {+ throw new InvalidInputError("Insufficient quantity for scrap");+ }+ const bin = currentQuantity?.storageUnitId ?? storageUnitId ?? null;++ let scrappedEntityId = trackedEntityId;+ if (!isFullDraw(entityQuantity, scrapQuantity)) {+ // Partial batch scrap: identity-flip split — the parent keeps its+ // id and is decremented; the departing child is the Scrapped+ // record of what left.+ const split = buildBatchSplitRecords({+ parent: {+ id: entity.id,+ readableId: entity.readableId,+ quantity: entityQuantity,+ sourceDocument: entity.sourceDocument,+ sourceDocumentId: entity.sourceDocumentId,+ sourceDocumentReadableId: entity.sourceDocumentReadableId,+ itemId: entity.itemId,+ expirationDate: entity.expirationDate+ ? String(entity.expirationDate)+ : null,+ attributes:+ (entity.attributes as Record<string, unknown> | null) ?? null+ },+ drawQuantity: scrapQuantity,+ childId: nanoid(),+ splitActivityId: nanoid(),+ activitySourceDocument: "Item",+ activitySourceDocumentId: itemId,+ bin: { storageUnitId: bin, locationId },+ itemLedgerItemId: itemId,+ companyId,+ userId,+ postingDate: today,+ childStatus: "Scrapped"+ });+ await trx+ .insertInto("trackedEntity")+ .values({+ ...split.childEntityInsert,+ sourceDocument: split.childEntityInsert.sourceDocument ?? "Item",+ sourceDocumentId:+ split.childEntityInsert.sourceDocumentId ?? itemId,+ attributes: split.childEntityInsert.attributes as unknown as Json+ })+ .execute();+ await trx+ .updateTable("trackedEntity")+ .set(split.parentUpdate)+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .insertInto("trackedActivity")+ .values({+ ...split.activityInsert,+ attributes: split.activityInsert.attributes as unknown as Json+ })+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert)+ .execute();+ await trx+ .insertInto("trackedActivityOutput")+ .values(split.activityOutputInsert)+ .execute();+ await trx+ .insertInto("itemLedger")+ .values(+ split.ledgerInserts.map((ledgerRow) => ({+ ...ledgerRow,+ itemId: ledgerRow.itemId ?? itemId,+ quantity: round(ledgerRow.quantity)+ }))+ )+ .execute();+ scrappedEntityId = split.childEntityInsert.id;+ } else {+ // Full-entity scrap: terminal status flip; the entity KEEPS its+ // quantity as the record of what was scrapped (the negative+ // ledger row below carries the stock decrement).+ await trx+ .updateTable("trackedEntity")+ .set({ status: "Scrapped" })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }++ const scrapActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: scrapActivityId,+ type: "Scrap",+ sourceDocument: "Item",+ sourceDocumentId: itemId,+ attributes: {+ "Scrap Reason": scrapReasonId,+ Employee: userId,+ ...(comment?.trim() ? { Notes: comment.trim() } : {})+ },+ companyId,+ createdBy: userId+ })+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: scrapActivityId,+ trackedEntityId: scrappedEntityId,+ quantity: scrapQuantity,+ companyId,+ createdBy: userId+ })+ .execute();++ const booked = await bookAdjustment(trx, {+ ledger: {+ ...scrapLedgerBase,+ trackedEntityId: scrappedEntityId,+ storageUnitId: bin,+ quantity: -Math.abs(scrapQuantity)+ },+ item,+ itemCost,+ accounting: accountingForScrap+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ // Untracked scrap: negative movement from the bin's untracked stock.+ if (quantity <= 0) {+ throw new InvalidInputError("Scrap quantity must be greater than zero");+ }+ const untrackedRow = trackingRows.find(+ (q) => q.trackedEntityId == null && q.storageUnitId == storageUnitId+ );+ if ((untrackedRow?.quantity ?? 0) < quantity) {+ throw new InvalidInputError("Insufficient quantity for scrap");+ }+ const booked = await bookAdjustment(trx, {+ ledger: {+ ...scrapLedgerBase,+ trackedEntityId: null,+ quantity: -Math.abs(quantity)+ },+ item,+ itemCost,+ accounting: accountingForScrap+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ if (adjustmentType === "Unscrap") {+ const unscrapLedgerBase = {+ ...ledgerBase,+ documentType: "Scrap" as const,+ scrapReasonId,+ entryType: "Positive Adjmt." as const+ };+ const accountingForUnscrap = scrapAccountingFor(+ comment?.trim() ? `Unscrap — ${comment.trim()}` : "Unscrap"+ );++ if (trackedEntityId) {+ const entity = await trx+ .selectFrom("trackedEntity")+ .select(["id", "quantity", "status"])+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!entity) throw new InvalidInputError("Tracked entity not found");+ if (entity.status !== "Scrapped") {+ throw new InvalidInputError(+ "Only scrapped tracked entities can be unscrapped"+ );+ }+ const entityQuantity = Number(entity.quantity) || 0;+ if (entityQuantity <= 0) {+ throw new InvalidInputError(+ "Tracked entity has no quantity to restore"+ );+ }++ // The original scrap movement: explicit id from the payload, else+ // the entity's newest negative Scrap row.+ let scrapMovement = unscrapOfItemLedgerId+ ? await trx+ .selectFrom("itemLedger")+ .select(["id", "storageUnitId", "locationId", "scrapReasonId"])+ .where("id", "=", unscrapOfItemLedgerId)+ .where("companyId", "=", companyId)+ // Constrain a caller-supplied id to THIS entity's own negative+ // Scrap movements (same filters as the fallback below) — an+ // unrelated ledger id must not drive the restored bin/cost.+ .where("trackedEntityId", "=", trackedEntityId)+ .where("documentType", "=", "Scrap")+ .where("quantity", "<", 0)+ .executeTakeFirst()+ : undefined;+ if (!scrapMovement) {+ scrapMovement = await trx+ .selectFrom("itemLedger")+ .select(["id", "storageUnitId", "locationId", "scrapReasonId"])+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .where("documentType", "=", "Scrap")+ .where("quantity", "<", 0)+ .orderBy("createdAt", "desc")+ .executeTakeFirst();+ }++ // Inherit the reason from the original scrap movement so an unscrap+ // is never mis-classified — the operator no longer re-enters it. Fall+ // back to any payload reason, then null (untracked/legacy rows).+ const resolvedScrapReasonId =+ scrapMovement?.scrapReasonId ?? scrapReasonId ?? null;+ const accountingForTrackedUnscrap = {+ ...accountingForUnscrap,+ extraDimensions: [+ ...(resolvedScrapReasonId+ ? [+ {+ entityType: "ScrapReason",+ valueId: resolvedScrapReasonId+ }+ ]+ : []),+ { entityType: "Employee", valueId: userId }+ ]+ };++ // Reverse at the ORIGINAL scrapped cost when the scrap movement's+ // cost rows are resolvable (costLedger.documentId = the scrap+ // itemLedger id — bookAdjustment's linkage); else current cost.+ let fixedUnitCost: number | undefined;+ if (scrapMovement) {+ const costRows = await trx+ .selectFrom("costLedger")+ .select(["quantity", "cost"])+ .where("documentId", "=", scrapMovement.id)+ .where("companyId", "=", companyId)+ .execute();+ const resolved = resolveUnscrapUnitCost(+ costRows.map((r) => ({+ quantity: Number(r.quantity),+ cost: Number(r.cost)+ }))+ );+ if (resolved != null) fixedUnitCost = resolved;+ }++ await trx+ .updateTable("trackedEntity")+ .set({ status: "Available" })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ const unscrapActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: unscrapActivityId,+ type: "Unscrap",+ sourceDocument: "Item",+ sourceDocumentId: itemId,+ attributes: {+ "Scrap Reason": resolvedScrapReasonId,+ Employee: userId,+ ...(comment?.trim() ? { Notes: comment.trim() } : {})+ },+ companyId,+ createdBy: userId+ })+ .execute();+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: unscrapActivityId,+ trackedEntityId,+ quantity: entityQuantity,+ companyId,+ createdBy: userId+ })+ .execute();++ const booked = await bookAdjustment(trx, {+ ledger: {+ ...unscrapLedgerBase,+ scrapReasonId: resolvedScrapReasonId,+ // A Scrapped tracked-entity row carries no location — restore to+ // the bin/location the scrap movement removed it from.+ locationId:+ scrapMovement?.locationId ?? unscrapLedgerBase.locationId,+ storageUnitId:+ scrapMovement?.storageUnitId ?? storageUnitId ?? null,+ correctionOfItemLedgerId: scrapMovement?.id ?? null,+ quantity: entityQuantity+ },+ item,+ itemCost,+ accounting: accountingForTrackedUnscrap,+ fixedUnitCost+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ // Untracked unscrap: positive movement at current cost (no original+ // movement linkage to reverse against — v1).+ if (quantity <= 0) {+ throw new InvalidInputError(+ "Unscrap quantity must be greater than zero"+ );+ }+ // Unscrap makes locationId optional in the validator (the tracked path+ // recovers it from the scrap movement). The untracked path has no such+ // recovery, so require it — a null-location ledger row is invisible to+ // location-scoped inventory queries.+ if (!locationId) {+ throw new InvalidInputError(+ "Location is required to unscrap untracked stock"+ );+ }+ const booked = await bookAdjustment(trx, {+ ledger: {+ ...unscrapLedgerBase,+ trackedEntityId: null,+ quantity+ },+ item,+ itemCost,+ accounting: accountingForUnscrap+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ if (isStorageUnitTransfer) {+ if (readableId !== undefined && readableId !== null) {+ await trx+ .updateTable("trackedEntity")+ .set({ readableId })+ .where("id", "=", trackedEntityId!)+ .where("companyId", "=", companyId)+ .execute();+ }+ await applyExpirationOverride(trx, trackedEntityId!);++ await bookAdjustment(trx, {+ ledger: {+ ...ledgerBase,+ storageUnitId: originalStorageUnitId!,+ entryType: "Negative Adjmt.",+ quantity: -currentQuantityOnHand+ },+ item,+ itemCost,+ accounting,+ skipValuation: true+ });+ const positive = await bookAdjustment(trx, {+ ledger: {+ ...ledgerBase,+ entryType: "Positive Adjmt.",+ quantity: currentQuantityOnHand+ },+ item,+ itemCost,+ accounting,+ skipValuation: true+ });+ resultLedgerId = positive.itemLedgerId;+ return;+ }++ let entryType: "Positive Adjmt." | "Negative Adjmt." =+ adjustmentType === "Set Quantity" ? "Positive Adjmt." : adjustmentType;+ let adjustmentQuantity = quantity;++ if (adjustmentType === "Set Quantity" && currentQuantity) {+ const quantityDifference = quantity - currentQuantityOnHand;+ if (quantityDifference > 0) {+ entryType = "Positive Adjmt.";+ adjustmentQuantity = quantityDifference;+ } else if (quantityDifference < 0) {+ entryType = "Negative Adjmt.";+ adjustmentQuantity = Math.abs(quantityDifference);+ } else {+ // No quantity change — readableId / expirationDate may still change.+ if (+ trackedEntityId &&+ readableId !== undefined &&+ readableId !== null+ ) {+ await trx+ .updateTable("trackedEntity")+ .set({ readableId })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }+ if (trackedEntityId) {+ await applyExpirationOverride(trx, trackedEntityId);+ }+ resultLedgerId = null;+ return;+ }+ }++ // Resolve the stock target for a negative adjustment when a serial+ // number is provided or nothing matched the loose lookup.+ if (entryType === "Negative Adjmt." && (readableId || !currentQuantity)) {+ if (readableId) {+ const resolvedQtyRow = trackingRows.find(+ (q) =>+ q.readableId === readableId &&+ q.trackedEntityId != null &&+ (q.quantity ?? 0) > 0+ );+ if (!resolvedQtyRow) {+ throw new InvalidInputError("Serial number not found");+ }+ const resolvedId = resolvedQtyRow.trackedEntityId as string;+ const resolvedQty = round(resolvedQtyRow.quantity ?? 0);+ if (round(adjustmentQuantity) > resolvedQty) {+ throw new InvalidInputError(+ "Insufficient quantity for negative adjustment"+ );+ }+ // A negative adjustment draws down Available stock; when it lands+ // on zero the lot is Consumed, not a zero-quantity Available husk.+ // settleQuantity is the shared rule, so this path also preserves a+ // Scrapped lot — which the inline flip it replaces did not.+ await trx+ .updateTable("trackedEntity")+ .set({+ ...settleQuantity({+ quantity: resolvedQty - adjustmentQuantity,+ status: await currentEntityStatus(trx, resolvedId, companyId)+ }),+ readableId+ })+ .where("id", "=", resolvedId)+ .where("companyId", "=", companyId)+ .execute();+ const booked = await bookAdjustment(trx, {+ ledger: {+ ...ledgerBase,+ trackedEntityId: resolvedId,+ entryType,+ quantity: -Math.abs(adjustmentQuantity)+ },+ item,+ itemCost,+ accounting+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ // No serial number provided. Prefer untracked (legacy) stock in this bin.+ const legacyRow = trackingRows.find(+ (q) => q.trackedEntityId == null && q.storageUnitId == storageUnitId+ );+ if (legacyRow) {+ const legacyQty = legacyRow.quantity ?? 0;+ if (adjustmentQuantity > legacyQty) {+ throw new InvalidInputError(+ "Insufficient quantity for negative adjustment"+ );+ }+ const booked = await bookAdjustment(trx, {+ ledger: {+ ...ledgerBase,+ trackedEntityId: null,+ entryType,+ quantity: -Math.abs(adjustmentQuantity)+ },+ item,+ itemCost,+ accounting+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ // No untracked stock in the bin — resolve a tracked entity sitting in+ // the same storage unit. Ambiguous when more than one holds stock.+ const trackedRowsInUnit = trackingRows.filter(+ (q) =>+ q.trackedEntityId != null &&+ q.storageUnitId == storageUnitId &&+ (q.quantity ?? 0) > 0+ );+ if (trackedRowsInUnit.length === 0) {+ throw new InvalidInputError(+ "Insufficient quantity for negative adjustment"+ );+ }+ if (trackedRowsInUnit.length > 1) {+ throw new InvalidInputError(+ "Multiple tracked entities in this storage unit — select a specific row to adjust"+ );+ }+ const targetRow = trackedRowsInUnit[0]!;+ const targetQty = round(targetRow.quantity ?? 0);+ if (round(adjustmentQuantity) > targetQty) {+ throw new InvalidInputError(+ "Insufficient quantity for negative adjustment"+ );+ }+ const targetId = targetRow.trackedEntityId as string;+ await trx+ .updateTable("trackedEntity")+ .set(+ settleQuantity({+ quantity: targetQty - adjustmentQuantity,+ status: await currentEntityStatus(trx, targetId, companyId)+ })+ )+ .where("id", "=", targetId)+ .where("companyId", "=", companyId)+ .execute();+ const booked = await bookAdjustment(trx, {+ ledger: {+ ...ledgerBase,+ trackedEntityId: targetId,+ entryType,+ quantity: -Math.abs(adjustmentQuantity)+ },+ item,+ itemCost,+ accounting+ });+ resultLedgerId = booked.itemLedgerId;+ return;+ }++ let signedQuantity = adjustmentQuantity;+ if (entryType === "Negative Adjmt.") {+ if (adjustmentQuantity > currentQuantityOnHand) {+ throw new InvalidInputError(+ "Insufficient quantity for negative adjustment"+ );+ }+ signedQuantity = -Math.abs(adjustmentQuantity);+ }++ if (trackedEntityId) {+ if (currentQuantity) {+ // Draining a lot to zero Consumes it (a Set Quantity to 0 or a full+ // negative adjustment); above zero its status is untouched. This path+ // takes an arbitrary trackedEntityId from the payload, so it is the+ // one that can land on a Scrapped lot — settleQuantity preserves it.+ const entityUpdate: Record<string, unknown> = settleQuantity({+ quantity: signedQuantity + currentQuantityOnHand,+ status: await currentEntityStatus(trx, trackedEntityId, companyId)+ });+ if (readableId !== undefined && readableId !== null) {+ entityUpdate.readableId = readableId;+ }+ await trx+ .updateTable("trackedEntity")+ .set(entityUpdate)+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ await applyExpirationOverride(trx, trackedEntityId);+ } else {+ // Nothing to create for a zero-quantity new entity: the physical+ // state is already zero, so skip the insert AND the ledger row and+ // return a success no-op (keeps repeated scanners idempotent).+ if (round(signedQuantity) === 0) {+ return;+ }+ const expirationDate = resolveExpirationForNewEntity();+ // Stamp the trace blob so the popover Source / Override steps can+ // show the entity originated from a manual inventory adjustment.+ const adjustmentStamp = {+ userId,+ at: nowIso,+ reason: comment?.trim() || "Created via inventory adjustment"+ };+ const attributes: Record<string, unknown> = {+ "Inventory Adjustment": adjustmentStamp,+ ...(expirationDate+ ? {+ expiryOverrides: [+ {+ previous: null,+ next: expirationDate,+ reason: adjustmentStamp.reason,+ source: "Inventory Adjustment",+ userId: adjustmentStamp.userId,+ at: adjustmentStamp.at+ }+ ]+ }+ : {})+ };+ await trx+ .insertInto("trackedEntity")+ .values({+ id: trackedEntityId,+ sourceDocument: "Item",+ sourceDocumentId: itemId,+ sourceDocumentReadableId:+ itemResult.data.readableIdWithRevision ?? undefined,+ // Every by-item consumer filters on this column (notably the+ // sales-return picker); omitting it made this stock unreturnable.+ itemId,+ readableId: readableId ?? null,+ quantity: round(signedQuantity),+ status: "Available",+ expirationDate,+ attributes: attributes as unknown as Json,+ companyId,+ createdBy: userId+ })+ .execute();+ }+ }++ const booked = await bookAdjustment(trx, {+ ledger: {+ ...ledgerBase,+ entryType,+ quantity: signedQuantity+ },+ item,+ itemCost,+ accounting+ });+ resultLedgerId = booked.itemLedgerId;+ });++ // Set inside the transaction callback, which narrowing does not follow.+ const ledgerId = resultLedgerId as string | null;+ return {+ success: true,+ itemLedger: ledgerId ? { id: ledgerId } : null+ };+ }+ type ItemLedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];++ export const postPickingPermission = {} satisfies PermissionRule<+ z.output<typeof postPickingInput>+ >;++ /**+ * Picks, un-picks and returns picking-list material, per `type`.+ *+ * A pick is a TRANSFER of material from the warehouse source shelf+ * (pickingListLine.storageUnitId) to the work center's lineside shelf+ * (pickingListLine.toStorageUnitId). Consumption happens later at production,+ * which is why we also point jobMaterial.storageUnitId at the lineside shelf.+ */+ export async function postPicking(+ ctx: ServiceContext,+ raw: z.input<typeof postPickingInput>+ ) {+ const input = postPickingInput.parse(raw);++ const db = ctx.asSystem.pg;+ const validatedPayload = {+ ...input,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ };++ // The permission check proves the caller may act in companyId, not that the+ // body's ids belong to it. Every line-scoped case writes pickingListId as the+ // ledger/activity documentId and locationId / fromStorageUnitId /+ // trackedEntityId onto this company's ledger rows, so all of them are+ // re-read under companyId — and the line must be on the list the body names.+ if ("pickingListLineId" in validatedPayload) {+ const { companyId, pickingListId, pickingListLineId, locationId } =+ validatedPayload;+ const line = await db+ .selectFrom("pickingListLine")+ .select("id")+ .where("id", "=", pickingListLineId)+ .where("pickingListId", "=", pickingListId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!line) throw new NotFoundError("Picking list line not found");+ await assertCompanyRecords(+ db,+ "location",+ [locationId],+ companyId,+ "Location"+ );+ await assertCompanyRecords(+ db,+ "storageUnit",+ [+ "fromStorageUnitId" in validatedPayload+ ? validatedPayload.fromStorageUnitId+ : null+ ],+ companyId,+ "Storage unit"+ );+ await assertCompanyRecords(+ db,+ "trackedEntity",+ [+ "trackedEntityId" in validatedPayload+ ? validatedPayload.trackedEntityId+ : null+ ],+ companyId,+ "Tracked entity"+ );+ }++ const today = datetime+ .today(await getCompanyTimeZone(db, validatedPayload.companyId))+ .toString();+ let splitEntityId: string | undefined;++ switch (validatedPayload.type) {+ case "inventory": {+ const {+ pickingListId,+ pickingListLineId,+ quantity,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line: every case here read-modify-writes its picked or+ // returned counter, so two concurrent scans of the same line would+ // both add to the same stale total and the ledger would double. Same+ // lock post-stock-transfer takes.+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ const inserts: ItemLedgerInsert[] = [+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(-quantity),+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(quantity),+ locationId,+ storageUnitId: line.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ createdBy: userId,+ companyId+ }+ ];++ await trx.insertInto("itemLedger").values(inserts).execute();++ await trx+ .updateTable("pickingListLine")+ .set({+ quantityPicked: resolvePick({+ lineQuantity: Number(line.quantityToPick ?? 0),+ pickedQuantity: Number(line.quantityPicked ?? 0),+ transferQuantity: quantity+ }),+ status: "Picked",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .execute();++ // Production consumes from where the material now physically sits.+ await pointJobMaterialAtLineside(trx, line, userId, companyId);+ });+ break;+ }++ case "unpickInventory": {+ const {+ pickingListId,+ pickingListLineId,+ quantity,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line: every case here read-modify-writes its picked or+ // returned counter, so two concurrent scans of the same line would+ // both add to the same stale total and the ledger would double. Same+ // lock post-stock-transfer takes.+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ const inserts: ItemLedgerInsert[] = [+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(-quantity),+ locationId,+ storageUnitId: line.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(quantity),+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ createdBy: userId,+ companyId+ }+ ];++ await trx.insertInto("itemLedger").values(inserts).execute();++ await trx+ .updateTable("pickingListLine")+ .set({+ quantityPicked: Math.max(+ 0,+ round(round(Number(line.quantityPicked ?? 0)) - round(quantity))+ ),+ status: "Pending",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .execute();++ // Restore the warehouse source as the consumption point.+ await restoreJobMaterialSource(trx, line, userId, companyId);+ });+ break;+ }++ case "serial": {+ const {+ pickingListId,+ pickingListLineId,+ trackedEntityId,+ fromStorageUnitId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line: every case here read-modify-writes its picked or+ // returned counter, so two concurrent scans of the same line would+ // both add to the same stale total and the ledger would double. Same+ // lock post-stock-transfer takes.+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Pick",+ sourceDocument: "Picking List",+ sourceDocumentId: pickingListId,+ attributes: {+ "Picking List": pickingListId,+ "Picking List Line": pickingListLineId,+ "From Shelf": fromStorageUnitId,+ "To Shelf": line.toStorageUnitId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId,+ quantity: 1,+ companyId,+ createdBy: userId+ })+ .execute();++ const inserts: ItemLedgerInsert[] = [+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: -1,+ locationId,+ storageUnitId: fromStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: 1,+ locationId,+ storageUnitId: line.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ }+ ];+ await trx.insertInto("itemLedger").values(inserts).execute();++ await trx+ .updateTable("pickingListLine")+ .set({+ quantityPicked: resolvePick({+ lineQuantity: Number(line.quantityToPick ?? 0),+ pickedQuantity: Number(line.quantityPicked ?? 0),+ transferQuantity: 1+ }),+ status: "Picked",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .execute();++ // Record which lot this line picked (drives the line's picked-lot+ // display, unpick, and the allocation-dedup in the picker).+ await trx+ .insertInto("pickingListLineTrackedEntity")+ .values({+ pickingListLineId,+ trackedEntityId,+ companyId,+ quantity: 1,+ quantityPicked: 1+ })+ .onConflict((oc) =>+ oc.columns(["pickingListLineId", "trackedEntityId"]).doUpdateSet({+ quantity: (eb) =>+ eb("pickingListLineTrackedEntity.quantity", "+", 1),+ quantityPicked: (eb) =>+ eb("pickingListLineTrackedEntity.quantityPicked", "+", 1)+ })+ )+ .execute();++ await pointJobMaterialAtLineside(trx, line, userId, companyId);+ });+ break;+ }++ case "batch": {+ const {+ pickingListId,+ pickingListLineId,+ trackedEntityId,+ fromStorageUnitId,+ quantity,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line: every case here read-modify-writes its picked or+ // returned counter, so two concurrent scans of the same line would+ // both add to the same stale total and the ledger would double. Same+ // lock post-stock-transfer takes.+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ // Lock the source lot too: the split below draws against this+ // on-hand, and a concurrent pick of the same lot must not spend it.+ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ // Refuse an over-pick before any record is written; resolvePick+ // returns the new running total (the UI caps the picker at the same+ // outstanding figure, so this only fires on a stale page or a+ // double submit — which is exactly when it matters).+ const newQuantityPicked = resolvePick({+ lineQuantity: Number(line.quantityToPick ?? 0),+ pickedQuantity: Number(line.quantityPicked ?? 0),+ transferQuantity: quantity+ });++ // Round BOTH operands once: the split gate, the split records, the+ // Pick activity input, the allocation row and the two ledger rows+ // all derive from these.+ const entityQuantity = round(Number(trackedEntity.quantity));+ const transferQuantity = round(quantity);++ // resolvePick bounds the pick by the LINE's outstanding quantity, not+ // by what this lot holds. A line outstanding larger than the lot would+ // fall through isFullDraw into buildBatchSplitRecords, which throws a+ // plain Error on `draw >= parentQty` — surfaced as a 500. This is the+ // same guard post-stock-transfer's batch case takes, and it makes the+ // refusal a 400 the scan UI can show.+ assertEntityCoversPick({ entityQuantity, transferQuantity });++ const inserts: ItemLedgerInsert[] = [];++ // Split the batch when picking less than the whole entity: the shelf+ // entity keeps its id and is decremented; a NEW child entity departs+ // to the lineside bin carrying the drawn quantity.+ let pickedEntityId = trackedEntityId;+ if (!isFullDraw(entityQuantity, transferQuantity)) {+ const childId = nanoid();+ splitEntityId = childId;+ pickedEntityId = childId;++ const split = buildBatchSplitRecords({+ parent: {+ id: trackedEntity.id,+ readableId: trackedEntity.readableId,+ quantity: entityQuantity,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId: trackedEntity.sourceDocumentReadableId,+ itemId: trackedEntity.itemId ?? null,+ expirationDate: trackedEntity.expirationDate ?? null,+ attributes: trackedEntity.attributes as Record<+ string,+ unknown+ > | null+ },+ drawQuantity: transferQuantity,+ childId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Picking List",+ activitySourceDocumentId: pickingListId,+ bin: { storageUnitId: fromStorageUnitId, locationId },+ itemLedgerItemId: line.itemId,+ companyId,+ userId,+ postingDate: today,+ childStatus: "Available"+ });++ await trx+ .insertInto("trackedActivity")+ .values(+ split.activityInsert as Insertable<+ KyselyDatabase["trackedActivity"]+ >+ )+ .execute();++ await trx+ .insertInto("trackedEntity")+ .values(+ split.childEntityInsert as Insertable<+ KyselyDatabase["trackedEntity"]+ >+ )+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert)+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values(split.activityOutputInsert)+ .execute();++ await trx+ .updateTable("trackedEntity")+ .set(split.parentUpdate)+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ inserts.push(+ ...(split.ledgerInserts.map((ledgerRow) => ({+ ...ledgerRow,+ quantity: round(ledgerRow.quantity)+ })) as typeof inserts)+ );+ }++ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Pick",+ sourceDocument: "Picking List",+ sourceDocumentId: pickingListId,+ attributes: {+ "Picking List": pickingListId,+ "Picking List Line": pickingListLineId,+ "From Shelf": fromStorageUnitId,+ "To Shelf": line.toStorageUnitId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: pickedEntityId,+ quantity: transferQuantity,+ companyId,+ createdBy: userId+ })+ .execute();++ // A pick MOVES the batch — it stays Available (consumed at production).+ inserts.push(+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(-transferQuantity),+ locationId,+ storageUnitId: fromStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId: pickedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(transferQuantity),+ locationId,+ storageUnitId: line.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId: pickedEntityId,+ createdBy: userId,+ companyId+ }+ );++ await trx.insertInto("itemLedger").values(inserts).execute();++ await trx+ .updateTable("pickingListLine")+ .set({+ quantityPicked: newQuantityPicked,+ status: "Picked",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .execute();++ // Record which lot this line picked (drives picked-lot display,+ // unpick, and the picker's allocation-dedup). On a split the picked+ // lot is the departing CHILD — the lineside entity the operator+ // consumes — never the shelf survivor.+ await trx+ .insertInto("pickingListLineTrackedEntity")+ .values({+ pickingListLineId,+ trackedEntityId: pickedEntityId,+ companyId,+ quantity: transferQuantity,+ quantityPicked: transferQuantity+ })+ .onConflict((oc) =>+ oc.columns(["pickingListLineId", "trackedEntityId"]).doUpdateSet({+ quantity: (eb) =>+ eb(+ "pickingListLineTrackedEntity.quantity",+ "+",+ transferQuantity+ ),+ quantityPicked: (eb) =>+ eb(+ "pickingListLineTrackedEntity.quantityPicked",+ "+",+ transferQuantity+ )+ })+ )+ .execute();++ await pointJobMaterialAtLineside(trx, line, userId, companyId);+ });+ break;+ }++ case "unpickSerial": {+ const {+ pickingListId,+ pickingListLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line: every case here read-modify-writes its picked or+ // returned counter, so two concurrent scans of the same line would+ // both add to the same stale total and the ledger would double. Same+ // lock post-stock-transfer takes.+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const qty = Number(trackedEntity.quantity);++ const activity = await trx+ .selectFrom("trackedActivity")+ .innerJoin(+ "trackedActivityInput",+ "trackedActivity.id",+ "trackedActivityInput.trackedActivityId"+ )+ .where("trackedActivity.type", "=", "Pick")+ .where("trackedActivity.sourceDocument", "=", "Picking List")+ .where("trackedActivity.sourceDocumentId", "=", pickingListId)+ .where("trackedActivityInput.trackedEntityId", "=", trackedEntityId)+ .where("trackedActivity.companyId", "=", companyId)+ .selectAll("trackedActivity")+ .executeTakeFirstOrThrow();++ const inserts: ItemLedgerInsert[] = [+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(-qty),+ locationId,+ storageUnitId: line.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(qty),+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ }+ ];+ await trx.insertInto("itemLedger").values(inserts).execute();++ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", activity.id!)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", activity.id!)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .updateTable("pickingListLine")+ .set({+ quantityPicked: Math.max(+ 0,+ round(round(Number(line.quantityPicked ?? 0)) - round(qty))+ ),+ status: "Pending",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .execute();++ // Drop the recorded lot so it's pickable again + display clears.+ await trx+ .deleteFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", pickingListLineId)+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ await restoreJobMaterialSource(trx, line, userId, companyId);+ });+ break;+ }++ case "unpickBatch": {+ const {+ pickingListId,+ pickingListLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line: every case here read-modify-writes its picked or+ // returned counter, so two concurrent scans of the same line would+ // both add to the same stale total and the ledger would double. Same+ // lock post-stock-transfer takes.+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // The unpick quantity is what THIS line picked of the entity — from+ // the allocation row, never trackedEntity.quantity: post-flip the+ // allocated entity is the departing child, and once consumption+ // starts its current quantity no longer equals what was picked.+ const allocation = await trx+ .selectFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", pickingListLineId)+ .where("trackedEntityId", "=", trackedEntityId)+ .selectAll()+ .executeTakeFirst();++ if (!allocation) {+ throw new Error(+ `Cannot unpick batch: no allocation row for picking list line ${pickingListLineId} and tracked entity ${trackedEntityId}`+ );+ }++ const unpickQuantity = Number(allocation.quantityPicked);++ const activity = await trx+ .selectFrom("trackedActivity")+ .innerJoin(+ "trackedActivityInput",+ "trackedActivity.id",+ "trackedActivityInput.trackedActivityId"+ )+ .where("trackedActivity.type", "=", "Pick")+ .where("trackedActivity.sourceDocument", "=", "Picking List")+ .where("trackedActivity.sourceDocumentId", "=", pickingListId)+ .where("trackedActivityInput.trackedEntityId", "=", trackedEntityId)+ .where("trackedActivity.companyId", "=", companyId)+ .selectAll("trackedActivity")+ .executeTakeFirstOrThrow();++ // Reverse the Transfer pair at the picked magnitude.+ const inserts: ItemLedgerInsert[] = [+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(-unpickQuantity),+ locationId,+ storageUnitId: line.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(unpickQuantity),+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ }+ ];++ // Merge-back undo: post-flip the picked entity is a Split child+ // whose parent stayed on the shelf. Fold the quantity back into the+ // parent and delete the Split so genealogy reads as if the pick+ // never happened. Legacy allocations (no Split From pointer, or a+ // parent that no longer matches) skip this — the entity simply+ // returns to the source bin as its own lot, today's behavior.+ const attrs = (trackedEntity.attributes ?? {}) as Record<+ string,+ unknown+ >;+ const parentId = attrs["Split From Entity ID"];+ if (typeof parentId === "string" && parentId) {+ const parent = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", parentId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ if (parent && parent.readableId === trackedEntity.readableId) {+ // Round before comparing: a residue child (holding+ // 0.020000000000000018 after an earlier split) giving back its+ // 0.02 lands on −1.7e-17, and a raw `< 0` refuses a legitimate+ // full unpick. settleQuantity rounds, refuses a REAL negative,+ // and Consumes the emptied child in one decision.+ const childSettled = settleQuantity({+ quantity: Number(trackedEntity.quantity) - unpickQuantity,+ status: trackedEntity.status,+ refusal: `Cannot unpick batch: entity ${trackedEntityId} holds ${trackedEntity.quantity} but ${unpickQuantity} was picked — partial consumption must be unconsumed first`+ });++ const splitActivity = await trx+ .selectFrom("trackedActivity")+ .where("type", "=", "Split")+ .where(attributesContain({ "Split Entity ID": trackedEntityId }))+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: round(+ round(Number(parent.quantity)) + round(unpickQuantity)+ )+ })+ .where("id", "=", parent.id)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .updateTable("trackedEntity")+ .set(childSettled)+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ // Net out the original split pair at the source bin. Keep the+ // child's entity row — itemLedger.trackedEntityId history stays+ // intact (the FK is ON DELETE SET NULL; deleting would null it).+ inserts.push(+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(-unpickQuantity),+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivity?.id ?? pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(unpickQuantity),+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivity?.id ?? pickingListId,+ trackedEntityId: parent.id,+ createdBy: userId,+ companyId+ }+ );++ // Clean undo: the Split never happened.+ if (splitActivity) {+ await trx+ .deleteFrom("trackedActivityOutput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", splitActivity.id!)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ }++ await trx.insertInto("itemLedger").values(inserts).execute();++ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", activity.id!)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", activity.id!)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .updateTable("pickingListLine")+ .set({+ quantityPicked: Math.max(+ 0,+ round(+ round(Number(line.quantityPicked ?? 0)) - round(unpickQuantity)+ )+ ),+ status: "Pending",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .execute();++ // Drop the recorded lot so it's pickable again + display clears.+ await trx+ .deleteFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", pickingListLineId)+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ await restoreJobMaterialSource(trx, line, userId, companyId);+ });+ break;+ }++ case "returnPickedRemainder": {+ const {+ pickingListLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Lock the line: every case here read-modify-writes its picked or+ // returned counter, so two concurrent scans of the same line would+ // both add to the same stale total and the ledger would double. Same+ // lock post-stock-transfer takes.+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .forUpdate()+ .executeTakeFirstOrThrow();++ const totalReturned = await returnTrackedAllocationRemainder(trx, {+ today,+ line,+ trackedEntityId,+ locationId,+ userId,+ companyId+ });++ // Legacy single-allocation call: restore the consumption pointer+ // only when something actually returned (matching the original+ // early-return behavior). The sweep cases decide per material.+ if (totalReturned > 0) {+ await restoreJobMaterialSource(trx, line, userId, companyId);+ }+ });+ break;+ }++ case "returnOperationRemainders": {+ const { jobOperationId, userId, companyId } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ const op = await trx+ .selectFrom("jobOperation")+ .where("id", "=", jobOperationId)+ .where("companyId", "=", companyId)+ .select(["id", "jobId", "quantityComplete"])+ .executeTakeFirst();+ if (!op) throw new NotFoundError("Job operation not found");+ if (!op.jobId) return;++ const job = await trx+ .selectFrom("job")+ .where("id", "=", op.jobId)+ .where("companyId", "=", companyId)+ .select(["id", "quantity", "locationId", "status"])+ .executeTakeFirst();+ if (!job) throw new NotFoundError("Job not found");+ if (!job.locationId) return;+ const sweepJob = {+ id: job.id,+ quantity: job.quantity,+ locationId: job.locationId+ };++ // The last operation completed the job (sync_finish_job_operation),+ // so its whole remainder is provably surplus under either policy.+ if (job.status === "Completed") {+ await runReturnSweep(trx, {+ scope: "job",+ job: sweepJob,+ today,+ userId,+ companyId+ });+ return;+ }++ const settings = await trx+ .selectFrom("companySettings")+ .where("id", "=", companyId)+ .select("returnPickedMaterialTiming")+ .executeTakeFirst();+ if (settings?.returnPickedMaterialTiming !== "operation") return;++ await runReturnSweep(trx, {+ scope: "operation",+ job: sweepJob,+ opId: op.id,+ opQuantityComplete: Number(op.quantityComplete ?? 0),+ today,+ userId,+ companyId+ });+ });+ break;+ }++ case "returnJobRemainders": {+ const { jobId, userId, companyId } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ const job = await trx+ .selectFrom("job")+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .select(["id", "quantity", "locationId", "status"])+ .executeTakeFirst();+ if (!job) throw new NotFoundError("Job not found");+ // Job scope is the final catch-all: only a finished job's remainder+ // is provably surplus (completion-time backflush has already run,+ // or the job is being cancelled and will never consume it).+ const sweepable =+ job.status === "Completed" || job.status === "Cancelled";+ if (!sweepable || !job.locationId) return;++ await runReturnSweep(trx, {+ scope: "job",+ job: {+ id: job.id,+ quantity: job.quantity,+ locationId: job.locationId+ },+ today,+ userId,+ companyId+ });+ });+ break;+ }+ }++ return { success: true, splitEntityId };+ }++ // A balanced Transfer ledger pair moving `quantity` of a tracked entity from one+ // storage unit to another (a pick, unpick, or return is all the same shape).+ function transferPair(args: {+ today: string;+ itemId: string;+ quantity: number;+ locationId: string;+ fromStorageUnitId: string;+ toStorageUnitId: string;+ documentId: string;+ trackedEntityId: string;+ userId: string;+ companyId: string;+ }): ItemLedgerInsert[] {+ const base = {+ postingDate: args.today,+ itemId: args.itemId,+ locationId: args.locationId,+ entryType: "Transfer" as const,+ documentType: "Direct Transfer" as const,+ documentId: args.documentId,+ trackedEntityId: args.trackedEntityId,+ createdBy: args.userId,+ companyId: args.companyId+ };+ return [+ {+ ...base,+ quantity: round(-args.quantity),+ storageUnitId: args.fromStorageUnitId+ },+ {+ ...base,+ quantity: round(args.quantity),+ storageUnitId: args.toStorageUnitId+ }+ ];+ }++ // Point the job material at the lineside shelf so production (backflush/issue)+ // consumes from where the pick just moved the stock.+ async function pointJobMaterialAtLineside(+ trx: any,+ line: { jobMaterialId: string; toStorageUnitId: string | null },+ userId: string,+ companyId: string+ ) {+ if (!line.toStorageUnitId) return;+ await trx+ .updateTable("jobMaterial")+ .set({+ storageUnitId: line.toStorageUnitId,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", line.jobMaterialId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Restore the warehouse source on unpick.+ async function restoreJobMaterialSource(+ trx: any,+ line: { jobMaterialId: string; storageUnitId: string | null },+ userId: string,+ companyId: string+ ) {+ await trx+ .updateTable("jobMaterial")+ .set({+ storageUnitId: line.storageUnitId,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", line.jobMaterialId)+ .where("companyId", "=", companyId)+ .execute();+ }++ type ReturnSweepLine = {+ id: string;+ pickingListId: string;+ jobMaterialId: string;+ jobOperationId: string | null;+ itemId: string;+ quantityPicked: number | string | null;+ quantityReturned: number | string | null;+ storageUnitId: string | null;+ toStorageUnitId: string | null;+ createdAt: string | Date | null;+ };++ // Return the un-consumed remainder of ONE tracked (batch/serial) allocation from+ // the lineside shelf back to the warehouse source. Walks the picked entity's+ // split lineage and moves whatever is still physically on hand at the lineside+ // bin (a partial consume splits the remainder into a NEW entity the picking line+ // never references). Idempotent: nothing on hand → nothing moves.+ //+ // Books the return on pickingListLine.quantityReturned instead of decrementing+ // quantityPicked — the update_picking_list_status trigger reacts to+ // quantityPicked/status changes and would demote a Completed/Partial header back+ // to In Progress. quantityPicked stays gross-picked; net staged at lineside is+ // quantityPicked - quantityReturned. The allocation row keeps its historical+ // decrement/delete-at-0 so the lot becomes re-allocatable (the availability RPCs+ // net allocations out of on-hand). Does NOT repoint jobMaterial.storageUnitId —+ // callers decide that per material.+ async function returnTrackedAllocationRemainder(+ trx: any,+ args: {+ today: string;+ line: {+ id: string;+ pickingListId: string;+ itemId: string;+ storageUnitId: string | null;+ toStorageUnitId: string | null;+ };+ trackedEntityId: string;+ locationId: string;+ userId: string;+ companyId: string;+ }+ ): Promise<number> {+ const { today, line, trackedEntityId, locationId, userId, companyId } = args;+ const lineside = line.toStorageUnitId;++ // Return target = the bin this lot was actually PICKED from, recorded+ // on its Pick trackedActivity at pick time — not the line's stale+ // generation-time source bin, which can be wrong per-lot and is null+ // for a shortage line that later got picked anyway.+ const pickActivities = await trx+ .selectFrom("trackedActivity as ta")+ .innerJoin("trackedActivityInput as tai", "tai.trackedActivityId", "ta.id")+ .where("ta.type", "=", "Pick")+ .where("ta.sourceDocument", "=", "Picking List")+ .where("ta.sourceDocumentId", "=", line.pickingListId)+ .where("tai.trackedEntityId", "=", trackedEntityId)+ .where("ta.companyId", "=", companyId)+ .where("tai.companyId", "=", companyId)+ .orderBy("ta.createdAt", "desc")+ .select("ta.attributes")+ .execute();++ // Use the LATEST pick for this line (activities are newest-first). Its+ // "From Shelf" is the current truth — even if null (picked from an+ // unassigned bin), fall through to the line bin rather than reusing an+ // older pick's stale shelf.+ const latestPickForLine = pickActivities+ .map(+ (a: { attributes: unknown }) =>+ a.attributes as Record<string, unknown> | null+ )+ // Disambiguate if the same entity was picked on multiple lines.+ .find(+ (a: Record<string, unknown> | null) =>+ a?.["Picking List Line"] === line.id+ );+ const pickedFromShelf = latestPickForLine?.["From Shelf"] as+ | string+ | null+ | undefined;++ const source = pickedFromShelf ?? line.storageUnitId;+ // No lineside stage or no source to return to → nothing to do.+ if (!lineside || !source) return 0;++ // Walk the picked entity's split lineage (picked entity + every split+ // descendant). A partial consume splits the un-consumed remainder into+ // a new entity, so the leftover stock at lineside sits under a+ // descendant, not the originally-picked entity.+ const lineage = new Set<string>([trackedEntityId]);+ let frontier: string[] = [trackedEntityId];+ while (frontier.length > 0) {+ const rows = await trx+ .selectFrom("trackedActivityInput as tai")+ .innerJoin(+ "trackedActivityOutput as tao",+ "tao.trackedActivityId",+ "tai.trackedActivityId"+ )+ .where("tai.trackedEntityId", "in", frontier)+ .where("tai.companyId", "=", companyId)+ .whereRef("tao.trackedEntityId", "<>", "tai.trackedEntityId")+ .select("tao.trackedEntityId as id")+ .distinct()+ .execute();+ const next: string[] = [];+ for (const r of rows) {+ if (r.id && !lineage.has(r.id)) {+ lineage.add(r.id);+ next.push(r.id);+ }+ }+ frontier = next;+ }++ // Transfer each lineage entity's remaining lineside on-hand back to the+ // warehouse source bin. A split child whose parent still sits Available at+ // the source bin MERGES back into the parent (no standalone fragment);+ // anything ineligible falls back to today's standalone return — never+ // block a return on merge eligibility.+ const inserts: ItemLedgerInsert[] = [];+ let totalReturned = 0;+ for (const entityId of lineage) {+ const onHandRow = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", entityId)+ .where("storageUnitId", "=", lineside)+ .where("itemId", "=", line.itemId)+ .where("companyId", "=", companyId)+ .select((eb: any) => eb.fn.sum("quantity").as("qty"))+ .executeTakeFirst();+ const onHand = Number(onHandRow?.qty ?? 0);+ if (onHand <= 0) continue;++ const entity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", entityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();+ const parentId = ((entity?.attributes ?? {}) as Record<string, unknown>)[+ "Split From Entity ID"+ ];++ let merged = false;+ if (entity && typeof parentId === "string" && parentId) {+ const parent = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", parentId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ if (+ parent &&+ parent.status === "Available" &&+ parent.readableId === entity.readableId &&+ // Rounded: buildMergeRecords refuses merge > childQty at scale, so a+ // raw compare here could skip a merge the builder would have accepted+ // (0.30000000000000004 of a 0.3 lot) and silently fall back.+ round(onHand) <= round(Number(entity.quantity))+ ) {+ const parentLedgers = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", parent.id)+ .where("companyId", "=", companyId)+ .select(["trackedEntityId", "storageUnitId", "quantity"])+ .execute();++ if (resolveTrackedEntityBin(parentLedgers, parent.id) === source) {+ const merge = buildMergeRecords({+ child: { id: entity.id, quantity: Number(entity.quantity) },+ parent: { id: parent.id, quantity: Number(parent.quantity) },+ mergeQuantity: onHand,+ mergeActivityId: nanoid(),+ companyId,+ userId+ });++ // Physical move: −r on the child at lineside, +r on the parent at+ // the source bin — same Transfer shape the sweep books today.+ inserts.push(+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(-onHand),+ locationId,+ storageUnitId: lineside,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: line.pickingListId,+ trackedEntityId: entity.id,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: round(onHand),+ locationId,+ storageUnitId: source,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: line.pickingListId,+ trackedEntityId: parent.id,+ createdBy: userId,+ companyId+ }+ );++ await trx+ .insertInto("trackedActivity")+ .values(merge.activityInsert)+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values(merge.activityInputInsert)+ .execute();+ await trx+ .insertInto("trackedActivityOutput")+ .values(merge.activityOutputInsert)+ .execute();+ await trx+ .updateTable("trackedEntity")+ .set(merge.parentUpdate)+ .where("id", "=", parent.id)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .updateTable("trackedEntity")+ .set(merge.childUpdate)+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();++ merged = true;+ }+ }+ }++ if (!merged) {+ inserts.push(+ ...transferPair({+ today,+ itemId: line.itemId,+ quantity: onHand,+ locationId,+ fromStorageUnitId: lineside,+ toStorageUnitId: source,+ documentId: line.pickingListId,+ trackedEntityId: entityId,+ userId,+ companyId+ })+ );+ }+ totalReturned += onHand;+ }++ if (totalReturned <= 0) return 0;++ await trx.insertInto("itemLedger").values(inserts).execute();++ // Decrement the recorded allocation by what was returned so the lot is+ // re-allocatable.+ const allocation = await trx+ .selectFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", line.id)+ .where("trackedEntityId", "=", trackedEntityId)+ .selectAll()+ .executeTakeFirst();+ if (allocation) {+ const nextQuantity = Math.max(+ 0,+ Number(allocation.quantity ?? 0) - totalReturned+ );+ const nextPicked = Math.max(+ 0,+ Number(allocation.quantityPicked ?? 0) - totalReturned+ );+ if (nextPicked <= 0) {+ await trx+ .deleteFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", line.id)+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ await trx+ .updateTable("pickingListLineTrackedEntity")+ .set({ quantity: nextQuantity, quantityPicked: nextPicked })+ .where("pickingListLineId", "=", line.id)+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ await trx+ .updateTable("pickingListLine")+ .set((eb: any) => ({+ quantityReturned: eb("quantityReturned", "+", totalReturned),+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ }))+ .where("id", "=", line.id)+ .where("companyId", "=", companyId)+ .execute();++ return totalReturned;+ }++ // Return the un-consumed remainder of an UNTRACKED job material. There is no+ // per-line consumption attribution (jobMaterial.quantityIssued is one counter+ // across N lines), so the remainder is computed per material —+ // returnable = max(0, Σ(line.picked − line.returned) − max(issued, owed))+ // — and allocated back across the material's lines newest-first. `owed` is what+ // completion-time backflush is still entitled to draw from lineside; holding it+ // back is what keeps the top-up suppliable (never derived from bin on-hand: the+ // lineside bin is shared per work center across jobs).+ async function returnUntrackedMaterialRemainder(+ trx: any,+ args: {+ today: string;+ material: {+ id: string;+ itemId: string;+ jobId: string;+ quantityIssued: number | string | null;+ };+ lines: ReturnSweepLine[];+ owed: number;+ locationId: string;+ userId: string;+ companyId: string;+ }+ ): Promise<number> {+ const { today, material, lines, owed, locationId, userId, companyId } = args;++ const staged = lines+ .map((l) => ({+ ...l,+ stagedNet: Math.max(+ 0,+ Number(l.quantityPicked ?? 0) - Number(l.quantityReturned ?? 0)+ )+ }))+ .filter((l) => l.stagedNet > 0 && l.toStorageUnitId);+ if (staged.length === 0) return 0;++ const budgets = orderOldFirst(+ await getPickedBudgets(trx, { material, locationId, companyId }),+ material.itemId+ );+ const returnableByItem = new Map<string, number>();+ let owedRemaining = Math.max(0, owed);+ for (const budget of budgets) {+ const hold =+ budget.factor > 0+ ? Math.min(budget.available, owedRemaining * budget.factor)+ : 0;+ owedRemaining -= budget.factor > 0 ? hold / budget.factor : 0;+ returnableByItem.set(budget.itemId, Math.max(0, budget.available - hold));+ }+ let returnable = [...returnableByItem.values()].reduce((a, b) => a + b, 0);+ if (returnable <= 0) return 0;++ // Newest-first: return the most recently staged stock, deterministic.+ staged.sort(+ (a, b) =>+ new Date(b.createdAt ?? 0).getTime() -+ new Date(a.createdAt ?? 0).getTime()+ );++ // Lazy fallback bin for lines picked from an unassigned source.+ let fallbackBin: string | null | undefined;+ const resolveFallbackBin = async () => {+ if (fallbackBin !== undefined) return fallbackBin;+ const pickMethod = await trx+ .selectFrom("pickMethod")+ .where("itemId", "=", material.itemId)+ .where("locationId", "=", locationId)+ .where("companyId", "=", companyId)+ .select("defaultStorageUnitId")+ .executeTakeFirst();+ fallbackBin = pickMethod?.defaultStorageUnitId ?? null;+ return fallbackBin;+ };++ const inserts: ItemLedgerInsert[] = [];+ let totalReturned = 0;+ for (const line of staged) {+ if (returnable <= 0) break;+ const itemReturnable = returnableByItem.get(line.itemId) ?? 0;+ const quantity = Math.min(line.stagedNet, itemReturnable);+ if (quantity <= 0) continue;+ returnableByItem.set(line.itemId, itemReturnable - quantity);+ // Return target: the line's source bin, else the item's default pick bin,+ // else location-level unassigned stock (mirrors picks from unassigned bins;+ // never strands the return).+ const target = line.storageUnitId ?? (await resolveFallbackBin());++ const base = {+ postingDate: today,+ itemId: line.itemId,+ locationId,+ entryType: "Transfer" as const,+ documentType: "Direct Transfer" as const,+ documentId: line.pickingListId,+ createdBy: userId,+ companyId+ };+ inserts.push(+ {+ ...base,+ quantity: round(-quantity),+ storageUnitId: line.toStorageUnitId+ },+ { ...base, quantity: round(quantity), storageUnitId: target }+ );++ await trx+ .updateTable("pickingListLine")+ .set((eb: any) => ({+ quantityReturned: eb("quantityReturned", "+", quantity),+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ }))+ .where("id", "=", line.id)+ .where("companyId", "=", companyId)+ .execute();++ returnable -= quantity;+ totalReturned += quantity;+ }++ if (totalReturned <= 0) return 0;+ await trx.insertInto("itemLedger").values(inserts).execute();+ return totalReturned;+ }++ // Sweep every live picking-list line of one operation (scope "operation") or of+ // one whole job (scope "job"), returning each material's un-consumed remainder+ // and repointing jobMaterial.storageUnitId back at the warehouse source when+ // nothing staged remains to consume.+ async function runReturnSweep(+ trx: any,+ args: {+ scope: "operation" | "job";+ job: { id: string; quantity: number | string | null; locationId: string };+ opId?: string;+ opQuantityComplete?: number;+ today: string;+ userId: string;+ companyId: string;+ }+ ) {+ const { scope, job, opId, opQuantityComplete, today, userId, companyId } =+ args;++ let lineQuery = trx+ .selectFrom("pickingListLine as pll")+ .innerJoin("pickingList as pl", "pl.id", "pll.pickingListId")+ .where("pll.companyId", "=", companyId)+ .where("pll.jobId", "=", job.id)+ .where("pll.status", "<>", "Cancelled")+ .where("pl.status", "not in", ["Draft", "Cancelled"])+ .select([+ "pll.id",+ "pll.pickingListId",+ "pll.jobMaterialId",+ "pll.jobOperationId",+ "pll.itemId",+ "pll.quantityPicked",+ "pll.quantityReturned",+ "pll.storageUnitId",+ "pll.toStorageUnitId",+ "pll.createdAt"+ ]);+ if (scope === "operation") {+ lineQuery = lineQuery.where("pll.jobOperationId", "=", opId);+ }+ const lines: ReturnSweepLine[] = await lineQuery.execute();+ if (lines.length === 0) return;++ const materialIds = [...new Set(lines.map((l) => l.jobMaterialId))];+ const materials = await trx+ .selectFrom("jobMaterial")+ .where("id", "in", materialIds)+ .where("companyId", "=", companyId)+ .select([+ "id",+ "itemId",+ "jobId",+ "jobOperationId",+ "quantityIssued",+ "estimatedQuantity",+ "requiresBatchTracking",+ "requiresSerialTracking"+ ])+ .execute();++ const jobQuantity = Number(job.quantity ?? 0);++ for (const material of materials) {+ const materialLines = lines.filter((l) => l.jobMaterialId === material.id);+ const tracked =+ Boolean(material.requiresBatchTracking) ||+ Boolean(material.requiresSerialTracking);++ // What completion-time backflush is still entitled to consume from lineside.+ // Op scope, material owned by the completing op: its completed quantity is+ // final, so owed = (estimatedQuantity ÷ job quantity) × op completed — the+ // estimated ratio keeps the scrap allowance staged. A material owned by a+ // DIFFERENT (possibly not-yet-run) op has no final quantity yet: hold its+ // full estimate. Job scope: backflush already ran inside+ // complete_job_to_inventory, nothing further is owed.+ let owed = 0;+ if (scope === "operation") {+ const estimated = Number(material.estimatedQuantity ?? 0);+ if (material.jobOperationId === opId && jobQuantity > 0) {+ owed = (estimated / jobQuantity) * Number(opQuantityComplete ?? 0);+ } else {+ owed = estimated;+ }+ }++ if (tracked) {+ for (const line of materialLines) {+ const allocations = await trx+ .selectFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", line.id)+ .select("trackedEntityId")+ .execute();+ for (const allocation of allocations) {+ await returnTrackedAllocationRemainder(trx, {+ today,+ line,+ trackedEntityId: allocation.trackedEntityId,+ locationId: job.locationId,+ userId,+ companyId+ });+ }+ }+ } else {+ await returnUntrackedMaterialRemainder(trx, {+ today,+ material,+ lines: materialLines,+ owed,+ locationId: job.locationId,+ userId,+ companyId+ });+ }++ await maybeRestoreJobMaterialSource(trx, {+ scope,+ material: {+ id: material.id,+ itemId: material.itemId,+ jobId: material.jobId,+ quantityIssued: material.quantityIssued+ },+ locationId: job.locationId,+ userId,+ companyId+ });+ }+ }++ // Repoint jobMaterial.storageUnitId back at the warehouse source once nothing+ // staged remains for it to consume at lineside. Job scope: the job is done —+ // always restore. Op scope: restore only when net staged (Σ picked − returned+ // across ALL live lines of the material) is covered by what was already issued —+ // otherwise the held-back (owed) stock must stay consumable at lineside by the+ // completion-time backflush. Skips the restore when no line has a source bin,+ // rather than nulling the pointer.+ async function maybeRestoreJobMaterialSource(+ trx: any,+ args: {+ scope: "operation" | "job";+ material: {+ id: string;+ itemId: string;+ jobId: string;+ quantityIssued: number | string | null;+ };+ locationId: string;+ userId: string;+ companyId: string;+ }+ ) {+ const { scope, material, locationId, userId, companyId } = args;++ const liveLines = await trx+ .selectFrom("pickingListLine as pll")+ .innerJoin("pickingList as pl", "pl.id", "pll.pickingListId")+ .where("pll.jobMaterialId", "=", material.id)+ .where("pll.companyId", "=", companyId)+ .where("pll.status", "<>", "Cancelled")+ .where("pl.status", "not in", ["Draft", "Cancelled"])+ .select([+ "pll.storageUnitId",+ "pll.quantityPicked",+ "pll.quantityReturned",+ "pll.createdAt"+ ])+ .execute();++ if (scope === "operation") {+ const budgets = await getPickedBudgets(trx, {+ material,+ locationId,+ companyId+ });+ if (budgets.some((b) => b.available > 0)) return;+ }++ const sourceLine = liveLines+ .filter((l: ReturnSweepLine) => l.storageUnitId)+ .sort(+ (a: ReturnSweepLine, b: ReturnSweepLine) =>+ new Date(b.createdAt ?? 0).getTime() -+ new Date(a.createdAt ?? 0).getTime()+ )[0];+ if (!sourceLine) return;++ await restoreJobMaterialSource(+ trx,+ { jobMaterialId: material.id, storageUnitId: sourceLine.storageUnitId },+ userId,+ companyId+ );+ }++ // Pure resolver for a spare part returned from a maintenance dispatch: how much+ // of the return carries value, and at what unit cost.+ //+ // A return reverses what the dispatch actually expensed, so it reads the+ // dispatch's own 'Maintenance Consumption' cost-ledger rows for the item+ // (signed: issues negative, earlier returns positive) and books at their+ // blended issue cost — a round trip nets zero P&L. Only the quantity still+ // expensed (issued minus already returned) is valued: an issue posted before+ // maintenance consumption carried value has no cost row, so returning it must+ // not credit an expense that was never debited. Returns null when nothing is+ // left to reverse — the caller writes the ledger row alone.++ export function resolveMaintenanceReturnCost(+ rows: Array<{ quantity: number; cost: number }>,+ returnQuantity: number+ ): { quantity: number; unitCost: number } | null {+ let issuedQuantity = 0;+ let issuedCost = 0;+ let returnedQuantity = 0;+ for (const row of rows) {+ const quantity = Number(row.quantity) || 0;+ if (quantity < 0) {+ issuedQuantity += -quantity;+ issuedCost += Math.abs(Number(row.cost) || 0);+ } else {+ returnedQuantity += quantity;+ }+ }++ const outstanding = issuedQuantity - returnedQuantity;+ const quantity = Math.min(Math.abs(returnQuantity), outstanding);+ if (issuedQuantity < EPSILON || quantity < EPSILON) return null;++ return { quantity, unitCost: issuedCost / issuedQuantity };+ }+ // Reopen + capacity top-up after scrapping units of a make method, so the+ // replacement units can run the FULL routing (spec+ // .ai/specs/2026-08-06-scrap-unscrap-flow.md §1.6).+ //+ // - Done operations reopen to Ready (never Canceled); the quantity-sync+ // interceptor re-flips them once good quantity reaches targetQuantity —+ // which scrap no longer counts toward (20260807090629).+ // - targetQuantity is NEVER written: it is the good quantity to produce.+ // - operationQuantity (capacity incl. planned scrap allowance) is topped up+ // only when cumulative actual scrap exceeds the allowance:+ // needed = targetQuantity + totalScrapped; bump = max(0, needed − current).+ // - job.scrapQuantity mirrors the same monotonic rule for the ROOT make+ // method so the generated job.productionQuantity stays coherent.+ // - jobMaterial estimates grow by their per-parent quantity × the bump so+ // backflush caps (estimatedQuantity − quantityIssued) cover the+ // replacement units. Make-to-Order children are excluded (their capacity+ // is their own make method's).+ export async function applyScrapReplacement(+ trx: Transaction<KyselyDatabase>,+ args: {+ jobMakeMethodId: string;+ jobId: string;+ companyId: string;+ userId: string;+ }+ ): Promise<{ addedQuantity: number }> {+ const { jobMakeMethodId, jobId, companyId, userId } = args;++ const operations = await trx+ .selectFrom("jobOperation")+ .select(["id", "status", "operationQuantity", "targetQuantity"])+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .execute();+ if (operations.length === 0) return { addedQuantity: 0 };++ // Cumulative actual scrap for this make method, read from productionQuantity+ // directly so the math is independent of interceptor timing.+ const scrapTotal = await trx+ .selectFrom("productionQuantity")+ .select((eb) => eb.fn.sum("quantity").as("quantity"))+ .where("type", "=", "Scrap")+ .where("companyId", "=", companyId)+ .where(+ "jobOperationId",+ "in",+ operations.map((op) => op.id)+ )+ .executeTakeFirst();+ const totalScrapped = Number(scrapTotal?.quantity ?? 0);++ await trx+ .updateTable("jobOperation")+ .set({+ status: "Ready",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .where("status", "=", "Done")+ .execute();++ let addedQuantity = 0;+ for (const operation of operations) {+ const target = Number(operation.targetQuantity ?? 0);+ if (target <= 0) continue;+ const current = Number(operation.operationQuantity ?? 0);+ const needed = target + totalScrapped;+ const bump = Math.max(0, needed - current);+ if (bump <= 0) continue;+ addedQuantity = Math.max(addedQuantity, bump);+ await trx+ .updateTable("jobOperation")+ .set({+ operationQuantity: needed,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", operation.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ if (addedQuantity > 0) {+ // Root make method drives the job header's planned-scrap bucket.+ const makeMethod = await trx+ .selectFrom("jobMakeMethod")+ .select(["parentMaterialId"])+ .where("id", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (makeMethod && makeMethod.parentMaterialId === null) {+ const job = await trx+ .selectFrom("job")+ .select(["scrapQuantity"])+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const currentScrapQuantity = Number(job?.scrapQuantity ?? 0);+ if (totalScrapped > currentScrapQuantity) {+ await trx+ .updateTable("job")+ .set({+ scrapQuantity: totalScrapped,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Grow material requirements for the replacement units (mirrors+ // recalculateJobRequirements' per-parent math).+ const materials = await trx+ .selectFrom("jobMaterial")+ .select(["id", "quantity", "estimatedQuantity"])+ .where("jobMakeMethodId", "=", jobMakeMethodId)+ .where("companyId", "=", companyId)+ .where("methodType", "!=", "Make to Order")+ .execute();+ for (const material of materials) {+ const perParent = Number(material.quantity) || 0;+ if (perParent <= 0) continue;+ await trx+ .updateTable("jobMaterial")+ .set({+ estimatedQuantity:+ Number(material.estimatedQuantity ?? 0) + perParent * addedQuantity+ })+ .where("id", "=", material.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ return { addedQuantity };+ }+ /**+ * Applies the company's expired-entity policy to entities about to be+ * consumed: `ok` with a warning under `Warn`, `ok: false` with the reason when+ * blocked. An override with a reason passes under `BlockWithOverride`; the+ * caller records it.+ */+ function checkExpiredEntities(+ entities: { id: string; expirationDate: string | null }[],+ policy: ExpiredEntityPolicy,+ override: ExpiryOverride,+ today: CalendarDate+ ): { ok: true; warning?: string } | { ok: false; reason: string } {+ const expired = expiredEntities(entities, today);+ if (expired.length === 0) return { ok: true };++ const ids = expired.map((e) => e.id).join(", ");+ const noun = `entit${expired.length === 1 ? "y" : "ies"}`;+ switch (expiryVerdict(policy, override)) {+ case "warn":+ return {+ ok: true,+ warning: `Consumed ${expired.length} expired tracked ${noun}: ${ids}`+ };+ case "allow":+ return { ok: true };+ case "block":+ return {+ ok: false,+ reason: `Cannot consume expired tracked ${noun}: ${ids}`+ };+ }+ }++ async function issueJobOperationMaterials(+ trx: Transaction<KyselyDatabase>,+ {+ jobOperationId,+ quantity,+ companyId,+ userId,+ postingStatus,+ accountDefaults,+ dimensionMap,+ db+ }: {+ jobOperationId: string;+ quantity: number;+ companyId: string;+ userId: string;+ // Provisional before the company's accounting cutover, Posted after it.+ postingStatus: AutomaticJournalStatus;+ accountDefaults: ConsumeAccountDefaults;+ dimensionMap: Map<string, string>;+ db: Kysely<KyselyDatabase>;+ }+ ) {+ const materialsToIssue = await trx+ .selectFrom("jobMaterial")+ .where("jobOperationId", "=", jobOperationId)+ .where("companyId", "=", companyId)+ .where("itemType", "in", ["Material", "Part", "Consumable"])+ .where("methodType", "!=", "Make to Order")+ .where("estimatedQuantity", ">", 0)+ .where("requiresBatchTracking", "=", false)+ .where("requiresSerialTracking", "=", false)+ .selectAll()+ .execute();++ const kittedChildren = await trx+ .selectFrom("jobMaterialWithMakeMethodId")+ .where("jobOperationId", "=", jobOperationId)+ .where("companyId", "=", companyId)+ .where("itemType", "in", ["Material", "Part", "Consumable"])+ .where("methodType", "=", "Make to Order")+ .where("kit", "=", true)+ .selectAll()+ .execute();++ const jobMakeMethodIdsOfKittedChildren = kittedChildren.map(+ (kittedChild) => kittedChild.jobMaterialMakeMethodId+ );++ if (jobMakeMethodIdsOfKittedChildren.length > 0) {+ const materialsToIssueFromKittedChildren = await trx+ .selectFrom("jobMaterial")+ .where("jobMakeMethodId", "in", jobMakeMethodIdsOfKittedChildren)+ .where("itemType", "in", ["Material", "Part", "Consumable"])+ .where("methodType", "!=", "Make to Order")+ .where("estimatedQuantity", ">", 0)+ .where("requiresBatchTracking", "=", false)+ .where("requiresSerialTracking", "=", false)+ .selectAll()+ .execute();++ materialsToIssue.push(...materialsToIssueFromKittedChildren);+ }++ if (materialsToIssue.length === 0) return { totalMaterialCost: 0 };++ const jobId = materialsToIssue[0]!.jobId;++ const [job, items] = await Promise.all([+ trx+ .selectFrom("job")+ .where("id", "=", jobId)+ .select(["locationId", "jobId"])+ .executeTakeFirst(),+ trx+ .selectFrom("item")+ .where(+ "id",+ "in",+ materialsToIssue.map((material) => material.itemId)+ )+ .select(["id", "item.itemTrackingType"])+ .execute()+ ]);++ if (!job?.locationId) {+ throw new Error("Job location is required");+ }++ const itemIdIsTracked = new Map(+ items.map((item) => [item.id, item.itemTrackingType === "Inventory"])+ );++ // Company business day — item/cost ledgers and this function's journals must+ // all post on the same day (they previously relied on the CURRENT_DATE default,+ // which is UTC and diverged from the company-TZ journals here).+ const today = datetime+ .today(await getCompanyTimeZone(trx, companyId))+ .toString();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ const opStorageUnitId = await getOperationLinesideBin(trx, {+ jobOperationId,+ companyId+ });+ const takenShared: SharedTakes = new Map();+ for await (const material of materialsToIssue) {+ // Cap the backflush at the material's remaining unissued requirement,+ // mirroring backflush_job_materials. Without this, materials already+ // issued manually (e.g. from MES after skipping the operation) get+ // consumed a second time on operation completion — duplicate item/cost+ // ledger entries and duplicate DR WIP / CR Inventory journal lines.+ const demandQuantity = Number(material.quantity) * quantity;+ const remainingQuantity = Math.max(+ Number(material.estimatedQuantity ?? 0) -+ Number(material.quantityIssued ?? 0),+ 0+ );+ const quantityToIssue = Math.min(demandQuantity, remainingQuantity);++ if (quantityToIssue <= 0) continue;++ const budgets = orderOldFirst(+ await getPickedBudgets(trx, {+ material,+ locationId: job.locationId,+ companyId,+ opStorageUnitId,+ takenShared+ }),+ material.itemId+ );+ const { takes, remaining } = allocateAcrossBudgets(+ quantityToIssue,+ budgets,+ Number(material.quantity ?? 0)+ );+ recordSharedTakes(takenShared, takes);+ for (const take of takes) {+ if (!take.budget.isInventory) continue;+ for (const row of splitTakeByBin(take)) {+ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineId: jobOperationId,+ companyId,+ itemId: take.budget.itemId,+ quantity: -row.quantity,+ locationId: job.locationId,+ storageUnitId: row.storageUnitId,+ postingDate: today,+ createdBy: userId+ });+ }+ }++ if (remaining > 0) {+ let proposedStorageUnitId = material.storageUnitId;++ if (!proposedStorageUnitId) {+ if (material.defaultStorageUnit) {+ const pickMethod = await trx+ .selectFrom("pickMethod")+ .where("itemId", "=", material.itemId)+ .where("locationId", "=", job.locationId!)+ .where("companyId", "=", companyId)+ .select("defaultStorageUnitId")+ .executeTakeFirst();++ proposedStorageUnitId = pickMethod?.defaultStorageUnitId ?? null;++ if (!proposedStorageUnitId) {+ proposedStorageUnitId = await getStorageUnitWithHighestQuantity(+ trx,+ material.itemId,+ job.locationId!+ );+ }+ } else {+ proposedStorageUnitId = await getStorageUnitWithHighestQuantity(+ trx,+ material.itemId,+ job.locationId!+ );+ }+ }++ const currentStorageUnitQuantity = await trx+ .selectFrom("itemLedger")+ .select((eb) => eb.fn.sum("quantity").as("quantity"))+ .where("itemId", "=", material.itemId)+ .where("locationId", "=", job.locationId!)+ .where("storageUnitId", "=", proposedStorageUnitId ?? "")+ .executeTakeFirst();++ const allStorageUnitQuantities = await trx+ .selectFrom("itemLedger")+ .select(["storageUnitId", (eb) => eb.fn.sum("quantity").as("quantity")])+ .where("itemId", "=", material.itemId)+ .where("locationId", "=", job.locationId!)+ .groupBy("storageUnitId")+ .having((eb) => eb.fn.sum("quantity"), ">", 0)+ .execute();++ let finalStorageUnitId = proposedStorageUnitId;+ const currentQuantity = Number(currentStorageUnitQuantity?.quantity ?? 0);++ if (currentQuantity < remaining && allStorageUnitQuantities.length > 0) {+ const bestStorageUnit = allStorageUnitQuantities.reduce(+ (best, current) =>+ Number(current.quantity) > Number(best.quantity) ? current : best+ );+ finalStorageUnitId = bestStorageUnit.storageUnitId ?? null;+ }++ const isTracked = itemIdIsTracked.get(material.itemId);++ if (isTracked) {+ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineId: jobOperationId,+ companyId,+ itemId: material.itemId,+ quantity: -remaining,+ locationId: job.locationId,+ storageUnitId: finalStorageUnitId,+ postingDate: today,+ createdBy: userId+ });+ }+ }++ await trx+ .updateTable("jobMaterial")+ .set({+ quantityIssued: round(+ round(Number(material.quantityIssued) ?? 0) + round(quantityToIssue)+ )+ })+ .where("id", "=", material.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Total material cost this call relieved from inventory into WIP — the+ // jobOperationScrap case posts its WIP→scrap journal from this figure so a+ // second calculateCOGS pass never double-relieves cost layers.+ let totalMaterialCost = 0;++ if (itemLedgerInserts.length > 0) {+ await trx.insertInto("itemLedger").values(itemLedgerInserts).execute();++ for (const ledger of itemLedgerInserts) {+ await updatePickMethodDefaultStorageUnitIfNeeded(+ trx,+ ledger.itemId,+ ledger.locationId,+ ledger.storageUnitId,+ companyId,+ userId+ );+ }+ }++ if (itemLedgerInserts.length > 0) {+ const journalLineInserts: {+ accountId: string;+ description: string;+ amount: number;+ quantity: number;+ documentType: "Job Consumption";+ documentId: string;+ documentLineReference: string;+ journalLineReference: string;+ companyId: string;+ }[] = [];++ const journalLineDimensionsMeta: {+ itemPostingGroupId: string | null;+ itemId: string | null;+ locationId: string | null;+ }[] = [];++ const jobForLocation = await trx+ .selectFrom("job")+ .where("id", "=", jobId)+ .select(["locationId"])+ .executeTakeFirst();++ const consumedItemIds = [+ ...new Set(itemLedgerInserts.map((l) => l.itemId))+ ];+ const [consumedItemCosts, consumedItems] =+ consumedItemIds.length > 0+ ? await Promise.all([+ trx+ .selectFrom("itemCost")+ .where("itemId", "in", consumedItemIds)+ .where("companyId", "=", companyId)+ .select(["itemId", "itemPostingGroupId"])+ .execute(),+ trx+ .selectFrom("item")+ .where("id", "in", consumedItemIds)+ .where("companyId", "=", companyId)+ .select(["id", "replenishmentSystem"])+ .execute()+ ])+ : [[], []];+ const consumedPostingGroupMap = new Map(+ consumedItemCosts.map((ic) => [ic.itemId, ic.itemPostingGroupId])+ );+ const consumedReplenishmentMap = new Map(+ consumedItems.map((i) => [i.id, i.replenishmentSystem])+ );++ for (const ledger of itemLedgerInserts) {+ const materialQuantity = Math.abs(Number(ledger.quantity));+ if (materialQuantity === 0) continue;++ const cogsResult = await calculateCOGS(trx, {+ itemId: ledger.itemId,+ quantity: materialQuantity,+ companyId+ });+ totalMaterialCost += cogsResult.totalCost;++ const journalLineReference = nanoid();++ journalLineInserts.push({+ accountId: accountDefaults.workInProgressAccount,+ description: "WIP Account",+ amount: debit("asset", cogsResult.totalCost),+ quantity: materialQuantity,+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineReference:+ journalReference.to.materialIssue(jobOperationId),+ journalLineReference,+ companyId+ });++ const inventoryAccount = resolveInventoryAccount(+ consumedReplenishmentMap.get(ledger.itemId) ?? null,+ accountDefaults+ );+ journalLineInserts.push({+ accountId: inventoryAccount.account,+ description: inventoryAccount.description,+ amount: credit("asset", cogsResult.totalCost),+ quantity: materialQuantity,+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineReference:+ journalReference.to.materialIssue(jobOperationId),+ journalLineReference,+ companyId+ });++ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: "Consumption",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Job Consumption",+ documentId: jobId,+ itemId: ledger.itemId,+ quantity: -materialQuantity,+ cost: -cogsResult.totalCost,+ remainingQuantity: 0,+ postingDate: today,+ companyId+ })+ .execute();++ for (let i = 0; i < 2; i++) {+ journalLineDimensionsMeta.push({+ itemPostingGroupId:+ consumedPostingGroupMap.get(ledger.itemId) ?? null,+ itemId: ledger.itemId ?? null,+ locationId: jobForLocation?.locationId ?? null+ });+ }+ }++ if (journalLineInserts.length > 0) {+ // Resolve the period from the SAME hoisted `today` the ledger rows used —+ // a midnight rollover mid-transaction must not split journal and ledger.+ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, trx, today)+ : null;+ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `Material Issue to Job ${job?.jobId ?? jobId}`,+ postingDate: today,+ companyId,+ sourceType: "Job Consumption",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((line) => ({+ ...line,+ journalId: journalResult.id+ }))+ )+ .returning(["id"])+ .execute();++ if (dimensionMap.size > 0) {+ const dimensionInserts: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];++ journalLineResults.forEach((jl, index) => {+ const meta = journalLineDimensionsMeta[index];+ if (!meta) return;++ if (meta.itemPostingGroupId && dimensionMap.has("ItemPostingGroup")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("ItemPostingGroup")!,+ valueId: meta.itemPostingGroupId,+ companyId+ });+ }+ if (meta.itemId && dimensionMap.has("Item")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId+ });+ }+ if (meta.locationId && dimensionMap.has("Location")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Location")!,+ valueId: meta.locationId,+ companyId+ });+ }+ });++ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }+ }+ }+ }++ return { totalMaterialCost };+ }++ async function createMaterialWipEntries(+ trx: Transaction<KyselyDatabase>,+ args: {+ // trackedEntityId: the serial consumed, relieved from its own cost layer+ // first (specific identification, lib/cost-layer-order.ts).+ consumptionLedgers: Array<{+ itemId: string;+ quantity: number;+ trackedEntityId?: string | null;+ }>;+ jobId: string;+ operationId: string;+ description: string;+ wipAccount: string;+ rawMaterialsAccount: string;+ finishedGoodsAccount: string;+ dimensionMap: Map<string, string>;+ jobLocationId: string | null;+ db: Kysely<KyselyDatabase>;+ companyId: string;+ userId: string;+ // Provisional before the company's accounting cutover, Posted after it.+ postingStatus: AutomaticJournalStatus;+ }+ ) {+ const {+ consumptionLedgers,+ jobId,+ operationId,+ description,+ wipAccount,+ rawMaterialsAccount,+ finishedGoodsAccount,+ dimensionMap,+ jobLocationId,+ companyId,+ userId,+ postingStatus+ } = args;++ // Cost layer posts on the company business day, matching the caller's+ // itemLedger movement (was defaulting to CURRENT_DATE = UTC).+ const today = datetime+ .today(await getCompanyTimeZone(trx, companyId))+ .toString();++ const journalLineInserts: {+ accountId: string;+ description: string;+ amount: number;+ quantity: number;+ documentType: "Job Consumption";+ documentId: string;+ documentLineReference: string;+ journalLineReference: string;+ companyId: string;+ }[] = [];++ const journalLineDimensionsMeta: {+ itemPostingGroupId: string | null;+ itemId: string | null;+ locationId: string | null;+ }[] = [];++ const uniqueItemIds = [...new Set(consumptionLedgers.map((l) => l.itemId))];+ const [consumedItemCosts, consumedItems] =+ uniqueItemIds.length > 0+ ? await Promise.all([+ trx+ .selectFrom("itemCost")+ .where("itemId", "in", uniqueItemIds)+ .where("companyId", "=", companyId)+ .select(["itemId", "itemPostingGroupId"])+ .execute(),+ trx+ .selectFrom("item")+ .where("id", "in", uniqueItemIds)+ .where("companyId", "=", companyId)+ .select(["id", "replenishmentSystem"])+ .execute()+ ])+ : [[], []];+ const consumedPostingGroupMap = new Map(+ consumedItemCosts.map((ic) => [ic.itemId, ic.itemPostingGroupId])+ );+ const consumedReplenishmentMap = new Map(+ consumedItems.map((i) => [i.id, i.replenishmentSystem])+ );++ for (const ledger of consumptionLedgers) {+ const ledgerQty = Number(ledger.quantity);+ if (ledgerQty === 0) continue;++ const absQty = Math.abs(ledgerQty);+ const isConsumption = ledgerQty < 0;++ let cost: number;+ if (isConsumption) {+ const cogsResult = await calculateCOGS(trx, {+ itemId: ledger.itemId,+ quantity: absQty,+ companyId,+ trackedEntityIds: ledger.trackedEntityId ? [ledger.trackedEntityId] : []+ });+ cost = cogsResult.totalCost;+ } else {+ const itemCost = await trx+ .selectFrom("itemCost")+ .where("itemId", "=", ledger.itemId)+ .where("companyId", "=", companyId)+ .select("unitCost")+ .executeTakeFirst();+ cost = absQty * Number(itemCost?.unitCost ?? 0);+ }++ if (cost <= 0) continue;++ const jlRef = nanoid();+ const inventoryAccount = resolveInventoryAccount(+ consumedReplenishmentMap.get(ledger.itemId) ?? null,+ { rawMaterialsAccount, finishedGoodsAccount }+ );++ if (isConsumption) {+ journalLineInserts.push(+ {+ accountId: wipAccount,+ description: "WIP Account",+ amount: debit("asset", cost),+ quantity: absQty,+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineReference: journalReference.to.materialIssue(operationId),+ journalLineReference: jlRef,+ companyId+ },+ {+ accountId: inventoryAccount.account,+ description: inventoryAccount.description,+ amount: credit("asset", cost),+ quantity: absQty,+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineReference: journalReference.to.materialIssue(operationId),+ journalLineReference: jlRef,+ companyId+ }+ );+ } else {+ journalLineInserts.push(+ {+ accountId: inventoryAccount.account,+ description: inventoryAccount.description,+ amount: debit("asset", cost),+ quantity: absQty,+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineReference: journalReference.to.materialIssue(operationId),+ journalLineReference: jlRef,+ companyId+ },+ {+ accountId: wipAccount,+ description: "WIP Account",+ amount: credit("asset", cost),+ quantity: absQty,+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineReference: journalReference.to.materialIssue(operationId),+ journalLineReference: jlRef,+ companyId+ }+ );+ }++ await trx+ .insertInto("costLedger")+ .values({+ itemLedgerType: "Consumption",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Job Consumption",+ documentId: jobId,+ itemId: ledger.itemId,+ quantity: isConsumption ? -absQty : absQty,+ cost: isConsumption ? -cost : cost,+ remainingQuantity: 0,+ postingDate: today,+ companyId+ })+ .execute();++ for (let i = 0; i < 2; i++) {+ journalLineDimensionsMeta.push({+ itemPostingGroupId: consumedPostingGroupMap.get(ledger.itemId) ?? null,+ itemId: ledger.itemId ?? null,+ locationId: jobLocationId+ });+ }+ }++ if (journalLineInserts.length === 0) return;++ // Same hoisted `today` as this function's ledger rows (see above). A+ // Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, trx, today)+ : null;+ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description,+ postingDate: today,+ companyId,+ sourceType: "Job Consumption",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((line) => ({+ ...line,+ journalId: journalResult.id+ }))+ )+ .returning(["id"])+ .execute();++ if (dimensionMap.size > 0) {+ const dimensionInserts: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];++ journalLineResults.forEach((jl, index) => {+ const meta = journalLineDimensionsMeta[index];+ if (!meta) return;+ if (meta.itemPostingGroupId && dimensionMap.has("ItemPostingGroup")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("ItemPostingGroup")!,+ valueId: meta.itemPostingGroupId,+ companyId+ });+ }+ if (meta.itemId && dimensionMap.has("Item")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId+ });+ }+ if (meta.locationId && dimensionMap.has("Location")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Location")!,+ valueId: meta.locationId,+ companyId+ });+ }+ });++ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }+ }+ }++ // Each child's quantity is its own persist boundary — it becomes one+ // Consumption ledger row — so round PER CHILD and then round the sum. That is+ // what makes jobMaterial.quantityIssued net exactly against those rows; a+ // single round of the raw sum can differ from them by a minor unit.+ function roundedChildTotal(children: { quantity: number | string }[]): number {+ return round(+ children.reduce((sum, child) => sum + round(Number(child.quantity)), 0)+ );+ }++ // The production-event and inspection links a completion/scrap payload carries+ // are written verbatim into productionQuantity, whose single-column FKs accept+ // any company's row — re-read them under companyId first (one query per table).+ async function assertProductionQuantityLinks(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ links: {+ laborProductionEventId?: string;+ machineProductionEventId?: string;+ setupProductionEventId?: string;+ inspectionId?: string;+ inspectionSampleId?: string;+ }+ ) {+ await assertCompanyRecords(+ db,+ "productionEvent",+ [+ links.laborProductionEventId,+ links.machineProductionEventId,+ links.setupProductionEventId+ ],+ companyId,+ "Production event"+ );+ await assertCompanyRecords(+ db,+ "inspection",+ [links.inspectionId],+ companyId,+ "Inspection"+ );+ await assertCompanyRecords(+ db,+ "inspectionSample",+ [links.inspectionSampleId],+ companyId,+ "Inspection sample"+ );+ }++ // Shared accounting context for the job consumption paths: the posting-group+ // defaults and the active dimension map. Every company posts these journals+ // (Provisional before its accounting cutover), so both always load.+ async function loadConsumeAccountingContext(+ db: Kysely<KyselyDatabase>,+ companyId: string+ ) {+ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );+ if (companyRecord.error) throw new Error("Failed to fetch company");++ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }++ const dimensions = await many(+ db,+ "dimension",+ {+ companyGroupId: companyRecord.data.companyGroupId!,+ active: true,+ entityType: ["ItemPostingGroup", "Item", "Location"]+ },+ { columns: ["id", "entityType"] }+ );++ const dimensionMap = new Map<string, string>();+ if (dimensions.data) {+ for (const dim of dimensions.data) {+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);+ }+ }++ return { accountDefaults: accountDefaults.data, dimensionMap };+ }++ type ConsumeAccountDefaults = Awaited<+ ReturnType<typeof loadConsumeAccountingContext>+ >["accountDefaults"];++ // Spare parts issued to a maintenance dispatch are an expense the moment they+ // leave stock. The caller writes the item ledger rows; this values them: each+ // movement relieves (or, on a return, restores) the item's cost layers and+ // posts Dr maintenanceAccount / Cr inventory through+ // the shared adjustment core — one journal per call, tagged with the dispatch's+ // work center. A return reverses at what the dispatch actually booked+ // (`resolveMaintenanceReturnCost`), so a part issued before maintenance+ // consumption carried value comes back with no value either.+ async function valueMaintenanceMovements(+ trx: Transaction<KyselyDatabase>,+ args: {+ dispatch: {+ id: string;+ maintenanceDispatchId: string;+ workCenterId: string | null;+ locationId: string | null;+ };+ // SIGNED: < 0 issued to the dispatch, > 0 returned from it+ movements: Array<{ itemId: string; quantity: number }>;+ postingDate: string;+ companyId: string;+ userId: string;+ }+ ) {+ const { dispatch, postingDate, companyId, userId } = args;+ const movements = args.movements.filter((m) => Number(m.quantity) !== 0);+ if (movements.length === 0) return;++ const itemIds = [...new Set(movements.map((m) => m.itemId))];+ const hasReturns = movements.some((m) => Number(m.quantity) > 0);++ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);+ const [items, itemCosts, bookedRows] = await Promise.all([+ trx+ .selectFrom("item")+ .select(["id", "itemTrackingType", "replenishmentSystem"])+ .where("id", "in", itemIds)+ .where("companyId", "=", companyId)+ .execute(),+ trx+ .selectFrom("itemCost")+ .select([+ "itemId",+ "costingMethod",+ "unitCost",+ "standardCost",+ "itemPostingGroupId"+ ])+ .where("itemId", "in", itemIds)+ .where("companyId", "=", companyId)+ .execute(),+ hasReturns+ ? trx+ .selectFrom("costLedger")+ .select(["itemId", "quantity", "cost"])+ .where("documentId", "=", dispatch.id)+ .where("documentType", "=", "Maintenance Consumption")+ .where("itemId", "in", itemIds)+ .where("companyId", "=", companyId)+ .execute()+ : Promise.resolve([])+ ]);++ const itemById = new Map(items.map((item) => [item.id, item]));+ const itemCostById = new Map(itemCosts.map((cost) => [cost.itemId, cost]));+ const bookedByItem = new Map<+ string,+ Array<{ quantity: number; cost: number }>+ >();+ for (const row of bookedRows) {+ const list = bookedByItem.get(row.itemId as string) ?? [];+ list.push({ quantity: Number(row.quantity), cost: Number(row.cost) });+ bookedByItem.set(row.itemId as string, list);+ }++ const accountDefaults = await trx+ .selectFrom("accountDefault")+ .selectAll()+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!accountDefaults) throw new Error("Error getting account defaults");++ const dimensions = await trx+ .selectFrom("dimension")+ .innerJoin("company", "company.companyGroupId", "dimension.companyGroupId")+ .select(["dimension.id", "dimension.entityType"])+ .where("company.id", "=", companyId)+ .where("dimension.active", "=", true)+ .where("dimension.entityType", "in", [+ "Item",+ "ItemPostingGroup",+ "Location",+ "WorkCenter"+ ])+ .execute();++ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? (await resolveAccountingPeriod(trx, companyId, postingDate, "current"))+ .id+ : null;+ const description = `Maintenance Consumption ${dispatch.maintenanceDispatchId}`;+ let journalId: string | null = null;++ const accounting: Parameters<typeof valueMovement>[1]["accounting"] = {+ postingStatus,+ accountingPeriodId,+ accountDefaults: {+ rawMaterialsAccount: accountDefaults.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaults.finishedGoodsAccount,+ inventoryAdjustmentVarianceAccount:+ accountDefaults.inventoryAdjustmentVarianceAccount+ },+ offsetAccount: accountDefaults.maintenanceAccount,+ offsetDescription: "Maintenance Expense",+ description,+ userId,+ dimensions: Object.fromEntries(+ dimensions+ .filter((dim) => dim.entityType)+ .map((dim) => [dim.entityType as string, dim.id])+ ),+ extraDimensions: dispatch.workCenterId+ ? [{ entityType: "WorkCenter", valueId: dispatch.workCenterId }]+ : [],+ getJournalId: async () => {+ journalId ??= await createAdjustmentJournal(trx, {+ companyId,+ accountingPeriodId,+ status: postingStatus,+ description,+ postingDate,+ userId+ });+ return journalId;+ }+ };++ for (const movement of movements) {+ let quantity = Number(movement.quantity);+ let fixedUnitCost: number | undefined;++ if (quantity > 0) {+ const booked = bookedByItem.get(movement.itemId) ?? [];+ const reversal = resolveMaintenanceReturnCost(booked, quantity);+ if (!reversal) continue;+ quantity = reversal.quantity;+ fixedUnitCost = reversal.unitCost;+ // A later return of the same item in this call sees this one.+ booked.push({ quantity, cost: quantity * fixedUnitCost });+ bookedByItem.set(movement.itemId, booked);+ }++ const item = itemById.get(movement.itemId);+ const itemCost = itemCostById.get(movement.itemId);+ await valueMovement(trx, {+ movement: {+ postingDate,+ itemId: movement.itemId,+ quantity,+ locationId: dispatch.locationId,+ entryType: "Consumption",+ documentType: "Maintenance Consumption",+ documentId: dispatch.id,+ companyId+ },+ item: {+ itemTrackingType: item?.itemTrackingType ?? null,+ replenishmentSystem: item?.replenishmentSystem ?? null,+ itemPostingGroupId: itemCost?.itemPostingGroupId ?? null+ },+ itemCost: {+ costingMethod: itemCost?.costingMethod ?? "Average",+ unitCost: Number(itemCost?.unitCost ?? 0),+ standardCost: Number(itemCost?.standardCost ?? 0)+ },+ accounting,+ fixedUnitCost+ });+ }+ }++ // The per-operation tracked-consumption write sequence, extracted verbatim from+ // the trackedEntitiesToOperation case so trackedEntitiesToBatch can run it once+ // per member inside ONE transaction. Reads run against `trx`, so sequential+ // member calls drawing from the same lot see each other's decrements.+ async function consumeTrackedEntitiesIntoOperation(+ trx: Transaction<KyselyDatabase>,+ {+ materialId,+ jobOperationId,+ itemId,+ parentTrackedEntityId,+ children,+ jobOperationStepId,+ unitNumber,+ overrideExpired,+ overrideReason,+ companyId,+ userId,+ companyToday,+ db,+ postingStatus,+ accountDefaults: accountDefaultsTracked,+ dimensionMap: dimensionMapTracked+ }: {+ materialId?: string;+ jobOperationId?: string;+ itemId?: string;+ parentTrackedEntityId: string;+ children: { trackedEntityId: string; quantity: number }[];+ jobOperationStepId?: string;+ unitNumber?: number;+ overrideExpired?: boolean;+ overrideReason?: string | null;+ companyId: string;+ userId: string;+ companyToday: CalendarDate;+ db: Kysely<KyselyDatabase>;+ // Provisional before the company's accounting cutover, Posted after it.+ postingStatus: AutomaticJournalStatus;+ accountDefaults: ConsumeAccountDefaults;+ dimensionMap: Map<string, string>;+ }+ ): Promise<{+ splitEntities: Array<{+ originalId: string;+ newId: string;+ readableId: string;+ quantity: number;+ remainingQuantity: number;+ }>;+ warning: string | undefined;+ }> {+ let expiredWarning: string | undefined;++ const trackedEntities = await trx+ .selectFrom("trackedEntity")+ .where(+ "id",+ "in",+ children.map((child) => child.trackedEntityId)+ )+ .where("companyId", "=", companyId)+ .selectAll()+ .execute();++ const itemLedgers = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "in", [+ ...children.map((child) => child.trackedEntityId)+ ])+ .orderBy("createdBy", "desc")+ .selectAll()+ .execute();++ if (trackedEntities.length !== children.length) {+ throw new NotFoundError("Tracked entities not found");+ }++ if (trackedEntities.some((entity) => entity.status !== "Available")) {+ throw new Error("Tracked entities are not available");+ }++ // Expiry policy gate. Reads companySettings.inventoryShelfLife.+ const expiredPolicy = await getExpiredEntityPolicy(trx, companyId);+ const expiredCheck = checkExpiredEntities(+ trackedEntities.map((e) => ({+ id: e.id,+ expirationDate: e.expirationDate+ })),+ expiredPolicy,+ { allowed: !!overrideExpired, reason: overrideReason ?? null },+ companyToday+ );+ if (!expiredCheck.ok) {+ throw new Error(expiredCheck.reason);+ }+ if (expiredCheck.warning) {+ expiredWarning = expiredCheck.warning;+ }++ let jobMaterial: Selectable<KyselyDatabase["jobMaterial"]> | undefined;+ let actualMaterialId: string | undefined = materialId;+ const firstTrackedEntity = trackedEntities[0];++ if (materialId) {+ // Existing behavior: fetch the jobMaterial+ jobMaterial = await trx+ .selectFrom("jobMaterial")+ .where("id", "=", materialId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ // Check if any tracked entity has a different sourceDocumentId than the material's itemId+ if (+ firstTrackedEntity &&+ jobMaterial &&+ firstTrackedEntity.sourceDocumentId !== jobMaterial.itemId+ ) {+ // Create a new jobMaterial for the tracked entity's item+ const totalChildQuantity = roundedChildTotal(children);++ const itemCost = await trx+ .selectFrom("itemCost")+ .where("itemId", "=", firstTrackedEntity.sourceDocumentId!)+ .select("unitCost")+ .executeTakeFirst();++ const newJobMaterial = await trx+ .insertInto("jobMaterial")+ .values({+ companyId,+ createdBy: userId,+ description: firstTrackedEntity.sourceDocumentReadableId ?? "",+ estimatedQuantity: 0,+ itemId: firstTrackedEntity.sourceDocumentId!,+ jobId: jobMaterial.jobId!,+ jobMakeMethodId: jobMaterial.jobMakeMethodId,+ jobOperationId: jobMaterial.jobOperationId,+ itemType: jobMaterial.itemType,+ methodType: jobMaterial.methodType,+ quantity: 0,+ quantityIssued: totalChildQuantity,+ requiresBatchTracking: jobMaterial.requiresBatchTracking,+ requiresSerialTracking: jobMaterial.requiresSerialTracking,+ unitCost: itemCost?.unitCost ?? 0+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ actualMaterialId = newJobMaterial.id!;++ // Fetch the newly created jobMaterial+ jobMaterial = await trx+ .selectFrom("jobMaterial")+ .where("id", "=", actualMaterialId)+ .selectAll()+ .executeTakeFirstOrThrow();+ }+ } else if (jobOperationId && itemId) {+ // New behavior: create a jobMaterial on the fly+ const jobOperation = await trx+ .selectFrom("jobOperation")+ .where("id", "=", jobOperationId)+ .where("companyId", "=", companyId)+ .select(["jobId", "jobMakeMethodId"])+ .executeTakeFirst();++ if (!jobOperation) {+ throw new NotFoundError("Job operation not found");+ }++ const item = await trx+ .selectFrom("item")+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .select(["name", "type", "itemTrackingType", "defaultMethodType"])+ .executeTakeFirst();++ if (!item) {+ throw new NotFoundError("Item not found");+ }++ const totalChildQuantity = roundedChildTotal(children);++ const itemCost = await trx+ .selectFrom("itemCost")+ .where("itemId", "=", itemId)+ .select("unitCost")+ .executeTakeFirst();++ const newJobMaterial = await trx+ .insertInto("jobMaterial")+ .values({+ companyId,+ createdBy: userId,+ description: item.name ?? "",+ estimatedQuantity: 0,+ itemId: itemId,+ jobId: jobOperation.jobId!,+ jobMakeMethodId: jobOperation.jobMakeMethodId!,+ jobOperationId: jobOperationId,+ itemType: item.type ?? "Part",+ methodType: item.defaultMethodType ?? "Pull from Inventory",+ quantity: 0,+ quantityIssued: totalChildQuantity,+ requiresBatchTracking: item.itemTrackingType === "Batch",+ requiresSerialTracking: item.itemTrackingType === "Serial",+ unitCost: itemCost?.unitCost ?? 0+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ actualMaterialId = newJobMaterial.id!;++ // Scope this unplanned tracked part to the step it was issued on+ // (assembly view), so it shows on that step rather than as General.+ if (jobOperationStepId) {+ await trx+ .insertInto("jobMaterialStep")+ .values({+ jobMaterialId: actualMaterialId,+ jobOperationStepId+ })+ .onConflict((oc) => oc.doNothing())+ .execute();+ }++ // Fetch the newly created jobMaterial+ jobMaterial = await trx+ .selectFrom("jobMaterial")+ .where("id", "=", actualMaterialId)+ .selectAll()+ .executeTakeFirstOrThrow();+ }++ if (!jobMaterial) {+ throw new NotFoundError("Job material not found");+ }++ // Get item details+ const item = await trx+ .selectFrom("item")+ .where("id", "=", jobMaterial?.itemId!)+ .select(["readableIdWithRevision"])+ .executeTakeFirst();++ // Get job location+ const job = await trx+ .selectFrom("job")+ .select(["id", "locationId"])+ .where("id", "=", jobMaterial?.jobId!)+ .executeTakeFirst();++ // Get parent tracked entity details+ const parentTrackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", parentTrackedEntityId)+ .where("companyId", "=", companyId)+ .select(["id", "sourceDocumentId", "quantity", "attributes", "status"])+ .executeTakeFirst();++ if (!parentTrackedEntity) {+ throw new NotFoundError("Parent tracked entity not found");+ }++ // Create tracked activity+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Consume",+ sourceDocument: "Job Material",+ sourceDocumentId: actualMaterialId,+ sourceDocumentReadableId: item?.readableIdWithRevision ?? "",+ attributes: {+ Job: job?.id!,+ "Job Make Method": jobMaterial?.jobMakeMethodId!,+ "Job Material": jobMaterial?.id!,+ Employee: userId,+ // Assembly view: which step + 1-based unit this consume was for, so+ // the MES can attribute issued quantities per-unit even for a batch+ // parent (where all units share one lot entity).+ ...(jobOperationStepId+ ? { "Job Operation Step": jobOperationStepId }+ : {}),+ ...(unitNumber !== undefined ? { Unit: unitNumber } : {})+ },+ companyId,+ createdBy: userId+ })+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: parentTrackedEntityId,+ quantity: parentTrackedEntity.quantity,+ companyId,+ createdBy: userId+ })+ .execute();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const trackedActivityInputs: Database["public"]["Tables"]["trackedActivityInput"]["Insert"][] =+ [];++ const splitEntities: Array<{+ originalId: string;+ newId: string;+ readableId: string;+ quantity: number;+ remainingQuantity: number;+ }> = [];++ // Process each child tracked entity+ for (const child of children) {+ const trackedEntity = trackedEntities.find(+ (entity) => entity.id === child.trackedEntityId+ );+ if (!trackedEntity) {+ throw new NotFoundError("Tracked entity not found");+ }+ const { trackedEntityId } = child;++ // ONE canonical quantity for this child, rounded at the persist+ // boundary. On a FULL draw it is the lot's own on-hand: the entity+ // is flipped Consumed without its quantity being rewritten, so+ // booking the requested figure instead would leave the Consumption+ // ledger row disagreeing with the lot it just emptied.+ const entityQuantity = round(Number(trackedEntity.quantity));+ const fullDraw = isFullDraw(entityQuantity, child.quantity);+ const quantity = fullDraw ? entityQuantity : round(child.quantity);++ // Partial consume → split: the lineside entity keeps its id and+ // is decremented; a NEW child entity carries the consumed+ // quantity. EVERYTHING below (Consumed status, Consume input,+ // Consumption ledger) books against the child — flipping the+ // entity half without the ledger half would double-count on-hand.+ let consumedEntityId = trackedEntityId;+ if (!fullDraw) {+ const consumedChildId = nanoid();+ consumedEntityId = consumedChildId;++ const split = buildBatchSplitRecords({+ parent: {+ id: trackedEntity.id!,+ readableId: trackedEntity.readableId,+ quantity: entityQuantity,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId: trackedEntity.sourceDocumentReadableId,+ itemId: trackedEntity.itemId ?? trackedEntity.sourceDocumentId,+ expirationDate: trackedEntity.expirationDate ?? null,+ attributes: trackedEntity.attributes as Record<string, unknown> | null+ },+ drawQuantity: quantity,+ childId: consumedChildId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Job Material",+ activitySourceDocumentId: actualMaterialId!,+ bin: {+ storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),+ locationId: job?.locationId ?? null+ },+ itemLedgerItemId: trackedEntity.sourceDocumentId,+ companyId,+ userId,+ postingDate: companyToday.toString(),+ // Created Available; the shared status update below flips the+ // child to Consumed in the same transaction.+ childStatus: "Available",+ extraChildAttributes: {+ ...(jobOperationStepId+ ? { "Job Operation Step": jobOperationStepId }+ : {}),+ ...(unitNumber !== undefined ? { Unit: unitNumber } : {})+ }+ });++ // Track split entity for the MES confirmation: quantity = what+ // was consumed (the child), remainingQuantity = what the+ // surviving lineside entity still holds.+ splitEntities.push({+ originalId: trackedEntityId,+ newId: consumedChildId,+ readableId: trackedEntity.sourceDocumentReadableId ?? "",+ quantity,+ remainingQuantity: split.parentUpdate.quantity+ });++ await trx+ .insertInto("trackedActivity")+ .values(+ split.activityInsert as Insertable<KyselyDatabase["trackedActivity"]>+ )+ .execute();++ await trx+ .insertInto("trackedEntity")+ .values(+ split.childEntityInsert as Insertable<KyselyDatabase["trackedEntity"]>+ )+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert)+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values(split.activityOutputInsert)+ .execute();++ await trx+ .updateTable("trackedEntity")+ .set(split.parentUpdate)+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ // MTO skips ONLY the ledger inserts; entity/activity writes+ // above still happen.+ if (jobMaterial?.methodType !== "Make to Order") {+ itemLedgerInserts.push(...(split.ledgerInserts as ItemLedgerInsert[]));+ }+ }++ // Consume the drawn entity — the split child, or the whole+ // entity on a full draw.+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Consumed"+ })+ .where("id", "=", consumedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ trackedActivityInputs.push({+ trackedActivityId: activityId,+ trackedEntityId: consumedEntityId,+ quantity,+ companyId,+ createdBy: userId+ });++ if (jobMaterial?.methodType !== "Make to Order") {+ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Job Consumption",+ documentId: job?.id!,+ companyId,+ itemId: trackedEntity.sourceDocumentId,+ quantity: -quantity,+ locationId: job?.locationId,+ // The split child has no rows in the pre-transaction ledger+ // snapshot — it sits at the parent's resolved bin.+ storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),+ trackedEntityId: consumedEntityId,+ createdBy: userId+ });+ }+ }++ if (trackedActivityInputs.length > 0) {+ await trx+ .insertInto("trackedActivityInput")+ .values(trackedActivityInputs)+ .execute();+ }++ if (itemLedgerInserts.length > 0) {+ await trx.insertInto("itemLedger").values(itemLedgerInserts).execute();++ // Update pickMethod defaultStorageUnitId if needed for each inserted ledger+ for (const ledger of itemLedgerInserts) {+ await updatePickMethodDefaultStorageUnitIfNeeded(+ trx,+ ledger.itemId,+ ledger.locationId,+ ledger.storageUnitId,+ companyId,+ userId+ );+ }+ }++ if (itemLedgerInserts.length > 0) {+ const consumptionEntries = itemLedgerInserts+ .filter((l) => l.entryType === "Consumption")+ .map((l) => ({+ itemId: l.itemId as string,+ quantity: Number(l.quantity),+ trackedEntityId: l.trackedEntityId+ }));++ if (consumptionEntries.length > 0) {+ await createMaterialWipEntries(trx, {+ consumptionLedgers: consumptionEntries,+ jobId: job?.id!,+ operationId: jobMaterial?.jobOperationId ?? actualMaterialId!,+ description: "Tracked Entity Material Issue",+ wipAccount: accountDefaultsTracked.workInProgressAccount,+ rawMaterialsAccount: accountDefaultsTracked.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaultsTracked.finishedGoodsAccount,+ dimensionMap: dimensionMapTracked,++ jobLocationId: job?.locationId ?? null,+ db,+ companyId,+ userId,+ postingStatus+ });+ }+ }++ const totalChildQuantity = roundedChildTotal(children);++ // Only update if we didn't create a new jobMaterial (in which case it's already set)+ if (actualMaterialId === materialId) {+ const currentQuantityIssued = round(+ Number(jobMaterial?.quantityIssued) || 0+ );+ const newQuantityIssued = round(currentQuantityIssued + totalChildQuantity);++ await trx+ .updateTable("jobMaterial")+ .set({+ quantityIssued: newQuantityIssued+ })+ .where("id", "=", actualMaterialId!)+ .where("companyId", "=", companyId)+ .execute();++ logger.info("Job material quantity updated", {+ materialId: actualMaterialId,+ newQuantityIssued+ });+ }++ return { splitEntities, warning: expiredWarning };+ }++ // The Produce half of a batch-tracked operation completion — the activity ++ // entity flip EXTRACTED from jobOperationBatchComplete, so the batch-operations+ // Phase 2 (jobOperationBatchOutput) can finalize a member's output WITHOUT that+ // case's productionQuantity insert (batch Phase 1 already recorded it) and+ // WITHOUT its backflush (the batch's own issue step already ran).+ async function produceBatchOutput(+ trx: Transaction<KyselyDatabase>,+ {+ jobOperationId,+ trackedEntityId,+ producedQuantity,+ totalQuantity,+ companyId,+ userId+ }: {+ jobOperationId: string;+ trackedEntityId: string;+ producedQuantity: number;+ totalQuantity: number;+ companyId: string;+ userId: string;+ }+ ) {+ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ if (!trackedEntity) {+ throw new NotFoundError("Tracked entity not found");+ }++ if (trackedEntity.status !== "Consumed") {+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Produce",+ sourceDocument: "Job Operation",+ sourceDocumentId: jobOperationId,+ attributes: {+ "Job Operation": jobOperationId,+ Employee: userId,+ Quantity: producedQuantity+ },+ companyId,+ createdBy: userId+ })+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: trackedEntityId,+ quantity: producedQuantity,+ companyId,+ createdBy: userId+ })+ .execute();++ // Update the current trackedEntity to Complete+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ quantity: totalQuantity+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ export const issueMaterialPermission = {+ by: "type",+ rules: {+ convertEntity: { update: "inventory" },+ jobCompleteMakeToOrder: {},+ jobOperation: { update: "production" },+ jobOperationBatchComplete: { update: "production" },+ jobOperationBatchOutput: { update: "production" },+ jobOperationSerialComplete: { update: "production" },+ jobOperationScrap: { update: "production" },+ partToOperation: { update: "production" },+ scrapTrackedEntity: { update: "production" },+ mergeTrackedEntities: { update: "inventory" },+ trackedEntitiesToBatch: { update: "production" },+ trackedEntitiesToOperation: { update: "production" },+ unconsumeTrackedEntities: { update: "production" },+ maintenanceDispatchInventory: { update: "resources" },+ maintenanceDispatchTrackedEntities: { update: "resources" },+ maintenanceDispatchUnconsume: { update: "resources" },+ maintenanceDispatchUnissue: { update: "resources" }+ }+ } satisfies PermissionRule<z.output<typeof issueInput>>;++ /**+ * Issues material and records production against jobs, operations, tracked+ * entities and maintenance dispatches, per `type`.+ */+ export async function issueMaterial(+ ctx: ServiceContext,+ raw: z.input<typeof issueInput>+ ): Promise<IssueResult> {+ const input = issueInput.parse(raw);++ const db = ctx.asSystem.pg;+ const validatedPayload = {+ ...input,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ };++ logger.info(validatedPayload);++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ switch (validatedPayload.type) {+ case "jobOperation": {+ const { id, companyId, quantity, userId } = validatedPayload;++ const { accountDefaults, dimensionMap } =+ await loadConsumeAccountingContext(db, companyId);++ await db.transaction().execute(async (trx) => {+ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);+ await issueJobOperationMaterials(trx, {+ jobOperationId: id,+ quantity,+ companyId,+ userId,+ postingStatus,+ accountDefaults,+ dimensionMap,+ db+ });+ });++ break;+ }+ case "jobOperationBatchComplete": {+ const { trackedEntityId, companyId, userId, ...row } = validatedPayload;+ await assertProductionQuantityLinks(db, companyId, row);++ const [jobOperation, productionQuantities] = await inOrder([+ () => single(db, "jobOperation", { id: row.jobOperationId, companyId }),+ () =>+ many(db, "productionQuantity", {+ jobOperationId: row.jobOperationId,+ companyId,+ type: "Production"+ })+ ]);++ if (!jobOperation.data || !jobOperation.data.jobMakeMethodId) {+ throw new NotFoundError("Job operation not found");+ }++ const accountingBatch = await loadConsumeAccountingContext(db, companyId);++ await db.transaction().execute(async (trx) => {+ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);+ await trx+ .insertInto("productionQuantity")+ .values({+ ...row,+ type: "Production",+ companyId,+ createdBy: userId+ })+ .executeTakeFirst();++ const previousProductionQuantities =+ productionQuantities?.data?.reduce((acc, curr) => {+ const quantity = Number(curr.quantity);+ return acc + quantity;+ }, 0) ?? 0;++ await produceBatchOutput(trx, {+ jobOperationId: row.jobOperationId,+ trackedEntityId,+ producedQuantity: row.quantity,+ totalQuantity: previousProductionQuantities + row.quantity,+ companyId,+ userId+ });++ await issueJobOperationMaterials(trx, {+ jobOperationId: row.jobOperationId,+ quantity: row.quantity,+ companyId,+ userId,+ postingStatus,+ accountDefaults: accountingBatch.accountDefaults,+ dimensionMap: accountingBatch.dimensionMap,+ db+ });+ });++ return {+ success: true+ };+ }+ case "jobOperationBatchOutput": {+ const {+ jobOperationId,+ trackedEntityId,+ quantity,+ readableId,+ companyId,+ userId+ } = validatedPayload;++ const [entity, productionQuantities] = await inOrder([+ () =>+ single(+ db,+ "trackedEntity",+ { id: trackedEntityId, companyId },+ { columns: ["id", "status", "readableId"] }+ ),+ () =>+ many(+ db,+ "productionQuantity",+ { jobOperationId, companyId, type: "Production" },+ { columns: ["quantity"] }+ )+ ]);+ if (entity.error || !entity.data) {+ throw new NotFoundError("Tracked entity not found");+ }++ // Resume no-op: a prior attempt already produced this member's output.+ if (entity.data.status === "Available") {+ return { success: true, created: false };+ }++ // An Available lot must carry a number. Batch creation plans it (the+ // entity's readableId, or the merged lot passed as readableId); this is+ // the backstop for direct calls and for batches planned before that.+ if (!readableId && !entity.data.readableId) {+ throw new Error(+ `Operation ${jobOperationId} produces a batch-tracked item — its batch number is required`+ );+ }++ const totalQuantity =+ productionQuantities.data?.reduce(+ (acc: number, curr: { quantity: number | string | null }) =>+ acc + Number(curr.quantity),+ 0+ ) ?? 0;+ if (totalQuantity <= 0) {+ throw new Error(+ "No recorded production quantity for this operation — complete the batch first"+ );+ }++ await db.transaction().execute(async (trx) => {+ if (readableId) {+ await trx+ .updateTable("trackedEntity")+ .set({ readableId })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }+ await produceBatchOutput(trx, {+ jobOperationId,+ trackedEntityId,+ producedQuantity: quantity,+ totalQuantity,+ companyId,+ userId+ });+ });++ return { success: true, created: true };+ }+ case "jobOperationSerialComplete": {+ const { trackedEntityId, companyId, userId, ...row } = validatedPayload;+ await assertProductionQuantityLinks(db, companyId, row);++ const jobOperation = await single(db, "jobOperation", {+ id: row.jobOperationId,+ companyId+ });+ if (!jobOperation.data || !jobOperation.data.jobMakeMethodId) {+ throw new NotFoundError("Job operation not found");+ }++ // UNIT-AXIS order, identical to the apps' getTrackedEntitiesByMakeMethodId:+ // position here is the `index` step records are stored under, so the+ // tiebreakers are not optional — `createdAt` ties for bulk-minted serials+ // and Postgres breaks a tie by physical row order, which any UPDATE moves.+ const trackedEntities = await many(+ db,+ "trackedEntity",+ {+ attributes: contains({+ "Job Make Method": jobOperation.data.jobMakeMethodId+ }),+ companyId+ },+ { orderBy: ["createdAt", "readableId", "id"] }+ );++ if (!trackedEntities.data || trackedEntities.data.length === 0) {+ throw new NotFoundError("Tracked entities not found");+ }++ // The unit this completion is for, as the 0-based axis index its step+ // records are keyed by. Derived HERE rather than taken from the caller:+ // three routes post this payload and none of them should be trusted, or+ // required, to know the axis.+ const completedUnitIndex = trackedEntities.data.findIndex(+ (entity: { id: string }) => entity.id === trackedEntityId+ );++ const relatedTrackedEntities = trackedEntities.data.filter(+ (trackedEntity) =>+ `Operation ${row.jobOperationId}` in+ (trackedEntity.attributes as TrackedEntityAttributes)+ );++ const {+ accountDefaults: accountDefaultsSerial,+ dimensionMap: dimensionMapSerial+ } = await loadConsumeAccountingContext(db, companyId);++ let newEntityId: string | undefined;+ await db.transaction().execute(async (trx) => {+ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);+ await trx+ .insertInto("productionQuantity")+ .values({+ ...row,+ type: "Production",+ companyId,+ createdBy: userId+ })+ .executeTakeFirst();++ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ if (!trackedEntity) {+ throw new NotFoundError("Tracked entity not found");+ }++ if (trackedEntity.status !== "Consumed") {+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Complete",+ sourceDocument: "Job Operation",+ sourceDocumentId: row.jobOperationId,+ // `Job` is what the traceability sidebar loads step records by,+ // and `Unit` is what scopes them to THIS serial. Without `Job`+ // the sidebar showed none; without `Unit` it would show every+ // unit's values under one serial. Same two keys the production+ // event activity already writes (MES startProductionEvent).+ attributes: {+ Job: jobOperation.data.jobId,+ "Job Operation": row.jobOperationId,+ Employee: userId,+ ...(completedUnitIndex >= 0 ? { Unit: completedUnitIndex } : {})+ },+ companyId,+ createdBy: userId+ })+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: trackedEntityId,+ quantity: 1,+ companyId,+ createdBy: userId+ })+ .execute();+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ quantity: 1,+ attributes: {+ ...(trackedEntity.attributes as TrackedEntityAttributes),+ [`Operation ${row.jobOperationId}`]:+ relatedTrackedEntities.length + 1+ }+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }++ if (+ trackedEntities.data.length <+ (jobOperation.data.operationQuantity ?? 0)+ ) {+ // Number this lazily-spawned unit from the item's serial sequence, if+ // one is configured. This unit wasn't part of the initial pre-split at+ // job creation (e.g. the job quantity was increased afterwards, or the+ // sequence was configured later), so it would otherwise be created with+ // a null readableId. Resolve the job's location for the %{location}+ // token; the reservation runs in this transaction, atomic with the spawn.+ let spawnReadableId: string | null = null;+ if (trackedEntity.itemId) {+ let locationCode: string | null = null;+ let locationName: string | null = null;+ const jobIdForLocation = (+ trackedEntity.attributes as Record<string, unknown>+ ).Job;+ if (typeof jobIdForLocation === "string") {+ const jobRow = await single(+ trx,+ "job",+ { id: jobIdForLocation, companyId },+ { columns: ["locationId"] }+ );+ if (jobRow.data?.locationId) {+ const loc = await single(+ trx,+ "location",+ { id: jobRow.data.locationId, companyId },+ { columns: ["code", "name"] }+ );+ locationCode = loc.data?.code ?? null;+ locationName = loc.data?.name ?? null;+ }+ }+ const spawnSerials = await sequence.getNextSerialNumbers(trx, {+ itemId: trackedEntity.itemId,+ companyId,+ count: 1,+ locationCode,+ locationName+ });+ spawnReadableId = spawnSerials[0] ?? null;+ }++ // Create a new trackedEntity with the same attributes but status = Reserved+ const newTrackedEntityResult = await trx+ .insertInto("trackedEntity")+ .values({+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId: trackedEntity.sourceDocumentReadableId,+ quantity: 1,+ status: "Reserved",+ attributes: trackedEntity.attributes,+ itemId: trackedEntity.itemId ?? null,+ expirationDate: trackedEntity.expirationDate ?? null,+ readableId: spawnReadableId,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirst();++ newEntityId = newTrackedEntityResult?.id;+ }++ await issueJobOperationMaterials(trx, {+ jobOperationId: row.jobOperationId,+ quantity: row.quantity,+ companyId,+ userId,+ postingStatus,+ accountDefaults: accountDefaultsSerial,+ dimensionMap: dimensionMapSerial,+ db+ });+ });++ return {+ success: true,+ newTrackedEntityId: newEntityId+ };+ }+ case "jobOperationScrap": {+ const {+ jobOperationId,+ quantity,+ scrapReasonId,+ trackedEntityId: scrapEntityId,+ notes,+ laborProductionEventId,+ machineProductionEventId,+ setupProductionEventId,+ companyId,+ userId+ } = validatedPayload;+ // Lands on productionQuantity, the Scrap activity and the journal's+ // ScrapReason dimension — all this company's rows.+ await assertCompanyRecords(+ db,+ "scrapReason",+ [scrapReasonId],+ companyId,+ "Scrap reason"+ );+ await assertProductionQuantityLinks(db, companyId, {+ laborProductionEventId,+ machineProductionEventId,+ setupProductionEventId+ });++ const operationRes = await single(db, "jobOperation", {+ id: jobOperationId,+ companyId+ });+ const operation = operationRes.data;+ if (!operation || !operation.jobMakeMethodId) {+ throw new NotFoundError("Job operation not found");+ }++ const [makeMethodRes, jobRes, trackedEntitiesRes, companyRecordScrapOp] =+ await inOrder([+ () =>+ single(+ db,+ "jobMakeMethod",+ { id: operation.jobMakeMethodId, companyId },+ {+ columns: [+ "id",+ "itemId",+ "requiresSerialTracking",+ "requiresBatchTracking",+ "parentMaterialId"+ ]+ }+ ),+ () =>+ single(+ db,+ "job",+ { id: operation.jobId, companyId },+ { columns: ["id", "jobId", "locationId"] }+ ),+ () =>+ many(+ db,+ "trackedEntity",+ {+ attributes: contains({+ "Job Make Method": operation.jobMakeMethodId+ }),+ companyId+ },+ { columns: ["id"] }+ ),+ () =>+ single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ )+ ]);+ if (makeMethodRes.error || !makeMethodRes.data) {+ throw new NotFoundError("Job make method not found");+ }+ if (jobRes.error || !jobRes.data)+ throw new NotFoundError("Job not found");+ if (companyRecordScrapOp.error) {+ throw new Error("Failed to fetch company");+ }+ const makeMethod = makeMethodRes.data;+ const job = jobRes.data;+ const existingEntityCount = trackedEntitiesRes.data?.length ?? 0;++ const accountDefaultsScrapOp = await getDefaultPostingGroup(+ db,+ companyId+ );+ if (accountDefaultsScrapOp.error || !accountDefaultsScrapOp.data) {+ throw new Error("Error getting account defaults");+ }++ const dimensionsScrapOp = await many(+ db,+ "dimension",+ {+ companyGroupId: companyRecordScrapOp.data.companyGroupId!,+ active: true,+ entityType: [+ "ItemPostingGroup",+ "Item",+ "Location",+ "ScrapReason",+ "WorkCenter",+ "Employee"+ ]+ },+ { columns: ["id", "entityType"] }+ );+ const dimensionMapScrapOp = new Map<string, string>();+ if (dimensionsScrapOp.data) {+ for (const dim of dimensionsScrapOp.data) {+ if (dim.entityType) dimensionMapScrapOp.set(dim.entityType, dim.id);+ }+ }++ const isSerial = makeMethod.requiresSerialTracking === true;+ if (isSerial && !scrapEntityId) {+ throw new Error("trackedEntityId is required to scrap a serial unit");+ }+ if (isSerial && quantity !== 1) {+ throw new Error("Serial units are scrapped one at a time");+ }++ const todayScrapOp = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ let newEntityId: string | undefined;+ await db.transaction().execute(async (trx) => {+ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);++ // 1. Scrap quantity record. The quantity-sync interceptor aggregates+ // quantityScrapped; scrap no longer counts toward the auto-Done+ // target (20260807090629), so the operation stays open until the+ // good quantity is actually made.+ await trx+ .insertInto("productionQuantity")+ .values({+ jobOperationId,+ quantity,+ type: "Scrap",+ scrapReasonId,+ notes,+ laborProductionEventId,+ machineProductionEventId,+ setupProductionEventId,+ companyId,+ createdBy: userId+ })+ .executeTakeFirst();++ // 2. Backflush the scrapped units\' BOM for this operation — material+ // cost enters WIP exactly as a completion would (NetSuite "Issue+ // for Scrap"); the WIP→scrap journal below relieves it.+ const backflush = await issueJobOperationMaterials(trx, {+ jobOperationId,+ quantity,+ companyId,+ userId,+ postingStatus,+ accountDefaults: accountDefaultsScrapOp.data,+ dimensionMap: dimensionMapScrapOp,+ db+ });++ // 3. Serial: terminal status + Scrap genealogy on the selected unit.+ // The entity keeps its consumed-material input tree.+ let scrappedEntityAttributes: TrackedEntityAttributes | null = null;+ if (isSerial && scrapEntityId) {+ const entity = await trx+ .selectFrom("trackedEntity")+ .selectAll()+ .where("id", "=", scrapEntityId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!entity) throw new NotFoundError("Tracked entity not found");+ if (entity.status === "Consumed" || entity.status === "Scrapped") {+ throw new Error("Tracked entity is not in progress");+ }+ scrappedEntityAttributes =+ entity.attributes as TrackedEntityAttributes;++ const scrapActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: scrapActivityId,+ type: "Scrap",+ sourceDocument: "Job Operation",+ sourceDocumentId: jobOperationId,+ attributes: {+ "Job Operation": jobOperationId,+ "Scrap Reason": scrapReasonId,+ Employee: userId,+ ...(notes?.trim() ? { Notes: notes.trim() } : {})+ },+ companyId,+ createdBy: userId+ })+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: scrapActivityId,+ trackedEntityId: scrapEntityId,+ quantity: 1,+ companyId,+ createdBy: userId+ })+ .execute();+ // No `Operation ...` completion stamp — the unit did NOT complete+ // this operation; status is the terminal marker.+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Scrapped",+ attributes: {+ ...(entity.attributes as TrackedEntityAttributes),+ "Scrap Reason": scrapReasonId+ }+ })+ .where("id", "=", scrapEntityId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // 4. Reopen Done ops + capacity top-up beyond the planned allowance+ // so replacement units can run the FULL routing.+ await applyScrapReplacement(trx, {+ jobMakeMethodId: operation.jobMakeMethodId!,+ jobId: job.id,+ companyId,+ userId+ });++ // 5. Serial: spawn the replacement Reserved unit. Same convention as+ // jobOperationSerialComplete — spawn while total entities <+ // operationQuantity; the top-up above grew operationQuantity by+ // the beyond-allowance scrap, and pre-created allowance units+ // (job.scrapQuantity at release) already cover in-allowance scrap.+ if (isSerial && scrapEntityId && scrappedEntityAttributes) {+ const updatedOperation = await trx+ .selectFrom("jobOperation")+ .select(["operationQuantity"])+ .where("id", "=", jobOperationId)+ .executeTakeFirst();+ const capacity = Number(updatedOperation?.operationQuantity ?? 0);+ if (existingEntityCount < capacity) {+ let spawnReadableId: string | null = null;+ if (makeMethod.itemId) {+ let locationCode: string | null = null;+ let locationName: string | null = null;+ if (job.locationId) {+ const loc = await single(+ trx,+ "location",+ { id: job.locationId, companyId },+ { columns: ["code", "name"] }+ );+ locationCode = loc.data?.code ?? null;+ locationName = loc.data?.name ?? null;+ }+ const spawnSerials = await sequence.getNextSerialNumbers(trx, {+ itemId: makeMethod.itemId,+ companyId,+ count: 1,+ locationCode,+ locationName+ });+ spawnReadableId = spawnSerials[0] ?? null;+ }++ const scrappedEntity = await trx+ .selectFrom("trackedEntity")+ .selectAll()+ .where("id", "=", scrapEntityId)+ .executeTakeFirst();+ const newTrackedEntityResult = await trx+ .insertInto("trackedEntity")+ .values({+ sourceDocument: scrappedEntity?.sourceDocument ?? "Item",+ sourceDocumentId:+ scrappedEntity?.sourceDocumentId ?? makeMethod.itemId ?? "",+ sourceDocumentReadableId:+ scrappedEntity?.sourceDocumentReadableId,+ quantity: 1,+ status: "Reserved",+ attributes: scrappedEntityAttributes as unknown as Json,+ itemId: makeMethod.itemId ?? null,+ expirationDate: scrappedEntity?.expirationDate ?? null,+ readableId: spawnReadableId,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirst();+ newEntityId = newTrackedEntityResult?.id;+ }+ }++ // 6. GL: relieve the scrapped units\' accumulated material cost from+ // WIP into the scrap account. Valuation = this operation\'s actual+ // backflush cost + prior operations\' estimated material cost+ // (jobMaterial per-unit quantity × itemCost.unitCost). Labor and+ // overhead already absorbed stay in WIP and settle via close-job+ // variance (spec decision 6).+ let priorUnitMaterialCost = 0;+ const priorOperations = await trx+ .selectFrom("jobOperation")+ .select(["id"])+ .where("jobMakeMethodId", "=", operation.jobMakeMethodId!)+ .where("order", "<", operation.order)+ .execute();+ if (priorOperations.length > 0) {+ const priorMaterials = await trx+ .selectFrom("jobMaterial")+ .select(["itemId", "quantity"])+ .where(+ "jobOperationId",+ "in",+ priorOperations.map((op) => op.id)+ )+ .where("methodType", "!=", "Make to Order")+ .execute();+ if (priorMaterials.length > 0) {+ const priorCosts = await trx+ .selectFrom("itemCost")+ .select(["itemId", "unitCost"])+ .where(+ "itemId",+ "in",+ priorMaterials.map((m) => m.itemId)+ )+ .where("companyId", "=", companyId)+ .execute();+ const unitCostByItem = new Map(+ priorCosts.map((c) => [c.itemId, Number(c.unitCost) || 0])+ );+ for (const material of priorMaterials) {+ priorUnitMaterialCost +=+ (Number(material.quantity) || 0) *+ (unitCostByItem.get(material.itemId) ?? 0);+ }+ }+ }++ const scrapCost =+ backflush.totalMaterialCost + priorUnitMaterialCost * quantity;+ if (scrapCost > 0) {+ // A Provisional journal has no accounting period.+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, trx, todayScrapOp)+ : null;+ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );+ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `Scrap — Job ${job.jobId ?? job.id}`,+ postingDate: todayScrapOp,+ companyId,+ sourceType: "Job Consumption",+ status: postingStatus,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ // An empty scrapAccount falls back to the variance account.+ const scrapAccountId = resolveDefaultAccount(+ accountDefaultsScrapOp.data,+ "scrapAccount",+ postingStatus+ ).accountId;+ const journalLineReference = nanoid();+ const journalLineResults = await trx+ .insertInto("journalLine")+ .values([+ {+ journalId: journalResult.id,+ accountId: scrapAccountId,+ description: "Scrap Account",+ amount: debit("expense", scrapCost),+ quantity,+ documentType: "Scrap",+ documentId: job.id,+ documentLineReference: `jobOperationScrap:${jobOperationId}`,+ journalLineReference,+ companyId+ },+ {+ journalId: journalResult.id,+ accountId: accountDefaultsScrapOp.data.workInProgressAccount,+ description: "WIP Account",+ amount: credit("asset", scrapCost),+ quantity,+ documentType: "Scrap",+ documentId: job.id,+ documentLineReference: `jobOperationScrap:${jobOperationId}`,+ journalLineReference,+ companyId+ }+ ])+ .returning(["id"])+ .execute();++ const itemCostRow = makeMethod.itemId+ ? await trx+ .selectFrom("itemCost")+ .select(["itemPostingGroupId"])+ .where("itemId", "=", makeMethod.itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ : null;+ const scrapDimensionValues: Array<[string, string | null]> = [+ ["Item", makeMethod.itemId ?? null],+ ["ItemPostingGroup", itemCostRow?.itemPostingGroupId ?? null],+ ["Location", job.locationId ?? null],+ ["ScrapReason", scrapReasonId],+ ["WorkCenter", operation.workCenterId ?? null],+ ["Employee", userId]+ ];+ const dimensionInserts = journalLineResults.flatMap((line) =>+ scrapDimensionValues+ .filter(+ ([entityType, valueId]) =>+ dimensionMapScrapOp.has(entityType) && valueId+ )+ .map(([entityType, valueId]) => ({+ journalLineId: line.id,+ dimensionId: dimensionMapScrapOp.get(entityType)!,+ valueId: valueId as string,+ companyId+ }))+ );+ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }+ }+ });++ // Reschedule outside the transaction (trigger-rework precedent):+ // reopened/topped-up operations need fresh dates and priorities.+ // The scrap transaction already committed; a failed reschedule is logged, not raised.+ const rescheduled = await invokePosting(+ { db, companyId, userId },+ "reschedule",+ { jobId: job.id },+ rescheduleJob+ );+ if (rescheduled.error) {+ logger.error("Failed to trigger reschedule after scrap", {+ error: rescheduled.error+ });+ }++ return {+ success: true,+ newTrackedEntityId: newEntityId+ };+ }+ case "partToOperation": {+ const {+ id,+ companyId,+ userId,+ itemId,+ quantity,+ materialId,+ jobOperationStepId,+ adjustmentType+ } = validatedPayload;++ // Written into jobMaterialStep for an unplanned part (no companyId there).+ await assertCompanyRecords(+ db,+ "jobOperationStep",+ [jobOperationStepId],+ companyId,+ "Job operation step"+ );++ const { accountDefaults, dimensionMap } =+ await loadConsumeAccountingContext(db, companyId);++ await db.transaction().execute(async (trx) => {+ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);+ const jobOperation = await trx+ .selectFrom("jobOperation")+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .select(["jobId", "jobMakeMethodId"])+ .executeTakeFirst();+ if (!jobOperation) throw new NotFoundError("Job operation not found");++ const [job, item] = await Promise.all([+ trx+ .selectFrom("job")+ .where("id", "=", jobOperation?.jobId!)+ .select("locationId")+ .executeTakeFirst(),+ trx+ .selectFrom("item")+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .select([+ "id",+ "itemTrackingType",+ "name",+ "readableIdWithRevision",+ "type"+ ])+ .executeTakeFirst()+ ]);++ if (materialId) {+ const material = await trx+ .selectFrom("jobMaterial")+ .where("id", "=", materialId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();+ if (!material) throw new NotFoundError("Job material not found");++ let storageUnitId: string | null | undefined;+ // Prioritize material.storageUnitId if available+ if (material?.storageUnitId) {+ storageUnitId = material.storageUnitId;+ } else if (material?.defaultStorageUnit) {+ const pickMethod = await trx+ .selectFrom("pickMethod")+ .where("itemId", "=", itemId)+ .where("locationId", "=", job?.locationId!)+ .select("defaultStorageUnitId")+ .executeTakeFirst();+ storageUnitId = pickMethod?.defaultStorageUnitId;+ } else {+ storageUnitId = await getStorageUnitWithHighestQuantity(+ trx,+ itemId,+ job?.locationId!+ );+ }++ // Rounded once here: it drives the ledger rows, the budget+ // allocation and the quantityIssued write below.+ const quantityToIssue = round(+ adjustmentType === "Positive Adjmt."+ ? Number(quantity)+ : adjustmentType === "Negative Adjmt."+ ? Number(quantity)+ : round(Number(quantity)) -+ round(Number(material?.quantityIssued)) // set quantity+ );++ if (material && material.methodType !== "Make to Order") {+ let remaining = Number(quantityToIssue);+ if (adjustmentType !== "Positive Adjmt." && remaining > 0) {+ const budgets = orderOldFirst(+ await getPickedBudgets(trx, {+ material,+ locationId: job?.locationId!,+ companyId,+ opStorageUnitId: await getOperationLinesideBin(trx, {+ jobOperationId: material.jobOperationId,+ companyId+ })+ }),+ material.itemId+ );+ const allocation = allocateAcrossBudgets(+ remaining,+ budgets,+ Number(material.quantity ?? 0)+ );+ remaining = allocation.remaining;+ for (const take of allocation.takes) {+ if (!take.budget.isInventory) continue;+ for (const row of splitTakeByBin(take)) {+ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Job Consumption",+ documentId: material.jobId,+ documentLineId: id,+ companyId,+ itemId: take.budget.itemId,+ locationId: job?.locationId,+ storageUnitId: row.storageUnitId,+ quantity: -row.quantity,+ createdBy: userId+ });+ }+ }+ }+ if (item?.itemTrackingType === "Inventory" && remaining !== 0) {+ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Job Consumption",+ documentId: material.jobId,+ documentLineId: id,+ companyId,+ itemId: material.itemId,+ locationId: job?.locationId,+ storageUnitId,+ quantity:+ adjustmentType === "Positive Adjmt."+ ? Number(remaining)+ : -Number(remaining),+ createdBy: userId+ });+ }+ }++ await trx+ .updateTable("jobMaterial")+ .set({+ // A positive adjustment returns material to inventory, so it+ // reduces quantityIssued — otherwise the backflush cap sees+ // returned material as still issued.+ quantityIssued: round(+ round(Number(material?.quantityIssued) ?? 0) ++ (adjustmentType === "Positive Adjmt."+ ? -quantityToIssue+ : quantityToIssue)+ )+ })+ .where("id", "=", materialId)+ .where("companyId", "=", companyId)+ .execute();++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();++ // Update pickMethod defaultStorageUnitId if needed for each inserted ledger+ for (const ledger of itemLedgerInserts) {+ await updatePickMethodDefaultStorageUnitIfNeeded(+ trx,+ ledger.itemId,+ ledger.locationId,+ ledger.storageUnitId,+ companyId,+ userId+ );+ }+ }+ } else {+ let storageUnitId: string | null | undefined;+ if (item?.itemTrackingType === "Inventory") {+ const pickMethod = await trx+ .selectFrom("pickMethod")+ .where("itemId", "=", itemId)+ .where("locationId", "=", job?.locationId!)+ .select("defaultStorageUnitId")+ .executeTakeFirst();++ storageUnitId =+ pickMethod?.defaultStorageUnitId ??+ (await getStorageUnitWithHighestQuantity(+ trx,+ itemId,+ job?.locationId!+ ));++ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Job Consumption",+ documentId: jobOperation?.jobId,+ documentLineId: id,+ companyId,+ itemId: itemId!,+ quantity:+ adjustmentType === "Positive Adjmt."+ ? Number(quantity)+ : -Number(quantity),+ locationId: job?.locationId,+ storageUnitId,+ createdBy: userId+ });+ }++ const itemCost = await trx+ .selectFrom("itemCost")+ .where("itemId", "=", itemId!)+ .select("unitCost")+ .executeTakeFirst();++ const newJobMaterial = await trx+ .insertInto("jobMaterial")+ .values({+ companyId,+ createdBy: userId,+ description: item?.name ?? "",+ estimatedQuantity: 0,+ itemId: itemId!,+ itemType: item?.type ?? "Part",+ jobId: jobOperation?.jobId!,+ jobMakeMethodId: jobOperation?.jobMakeMethodId!,+ jobOperationId: id,+ storageUnitId: storageUnitId ?? undefined,+ methodType: "Pull from Inventory",+ quantity: 0,+ quantityIssued: round(Number(quantity ?? 0)),+ unitCost: itemCost?.unitCost ?? 0+ })+ .returning("id")+ .executeTakeFirst();++ // Scope this unplanned part to the step it was issued on (assembly+ // view), so it shows on that step rather than as a General material.+ if (jobOperationStepId && newJobMaterial?.id) {+ await trx+ .insertInto("jobMaterialStep")+ .values({+ jobMaterialId: newJobMaterial.id,+ jobOperationStepId+ })+ .onConflict((oc) => oc.doNothing())+ .execute();+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();++ // Update pickMethod defaultStorageUnitId if needed for each inserted ledger+ for (const ledger of itemLedgerInserts) {+ await updatePickMethodDefaultStorageUnitIfNeeded(+ trx,+ ledger.itemId,+ ledger.locationId,+ ledger.storageUnitId,+ companyId,+ userId+ );+ }+ }+ }++ if (itemLedgerInserts.length > 0) {+ const jobOperation = await trx+ .selectFrom("jobOperation")+ .where("id", "=", id)+ .select(["jobId"])+ .executeTakeFirst();++ const jobRecord = jobOperation?.jobId+ ? await trx+ .selectFrom("job")+ .where("id", "=", jobOperation.jobId)+ .select(["itemId", "locationId"])+ .executeTakeFirst()+ : null;++ await createMaterialWipEntries(trx, {+ consumptionLedgers: itemLedgerInserts.map((l) => ({+ itemId: l.itemId as string,+ quantity: Number(l.quantity),+ trackedEntityId: l.trackedEntityId+ })),+ jobId: jobOperation?.jobId!,+ operationId: id,+ description: "Manual Material Issue",+ wipAccount: accountDefaults.workInProgressAccount,+ rawMaterialsAccount: accountDefaults.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaults.finishedGoodsAccount,+ dimensionMap,++ jobLocationId: jobRecord?.locationId ?? null,+ db,+ companyId,+ userId,+ postingStatus+ });+ }+ });+ break;+ }+ case "scrapTrackedEntity": {+ const {+ trackedEntityId,+ materialId,+ parentTrackedEntityId,+ scrapReasonId,+ makeReplacement,+ companyId,+ userId+ } = validatedPayload;+ // The parent lands in trackedActivityOutput and the reason on the ledger,+ // the activity and the journal dimension — both must be this company's.+ await assertCompanyRecords(+ db,+ "trackedEntity",+ [parentTrackedEntityId],+ companyId,+ "Parent tracked entity"+ );+ await assertCompanyRecords(+ db,+ "scrapReason",+ [scrapReasonId],+ companyId,+ "Scrap reason"+ );++ const [trackedEntity, jobMaterial] = await inOrder([+ () => single(db, "trackedEntity", { id: trackedEntityId, companyId }),+ () => single(db, "jobMaterial", { id: materialId, companyId })+ ]);++ if (!trackedEntity.data) {+ throw new NotFoundError("Tracked entity not found");+ }++ if (!jobMaterial.data) {+ throw new NotFoundError("Job material not found");+ }+ if (trackedEntity.data.status === "Scrapped") {+ throw new Error("Tracked entity has already been scrapped");+ }++ const companyRecordScrap = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );+ if (companyRecordScrap.error) throw new Error("Failed to fetch company");+ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatusScrap = await journalPostingStatus(db, companyId);++ const accountDefaultsScrap = await getDefaultPostingGroup(db, companyId);+ if (accountDefaultsScrap.error || !accountDefaultsScrap.data) {+ throw new Error("Error getting account defaults");+ }++ const dimensionsScrap = await many(+ db,+ "dimension",+ {+ companyGroupId: companyRecordScrap.data.companyGroupId!,+ active: true,+ entityType: [+ "ItemPostingGroup",+ "Item",+ "Location",+ "ScrapReason",+ "WorkCenter",+ "Employee"+ ]+ },+ { columns: ["id", "entityType"] }+ );++ const dimensionMapScrap = new Map<string, string>();+ if (dimensionsScrap.data) {+ for (const dim of dimensionsScrap.data) {+ if (dim.entityType) dimensionMapScrap.set(dim.entityType, dim.id);+ }+ }++ const todayScrap = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();+ // Resolve the period BEFORE the transaction parks the (size 1) pool.+ // A Provisional journal has no accounting period.+ const accountingPeriodIdScrap =+ postingStatusScrap === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, todayScrap)+ : null;+ // An empty scrapAccount falls back to the variance account.+ const scrapAccountIdScrap = resolveDefaultAccount(+ accountDefaultsScrap.data,+ "scrapAccount",+ postingStatusScrap+ ).accountId;++ let didReplace = false;+ await db.transaction().execute(async (trx) => {+ // Re-read inside the transaction: its FOR SHARE lock holds the+ // status until commit, and the period above was resolved for it.+ await assertPostingStatusUnchanged(trx, companyId, postingStatusScrap);+ const entity = trackedEntity.data!;+ const material = jobMaterial.data!;+ const quantity = Number(entity.quantity);++ const job = await trx+ .selectFrom("job")+ .select(["id", "jobId", "locationId", "itemId"])+ .where("id", "=", material.jobId!)+ .executeTakeFirst();++ const item = await trx+ .selectFrom("item")+ .where("id", "=", material.itemId!)+ .select(["readableIdWithRevision"])+ .executeTakeFirst();++ // Scrap genealogy (was: Consume + attributes.Scrapped). The entity+ // keeps its full input tree; status is the terminal marker.+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Scrap",+ sourceDocument: "Job Material",+ sourceDocumentId: materialId,+ sourceDocumentReadableId: item?.readableIdWithRevision ?? "",+ attributes: {+ Job: job?.id!,+ "Job Make Method": material.jobMakeMethodId!,+ "Job Material": material.id!,+ "Scrap Reason": scrapReasonId,+ Employee: userId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId,+ quantity,+ companyId,+ createdBy: userId+ })+ .execute();++ if (parentTrackedEntityId) {+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: parentTrackedEntityId,+ quantity,+ companyId,+ createdBy: userId+ })+ .execute();+ }++ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Scrapped"+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ const consumedItemId = entity.sourceDocumentId ?? material.itemId!;+ const [itemRow, itemCostRow] = await Promise.all([+ trx+ .selectFrom("item")+ .select(["itemTrackingType", "replenishmentSystem"])+ .where("id", "=", consumedItemId)+ .executeTakeFirst(),+ trx+ .selectFrom("itemCost")+ .select([+ "costingMethod",+ "unitCost",+ "standardCost",+ "itemPostingGroupId"+ ])+ .where("itemId", "=", consumedItemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ ]);+ // A missing itemCost must not fail the scrap — fall back to zero+ // cost (no journal value) so the physical/traceability scrap still+ // records; accounting can be reconciled later.+ const resolvedItemCost = {+ costingMethod: itemCostRow?.costingMethod ?? "Average",+ unitCost: Number(itemCostRow?.unitCost ?? 0),+ standardCost: Number(itemCostRow?.standardCost ?? 0),+ itemPostingGroupId: itemCostRow?.itemPostingGroupId ?? null+ };++ // Entity STATE drives the accounting side, not methodType:+ // - Available (picked / in stock) → scrap FROM STOCK (Cr inventory)+ // - Consumed (already issued into the parent) → relieve WIP (Cr WIP)+ const isConsumed = entity.status === "Consumed";++ const scrapWorkCenterId = material.jobOperationId+ ? ((+ await trx+ .selectFrom("jobOperation")+ .select(["workCenterId"])+ .where("id", "=", material.jobOperationId)+ .executeTakeFirst()+ )?.workCenterId ?? null)+ : null;+ const scrapExtraDimensions = [+ { entityType: "ScrapReason", valueId: scrapReasonId },+ ...(scrapWorkCenterId+ ? [{ entityType: "WorkCenter", valueId: scrapWorkCenterId }]+ : []),+ { entityType: "Employee", valueId: userId }+ ];++ if (!isConsumed) {+ // AVAILABLE → scrap from stock (Dr scrapAccount / Cr inventory via+ // the shared adjustment core) at the entity's actual on-hand bin.+ // quantityIssued is untouched — it was never consumed.+ const ledgerRows = await trx+ .selectFrom("itemLedger")+ .select(["trackedEntityId", "storageUnitId", "quantity"])+ .where("trackedEntityId", "=", trackedEntityId)+ .execute();+ const bin = resolveTrackedEntityBin(ledgerRows, trackedEntityId);++ await bookAdjustment(trx, {+ ledger: {+ postingDate: todayScrap,+ itemId: consumedItemId,+ quantity: -Math.abs(quantity),+ locationId: job?.locationId ?? null,+ storageUnitId: bin,+ trackedEntityId,+ entryType: "Negative Adjmt.",+ documentType: "Scrap",+ documentId: job?.id ?? null,+ scrapReasonId,+ companyId,+ createdBy: userId+ },+ item: {+ itemTrackingType: itemRow?.itemTrackingType ?? null,+ replenishmentSystem: itemRow?.replenishmentSystem ?? null,+ itemPostingGroupId: resolvedItemCost.itemPostingGroupId+ },+ itemCost: {+ costingMethod: resolvedItemCost.costingMethod,+ unitCost: resolvedItemCost.unitCost,+ standardCost: resolvedItemCost.standardCost+ },+ accounting: {+ postingStatus: postingStatusScrap,+ accountingPeriodId: accountingPeriodIdScrap,+ accountDefaults: {+ rawMaterialsAccount:+ accountDefaultsScrap.data.rawMaterialsAccount,+ finishedGoodsAccount:+ accountDefaultsScrap.data.finishedGoodsAccount,+ inventoryAdjustmentVarianceAccount:+ accountDefaultsScrap.data.inventoryAdjustmentVarianceAccount+ },+ offsetAccount: scrapAccountIdScrap,+ offsetDescription: "Scrap Account",+ description: `Scrap — ${item?.readableIdWithRevision ?? ""}`,+ userId,+ dimensions: Object.fromEntries(dimensionMapScrap),+ extraDimensions: scrapExtraDimensions+ }+ });+ } else {+ // CONSUMED → the material cost was moved into WIP at consumption.+ // Relieve it to scrap (Dr scrapAccount / Cr WIP at the item's unit+ // cost — materials-only, spec decision 6) and reopen the material+ // requirement so a replacement can be issued.+ const scrapCost = resolvedItemCost.unitCost * quantity;+ if (scrapCost > 0) {+ const journalEntryId = await sequence.getNextSequence(+ trx,+ "journalEntry",+ companyId+ );+ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId: accountingPeriodIdScrap,+ description: `Scrap — ${item?.readableIdWithRevision ?? ""}`,+ postingDate: todayScrap,+ companyId,+ sourceType: "Job Consumption",+ status: postingStatusScrap,+ postedAt: datetime.timestamp(),+ postedBy: userId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const journalLineReference = nanoid();+ const journalLineResults = await trx+ .insertInto("journalLine")+ .values([+ {+ journalId: journalResult.id,+ accountId: scrapAccountIdScrap,+ description: "Scrap Account",+ amount: debit("expense", scrapCost),+ quantity,+ documentType: "Scrap",+ documentId: job?.id ?? null,+ documentLineReference: `scrapTrackedEntity:${materialId}`,+ journalLineReference,+ companyId+ },+ {+ journalId: journalResult.id,+ accountId: accountDefaultsScrap.data.workInProgressAccount,+ description: "WIP Account",+ amount: credit("asset", scrapCost),+ quantity,+ documentType: "Scrap",+ documentId: job?.id ?? null,+ documentLineReference: `scrapTrackedEntity:${materialId}`,+ journalLineReference,+ companyId+ }+ ])+ .returning(["id"])+ .execute();++ const scrapDimensionValues: Array<[string, string | null]> = [+ ["Item", consumedItemId],+ ["ItemPostingGroup", resolvedItemCost.itemPostingGroupId],+ ["Location", job?.locationId ?? null],+ ["ScrapReason", scrapReasonId],+ ["WorkCenter", scrapWorkCenterId],+ ["Employee", userId]+ ];+ const dimensionInserts = journalLineResults.flatMap((line) =>+ scrapDimensionValues+ .filter(+ ([entityType, valueId]) =>+ dimensionMapScrap.has(entityType) && valueId+ )+ .map(([entityType, valueId]) => ({+ journalLineId: line.id,+ dimensionId: dimensionMapScrap.get(entityType)!,+ valueId: valueId as string,+ companyId+ }))+ );+ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }+ }++ // Reopen the requirement — the consumed part is gone, so the+ // assembly needs a replacement issued.+ const currentQuantityIssued = round(+ Number(material.quantityIssued) || 0+ );+ await trx+ .updateTable("jobMaterial")+ .set({+ quantityIssued: Math.max(+ 0,+ round(currentQuantityIssued - round(quantity))+ )+ })+ .where("id", "=", materialId)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Replacement flow ("made 3, scrapped 1 → make 1 more"): only a+ // Make-to-Order subassembly can be re-made in place. Reopen its+ // routing, spawn the replacement serial, and record a rework row.+ if (makeReplacement && job) {+ const subMakeMethod = await trx+ .selectFrom("jobMakeMethod")+ .select(["id", "itemId", "requiresSerialTracking"])+ .where("parentMaterialId", "=", material.id!)+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ if (subMakeMethod) {+ didReplace = true;+ await applyScrapReplacement(trx, {+ jobMakeMethodId: subMakeMethod.id,+ jobId: job.id,+ companyId,+ userId+ });++ if (subMakeMethod.requiresSerialTracking && subMakeMethod.itemId) {+ let locationCode: string | null = null;+ let locationName: string | null = null;+ if (job.locationId) {+ const loc = await single(+ trx,+ "location",+ { id: job.locationId, companyId },+ { columns: ["code", "name"] }+ );+ locationCode = loc.data?.code ?? null;+ locationName = loc.data?.name ?? null;+ }+ const spawnSerials = await sequence.getNextSerialNumbers(trx, {+ itemId: subMakeMethod.itemId,+ companyId,+ count: 1,+ locationCode,+ locationName+ });+ await trx+ .insertInto("trackedEntity")+ .values({+ sourceDocument: entity.sourceDocument,+ sourceDocumentId: entity.sourceDocumentId,+ sourceDocumentReadableId: entity.sourceDocumentReadableId,+ quantity: 1,+ status: "Reserved",+ attributes: entity.attributes,+ itemId: subMakeMethod.itemId,+ expirationDate: entity.expirationDate ?? null,+ readableId: spawnSerials[0] ?? null,+ companyId,+ createdBy: userId+ })+ .execute();+ }++ const firstSubOperation = await trx+ .selectFrom("jobOperation")+ .select(["id"])+ .where("jobMakeMethodId", "=", subMakeMethod.id)+ .orderBy("order", "asc")+ .executeTakeFirst();+ const scrapReason = await trx+ .selectFrom("scrapReason")+ .select(["name"])+ .where("id", "=", scrapReasonId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (firstSubOperation && material.jobOperationId) {+ await trx+ .insertInto("rework")+ .values({+ jobId: job.id,+ triggeredAtJobOperationId: material.jobOperationId,+ targetJobOperationId: firstSubOperation.id,+ reason: scrapReason?.name ?? "Scrap",+ quantity,+ requestedById: userId,+ companyId+ })+ .execute();+ }+ }+ }+ });++ // Reschedule outside the transaction when the routing was reopened.+ if (didReplace) {+ // The scrap transaction already committed; a failed reschedule is logged, not raised.+ const rescheduled = await invokePosting(+ { db, companyId, userId },+ "reschedule",+ { jobId: jobMaterial.data.jobId },+ rescheduleJob+ );+ if (rescheduled.error) {+ logger.error("Failed to trigger reschedule after scrap", {+ error: rescheduled.error+ });+ }+ }++ return {+ success: true+ };+ }+ case "trackedEntitiesToOperation": {+ const {+ materialId,+ jobOperationId,+ itemId,+ parentTrackedEntityId,+ children,+ jobOperationStepId,+ unitNumber,+ overrideExpired,+ overrideReason,+ companyId,+ userId+ } = validatedPayload;++ if (!parentTrackedEntityId) {+ throw new Error("Parent ID is required");+ }++ if (children.length === 0) {+ throw new Error("Children are required");+ }++ // Either materialId or (jobOperationId + itemId) must be provided+ if (!materialId && (!jobOperationId || !itemId)) {+ throw new Error(+ "Either materialId or both jobOperationId and itemId must be provided"+ );+ }++ // Stamped on the Consume activity and written into jobMaterialStep.+ await assertCompanyRecords(+ db,+ "jobOperationStep",+ [jobOperationStepId],+ companyId,+ "Job operation step"+ );+ const companyToday = datetime.today(+ await getCompanyTimeZone(db, companyId)+ );+ const accounting = await loadConsumeAccountingContext(db, companyId);++ const result = await db.transaction().execute(async (trx) =>+ consumeTrackedEntitiesIntoOperation(trx, {+ db,+ materialId,+ jobOperationId,+ itemId,+ parentTrackedEntityId,+ children,+ jobOperationStepId,+ unitNumber,+ overrideExpired,+ overrideReason,+ companyId,+ userId,+ companyToday,+ // Provisional before the company's accounting cutover, Posted after it.+ postingStatus: await journalPostingStatus(trx, companyId),+ ...accounting+ })+ );++ return {+ success: true,+ splitEntities: result.splitEntities,+ warning: result.warning+ };+ }+ case "trackedEntitiesToBatch": {+ const {+ batchId,+ itemId,+ children,+ overrideExpired,+ overrideReason,+ companyId,+ userId+ } = validatedPayload;++ if (children.length === 0) {+ throw new Error("Children are required");+ }++ const companyToday = datetime.today(+ await getCompanyTimeZone(db, companyId)+ );+ const accounting = await loadConsumeAccountingContext(db, companyId);++ // Resolve (and lazily create) the accounting period BEFORE the member+ // transaction opens. getCurrentAccountingPeriod reads over HTTP but+ // writes in-transaction, so two members inside ONE transaction would+ // each try to create a missing period — the second cannot see the+ // first's uncommitted insert and the unique index rolls the whole pick+ // back. Committed here, every member's read finds it. A Provisional+ // journal has no accounting period, so none is created before the+ // company's accounting cutover.+ const postingStatus = await journalPostingStatus(db, companyId);+ if (postingStatus === "Posted") {+ await getCurrentAccountingPeriod(+ companyId,+ db,+ companyToday.toString()+ );+ }++ const batchResult = await db.transaction().execute(async (trx) => {+ // Re-read inside the transaction: its FOR SHARE lock holds the+ // status until commit, and the period above was resolved for it.+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);+ const batch = await trx+ .selectFrom("jobOperationBatch")+ .select(["id", "status"])+ .where("id", "=", batchId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!batch) {+ throw new NotFoundError("Batch not found");+ }+ if (batch.status === "Completed") {+ throw new Error("Batch is already completed");+ }++ const members = await trx+ .selectFrom("jobOperation")+ .select(["id", "jobId", "jobMakeMethodId"])+ .where("jobOperationBatchId", "=", batchId)+ .where("companyId", "=", companyId)+ .execute();+ if (members.length === 0) {+ throw new Error("Batch has no member operations");+ }+ const memberIds = members.map((m) => m.id);+ const memberIdSet = new Set(memberIds);+ // A member's materials are what its operation view lists: the+ // operation's make method BOM. A row linked straight to a member+ // operation stays with it; the rest belong to the member on its make+ // method (BOMs are usually not assigned per operation, and jobs built+ // from an item never carry the link).+ const memberByMakeMethod = new Map(+ members+ .filter((m) => m.jobMakeMethodId)+ .map((m) => [m.jobMakeMethodId as string, m.id])+ );++ // Lock the member material rows so a concurrent batch pick (or a+ // member-level manual issue) cannot double-allocate the remaining+ // requirement.+ const materialRows = await trx+ .selectFrom("jobMaterial")+ .select([+ "id",+ "jobOperationId",+ "jobMakeMethodId",+ "estimatedQuantity",+ "quantityIssued"+ ])+ .where("companyId", "=", companyId)+ .where("itemId", "=", itemId)+ .where((eb) =>+ eb.or([+ eb("jobOperationId", "in", memberIds),+ ...(memberByMakeMethod.size+ ? [eb("jobMakeMethodId", "in", [...memberByMakeMethod.keys()])]+ : [])+ ])+ )+ .forUpdate()+ .execute();++ const rowByOp = new Map<string, string>();+ const remainingByOp = new Map<string, number>();+ for (const row of materialRows) {+ const opId =+ row.jobOperationId && memberIdSet.has(row.jobOperationId)+ ? row.jobOperationId+ : memberByMakeMethod.get(row.jobMakeMethodId as string);+ if (!opId) continue;+ const remaining = Math.max(+ 0,+ Number(row.estimatedQuantity ?? 0) - Number(row.quantityIssued ?? 0)+ );+ remainingByOp.set(opId, (remainingByOp.get(opId) ?? 0) + remaining);+ // The write target: an OPEN row for this member/item when one+ // exists, else any row (which one is arbitrary either way).+ if (!rowByOp.has(opId) || remaining > 0) {+ rowByOp.set(opId, row.id as string);+ }+ }++ // Per picked lot, split pro-rata by each member's CURRENT remaining —+ // every member links to every lot it physically drew from, and a+ // multi-lot pick converges on exact per-member BOM totals.+ const drawsByOp = new Map<+ string,+ { trackedEntityId: string; quantity: number }[]+ >();+ for (const child of children) {+ const open = members+ .map((m) => ({+ jobOperationId: m.id,+ remaining: remainingByOp.get(m.id) ?? 0+ }))+ .filter((m) => m.remaining > 0);+ const shares = splitPickAcrossMembers(open, Number(child.quantity));+ for (const share of shares) {+ if (share.quantity <= 0) continue;+ remainingByOp.set(+ share.jobOperationId,+ (remainingByOp.get(share.jobOperationId) ?? 0) - share.quantity+ );+ const draws = drawsByOp.get(share.jobOperationId) ?? [];+ draws.push({+ trackedEntityId: child.trackedEntityId,+ quantity: share.quantity+ });+ drawsByOp.set(share.jobOperationId, draws);+ }+ }++ const splitEntities: Array<{+ originalId: string;+ newId: string;+ readableId: string;+ quantity: number;+ remainingQuantity: number;+ }> = [];+ let warning: string | undefined;++ for (const member of members) {+ const draws = drawsByOp.get(member.id);+ if (!draws || draws.length === 0) continue;+ if (!member.jobMakeMethodId) {+ throw new Error(`Job operation ${member.id} has no make method`);+ }+ // The member's WIP entity — what its consumption books into (the+ // same entity the single-operation page passes as the parent).+ const parent = await trx+ .selectFrom("trackedEntity")+ .select(["id"])+ .where(+ sql`"attributes"->>'Job Make Method'`,+ "=",+ member.jobMakeMethodId+ )+ .where("companyId", "=", companyId)+ // Scrap and split children inherit the attribute, so an earlier+ // run's dead entity can be the oldest match — it must not absorb+ // this member's consumption.+ .where("status", "not in", ["Consumed", "Scrapped", "Rejected"])+ // Deterministic among tied `createdAt` (bulk-minted serials).+ .orderBy("createdAt", "asc")+ .orderBy("readableId", "asc")+ .orderBy("id", "asc")+ .executeTakeFirst();+ if (!parent) {+ throw new Error(+ `No tracked entity found for job operation ${member.id} — release the member job before picking to the batch`+ );+ }++ const memberResult = await consumeTrackedEntitiesIntoOperation(trx, {+ db,+ materialId: rowByOp.get(member.id),+ jobOperationId: member.id,+ itemId,+ parentTrackedEntityId: parent.id as string,+ children: draws,+ overrideExpired,+ overrideReason,+ companyId,+ userId,+ companyToday,+ postingStatus,+ ...accounting+ });+ splitEntities.push(...memberResult.splitEntities);+ warning = warning ?? memberResult.warning;+ }++ return { splitEntities, warning };+ });++ return {+ success: true,+ ...batchResult+ };+ }+ case "mergeTrackedEntities": {+ const { trackedEntityIds, readableId, companyId, userId } =+ validatedPayload;++ const companyToday = datetime.today(+ await getCompanyTimeZone(db, companyId)+ );++ const mergeResult = await db.transaction().execute(async (trx) => {+ const parents = await trx+ .selectFrom("trackedEntity")+ .selectAll()+ .where("id", "in", trackedEntityIds)+ .where("companyId", "=", companyId)+ .forUpdate()+ .execute();++ if (parents.length !== trackedEntityIds.length) {+ throw new NotFoundError("Tracked entities not found");+ }++ // Order by the caller's list, not the DB's row order: the builder+ // reads the FIRST parent for the merged lot's number, bin, and+ // attribute base, so an unordered read makes those non-deterministic.+ const parentById = new Map(parents.map((p) => [p.id, p]));+ const orderedParents = trackedEntityIds.map((id) => {+ const row = parentById.get(id);+ if (!row) throw new NotFoundError("Tracked entities not found");+ return row;+ });++ const parentLedgers = await trx+ .selectFrom("itemLedger")+ .select([+ "trackedEntityId",+ "storageUnitId",+ "locationId",+ "quantity",+ "createdAt"+ ])+ .where("trackedEntityId", "in", trackedEntityIds)+ .where("companyId", "=", companyId)+ .orderBy("createdAt", "desc")+ .execute();++ // The parent's on-ledger balance: what its job receipt has put into+ // stock so far. The merge only moves this — unreceived quantity+ // reaches inventory later, through the member job's own receipt.+ const receivedOf = (entityId: string) =>+ (parentLedgers as any[])+ .filter((l) => l.trackedEntityId === entityId)+ .reduce((acc, l) => acc + Number(l.quantity), 0);++ const locationOf = (entityId: string) =>+ (parentLedgers as any[]).find(+ (l) => l.trackedEntityId === entityId && l.locationId+ )?.locationId ?? null;++ const mergedId = nanoid();+ const mergeActivityId = nanoid();++ const records = buildBatchMergeRecords({+ parents: orderedParents.map((p) => ({+ id: p.id,+ readableId: p.readableId,+ quantity: Number(p.quantity),+ receivedQuantity: receivedOf(p.id),+ status: p.status as string,+ sourceDocument: p.sourceDocument,+ sourceDocumentId: p.sourceDocumentId,+ sourceDocumentReadableId: p.sourceDocumentReadableId,+ itemId: p.itemId ?? null,+ expirationDate: (p.expirationDate as string | null) ?? null,+ attributes: p.attributes as Record<string, unknown> | null,+ bin: {+ storageUnitId: resolveTrackedEntityBin(+ parentLedgers as any[],+ p.id+ ),+ locationId: locationOf(p.id)+ }+ })),+ mergedId,+ mergeActivityId,+ readableId: readableId ?? null,+ activitySourceDocument: "Tracked Entity",+ activitySourceDocumentId: mergedId,+ companyId,+ userId,+ postingDate: companyToday.toString()+ });++ await trx+ .insertInto("trackedEntity")+ .values({+ ...records.mergedEntityInsert,+ // TEXT NOT NULL columns; the builder sources them from the first+ // parent, which the schema guarantees is non-null.+ sourceDocument: records.mergedEntityInsert.sourceDocument as string,+ sourceDocumentId: records.mergedEntityInsert+ .sourceDocumentId as string,+ attributes: records.mergedEntityInsert.attributes as Json+ })+ .execute();++ await trx+ .insertInto("trackedActivity")+ .values({+ ...records.activityInsert,+ attributes: records.activityInsert.attributes as Json+ })+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values(records.activityInputInserts)+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values(records.activityOutputInsert)+ .execute();++ await trx+ .insertInto("itemLedger")+ .values(+ records.ledgerInserts.map((l) => ({+ ...l,+ itemId: l.itemId as string+ }))+ )+ .execute();++ for (const update of records.parentUpdates) {+ await trx+ .updateTable("trackedEntity")+ .set({ status: update.status })+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ return {+ trackedEntityId: mergedId,+ readableId: records.mergedEntityInsert.readableId,+ quantity: records.mergedEntityInsert.quantity+ };+ });++ return {+ success: true,+ ...mergeResult+ };+ }+ case "unconsumeTrackedEntities": {+ const { materialId, parentTrackedEntityId, children, companyId, userId } =+ validatedPayload;++ if (!parentTrackedEntityId) {+ throw new Error("Parent ID is required");+ }++ if (children.length === 0) {+ throw new Error("Children are required");+ }++ const {+ accountDefaults: accountDefaultsUnconsume,+ dimensionMap: dimensionMapUnconsume+ } = await loadConsumeAccountingContext(db, companyId);++ await db.transaction().execute(async (trx) => {+ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);+ const trackedEntities = await trx+ .selectFrom("trackedEntity")+ .where(+ "id",+ "in",+ children.map((child) => child.trackedEntityId)+ )+ .where("companyId", "=", companyId)+ .selectAll()+ .execute();++ const itemLedgers = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "in", [+ ...children.map((child) => child.trackedEntityId)+ ])+ .orderBy("createdBy", "desc")+ .selectAll()+ .execute();++ if (trackedEntities.length !== children.length) {+ throw new NotFoundError("Tracked entities not found");+ }++ if (trackedEntities.some((entity) => entity.status !== "Consumed")) {+ throw new Error(+ "Tracked entities must be in Consumed status to unconsume"+ );+ }++ const jobMaterial = await trx+ .selectFrom("jobMaterial")+ .where("id", "=", materialId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();+ if (!jobMaterial) throw new NotFoundError("Job material not found");++ // Get item details+ const item = await trx+ .selectFrom("item")+ .where("id", "=", jobMaterial?.itemId!)+ .select(["readableIdWithRevision"])+ .executeTakeFirst();++ // Get job location+ const job = await trx+ .selectFrom("job")+ .select(["id", "locationId"])+ .where("id", "=", jobMaterial?.jobId!)+ .executeTakeFirst();++ // Get parent tracked entity details+ const parentTrackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", parentTrackedEntityId)+ .where("companyId", "=", companyId)+ .select([+ "id",+ "sourceDocumentId",+ "quantity",+ "attributes",+ "status"+ ])+ .executeTakeFirst();++ if (!parentTrackedEntity) {+ throw new NotFoundError("Parent tracked entity not found");+ }++ // Create tracked activity for unconsume+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Unconsume",+ sourceDocument: "Job Material",+ sourceDocumentId: materialId,+ sourceDocumentReadableId: item?.readableIdWithRevision ?? "",+ attributes: {+ Job: job?.id!,+ "Job Make Method": jobMaterial?.jobMakeMethodId!,+ "Job Material": jobMaterial?.id!,+ Employee: userId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: activityId,+ trackedEntityId: parentTrackedEntityId,+ quantity: parentTrackedEntity.quantity,+ companyId,+ createdBy: userId+ })+ .execute();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const trackedActivityOutputs: Database["public"]["Tables"]["trackedActivityOutput"]["Insert"][] =+ [];++ // Process each child tracked entity+ for (const child of children) {+ const trackedEntity = trackedEntities.find(+ (entity) => entity.id === child.trackedEntityId+ );+ if (!trackedEntity) {+ throw new NotFoundError("Tracked entity not found");+ }+ const { trackedEntityId, quantity } = child;+ // Update tracked entity status back to Available+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available"+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ trackedActivityOutputs.push({+ trackedActivityId: activityId,+ trackedEntityId,+ quantity,+ companyId,+ createdBy: userId+ });++ if (jobMaterial?.methodType !== "Make to Order") {+ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Job Consumption",+ documentId: job?.id!,+ companyId,+ itemId: trackedEntity.sourceDocumentId,+ quantity: quantity,+ locationId: job?.locationId,+ // NOTE: unconsume path left on its original bin-selection until+ // it can be verified; the resolveTrackedEntityBin fix is scoped+ // to the consumption path (trackedEntitiesToOperation).+ storageUnitId: itemLedgers.find(+ (itemLedger) => itemLedger.trackedEntityId === trackedEntityId+ )?.storageUnitId,+ trackedEntityId,+ createdBy: userId+ });+ }+ }++ if (trackedActivityOutputs.length > 0) {+ await trx+ .insertInto("trackedActivityOutput")+ .values(trackedActivityOutputs)+ .execute();+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();++ for (const ledger of itemLedgerInserts) {+ await updatePickMethodDefaultStorageUnitIfNeeded(+ trx,+ ledger.itemId,+ ledger.locationId,+ ledger.storageUnitId,+ companyId,+ userId+ );+ }++ const returnEntries = itemLedgerInserts.map((l) => ({+ itemId: l.itemId as string,+ quantity: Number(l.quantity)+ }));++ await createMaterialWipEntries(trx, {+ consumptionLedgers: returnEntries,+ jobId: job?.id!,+ operationId: jobMaterial?.jobOperationId ?? materialId,+ description: "Unconsume Material Return",+ wipAccount: accountDefaultsUnconsume.workInProgressAccount,+ rawMaterialsAccount: accountDefaultsUnconsume.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaultsUnconsume.finishedGoodsAccount,+ dimensionMap: dimensionMapUnconsume,++ jobLocationId: job?.locationId ?? null,+ db,+ companyId,+ userId,+ postingStatus+ });+ }++ const totalChildQuantity = roundedChildTotal(children);++ const currentQuantityIssued = round(+ Number(jobMaterial?.quantityIssued) || 0+ );+ const newQuantityIssued = round(+ currentQuantityIssued - totalChildQuantity+ );++ await trx+ .updateTable("jobMaterial")+ .set({+ quantityIssued: newQuantityIssued+ })+ .where("id", "=", materialId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }+ case "convertEntity": {+ const { trackedEntityId, newRevision, quantity, companyId, userId } =+ validatedPayload;++ const convertedEntity = await db.transaction().execute(async (trx) => {+ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ if (!trackedEntity.sourceDocumentId) {+ throw new Error("Tracked entity has no source document");+ }++ // Get the old item revision+ const oldItem = await trx+ .selectFrom("item")+ .where("id", "=", trackedEntity.sourceDocumentId)+ .select(["id", "readableId", "revision"])+ .executeTakeFirstOrThrow();++ // Check if new revision exists, create if not+ let newItem = await trx+ .selectFrom("item")+ .where("readableId", "=", oldItem.readableId)+ .where("revision", "=", newRevision)+ .where("companyId", "=", companyId)+ .select(["id", "readableId", "revision", "readableIdWithRevision"])+ .executeTakeFirst();++ if (!newItem) {+ // Get the part/material/tool/consumable record+ const baseItem = await trx+ .selectFrom("item")+ .where("id", "=", oldItem.id)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Create new item revision+ const insertedItem = await trx+ .insertInto("item")+ .values({+ readableId: oldItem.readableId,+ revision: newRevision,+ type: baseItem.type,+ active: baseItem.active,+ name: baseItem.name,+ description: baseItem.description,+ itemTrackingType: baseItem.itemTrackingType,+ replenishmentSystem: baseItem.replenishmentSystem,+ defaultMethodType: baseItem.defaultMethodType,+ unitOfMeasureCode: baseItem.unitOfMeasureCode,+ modelUploadId: baseItem.modelUploadId,+ companyId,+ createdBy: userId+ })+ .returning([+ "id",+ "readableId",+ "revision",+ "readableIdWithRevision"+ ])+ .executeTakeFirstOrThrow();++ newItem = insertedItem;++ // Create the part/material/tool/consumable record if it doesn't exist+ if (baseItem.type === "Part") {+ await trx+ .insertInto("part")+ .values({+ id: oldItem.readableId,+ companyId,+ createdBy: userId+ })+ .onConflict((oc) => oc.columns(["id", "companyId"]).doNothing())+ .execute();+ }+ }++ if (oldItem.id) {+ const oldItemCost = await trx+ .selectFrom("itemCost")+ .where("itemId", "=", oldItem.id)+ .select(["unitCost"])+ .executeTakeFirst();++ // Calculate new unit cost based on quantity conversion+ // Total value = oldQuantity * oldUnitCost+ // New unit cost = Total value / newQuantity+ const oldQuantity = Number(trackedEntity.quantity);+ const oldUnitCost = Number(oldItemCost?.unitCost ?? 0);++ const totalValue = oldQuantity * oldUnitCost;+ const newUnitCost = totalValue / quantity;++ // Update new revision's cost+ if (newItem?.id) {+ await trx+ .updateTable("itemCost")+ .set({+ unitCost: newUnitCost,+ costIsAdjusted: true+ })+ .where("itemId", "=", newItem.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Create conversion activity+ const conversionActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: conversionActivityId,+ type: "Convert",+ sourceDocument: "Revision Conversion",+ attributes: {+ "Old Revision": oldItem.revision,+ "New Revision": newRevision,+ "Old Item ID": oldItem.id,+ "New Item ID": newItem.id+ },+ companyId,+ createdBy: userId+ })+ .execute();++ // Record input (old revision entity)+ if (trackedEntity.id) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: conversionActivityId,+ trackedEntityId: trackedEntity.id,+ quantity: trackedEntity.quantity,+ companyId,+ createdBy: userId+ })+ .execute();+ }++ // Update tracked entity to new revision+ await trx+ .updateTable("trackedEntity")+ .set({+ sourceDocumentId: newItem.id,+ sourceDocumentReadableId: newItem.readableIdWithRevision,+ quantity: quantity+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ // Record output (new revision entity)+ if (trackedEntity.id) {+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: conversionActivityId,+ trackedEntityId: trackedEntity.id,+ quantity: quantity,+ companyId,+ createdBy: userId+ })+ .execute();+ }++ // Get the location from existing ledger entries+ const existingLedger = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", trackedEntityId)+ .select(["locationId", "storageUnitId"])+ .orderBy("createdAt", "desc")+ .executeTakeFirst();++ // Create item ledger entries+ if (oldItem.id && newItem?.id) {+ const oldQuantity = Number(trackedEntity.quantity);+ const ledgerEntries: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [+ // Remove old revision quantity+ {+ entryType: "Negative Adjmt.",+ documentType: "Batch Split",+ documentId: conversionActivityId,+ companyId,+ itemId: oldItem.id,+ quantity: -oldQuantity,+ locationId: existingLedger?.locationId,+ storageUnitId: existingLedger?.storageUnitId,+ trackedEntityId,+ createdBy: userId+ },+ // Add new revision quantity+ {+ entryType: "Positive Adjmt.",+ documentType: "Batch Split",+ documentId: conversionActivityId,+ companyId,+ itemId: newItem.id,+ quantity: quantity,+ locationId: existingLedger?.locationId,+ storageUnitId: existingLedger?.storageUnitId,+ trackedEntityId,+ createdBy: userId+ }+ ];++ await trx.insertInto("itemLedger").values(ledgerEntries).execute();+ }++ logger.info("Entity converted", {+ trackedEntityId,+ oldRevision: oldItem.revision,+ newRevision,+ oldItemId: oldItem.id,+ newItemId: newItem.id+ });++ // Get the updated readable ID with revision+ const updatedItem = await trx+ .selectFrom("item")+ .where("id", "=", newItem.id)+ .select(["readableIdWithRevision"])+ .executeTakeFirst();++ return {+ trackedEntityId,+ readableId: updatedItem?.readableIdWithRevision ?? oldItem.readableId,+ quantity: quantity+ };+ });++ return {+ success: true,+ message: "Entity converted successfully",+ convertedEntity+ };+ }+ case "maintenanceDispatchInventory": {+ const {+ maintenanceDispatchId,+ itemId,+ unitOfMeasureCode,+ quantity,+ companyId,+ userId+ } = validatedPayload;++ const postingDate = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ await db.transaction().execute(async (trx) => {+ // Get the maintenance dispatch to find the location+ const dispatch = await trx+ .selectFrom("maintenanceDispatch")+ .where("id", "=", maintenanceDispatchId)+ .where("companyId", "=", companyId)+ .select(["id", "maintenanceDispatchId", "workCenterId", "locationId"])+ .executeTakeFirstOrThrow();++ const locationId = dispatch.locationId;++ // Get item details+ const item = await trx+ .selectFrom("item")+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .select(["id", "itemTrackingType"])+ .executeTakeFirstOrThrow();++ // Create the dispatch item+ const dispatchItem = await trx+ .insertInto("maintenanceDispatchItem")+ .values({+ maintenanceDispatchId,+ itemId,+ unitOfMeasureCode,+ quantity,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ // Only create item ledger entry for non-tracked items (not Serial or Batch)+ if (+ item.itemTrackingType !== "Serial" &&+ item.itemTrackingType !== "Batch"+ ) {+ // Get storage unit with highest quantity for this item at this location+ const storageUnitId = locationId+ ? await getStorageUnitWithHighestQuantity(trx, itemId, locationId)+ : null;++ await trx+ .insertInto("itemLedger")+ .values({+ entryType: "Consumption",+ documentType: "Maintenance Consumption",+ documentId: dispatch.id,+ documentLineId: dispatchItem.id,+ companyId,+ itemId,+ quantity: -quantity,+ locationId,+ storageUnitId,+ createdBy: userId+ })+ .execute();++ await valueMaintenanceMovements(trx, {+ dispatch,+ movements: [{ itemId, quantity: -quantity }],+ postingDate,+ companyId,+ userId+ });++ // Update pickMethod defaultStorageUnitId if needed+ if (locationId) {+ await updatePickMethodDefaultStorageUnitIfNeeded(+ trx,+ itemId,+ locationId,+ storageUnitId,+ companyId,+ userId+ );+ }+ }+ });++ return {+ success: true,+ message: "Material issued successfully"+ };+ }+ case "maintenanceDispatchTrackedEntities": {+ const {+ maintenanceDispatchId,+ itemId,+ unitOfMeasureCode,+ children,+ overrideExpired,+ overrideReason,+ companyId,+ userId+ } = validatedPayload;++ if (children.length === 0) {+ throw new Error("At least one tracked entity is required");+ }++ let expiredWarning: string | undefined;+ const companyToday = datetime.today(+ await getCompanyTimeZone(db, companyId)+ );++ const splitEntities = await db.transaction().execute(async (trx) => {+ // Get the maintenance dispatch to find the location+ const dispatch = await trx+ .selectFrom("maintenanceDispatch")+ .where("id", "=", maintenanceDispatchId)+ .where("companyId", "=", companyId)+ .select(["id", "maintenanceDispatchId", "workCenterId", "locationId"])+ .executeTakeFirstOrThrow();++ const locationId = dispatch.locationId;++ // The company's item: the dispatch item and every entity name it.+ const item = await trx+ .selectFrom("item")+ .where("id", "=", itemId)+ .where("companyId", "=", companyId)+ .select(["id", "readableIdWithRevision"])+ .executeTakeFirst();+ if (!item) {+ throw new NotFoundError("Item not found");+ }++ // Calculate total quantity from children+ const totalQuantity = children.reduce(+ (sum, child) => sum + Number(child.quantity),+ 0+ );++ // Create the dispatch item+ const dispatchItem = await trx+ .insertInto("maintenanceDispatchItem")+ .values({+ maintenanceDispatchId,+ itemId,+ unitOfMeasureCode,+ quantity: totalQuantity,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ // Get tracked entities+ const trackedEntities = await trx+ .selectFrom("trackedEntity")+ .where(+ "id",+ "in",+ children.map((child) => child.trackedEntityId)+ )+ .where("companyId", "=", companyId)+ .selectAll()+ .execute();++ // Get item ledgers for these tracked entities+ const itemLedgers = await trx+ .selectFrom("itemLedger")+ .where(+ "trackedEntityId",+ "in",+ children.map((child) => child.trackedEntityId)+ )+ .where("companyId", "=", companyId)+ .orderBy("createdAt", "desc")+ .selectAll()+ .execute();++ if (trackedEntities.length !== children.length) {+ throw new NotFoundError("Some tracked entities not found");+ }++ if (+ trackedEntities.some(+ (entity) => (entity.itemId ?? entity.sourceDocumentId) !== itemId+ )+ ) {+ throw new InvalidInputError(+ "Some tracked entities are not of the dispatched item"+ );+ }++ if (trackedEntities.some((entity) => entity.status !== "Available")) {+ throw new Error("Some tracked entities are not available");+ }++ // Expiry policy gate.+ const expiredPolicy = await getExpiredEntityPolicy(trx, companyId);+ const expiredCheck = checkExpiredEntities(+ trackedEntities.map((e) => ({+ id: e.id,+ expirationDate: e.expirationDate+ })),+ expiredPolicy,+ { allowed: !!overrideExpired, reason: overrideReason ?? null },+ companyToday+ );+ if (!expiredCheck.ok) {+ throw new Error(expiredCheck.reason);+ }+ if (expiredCheck.warning) {+ expiredWarning = expiredCheck.warning;+ }++ const maintenanceDispatchItemId = dispatchItem.id;++ // Create tracked activity+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Consume",+ sourceDocument: "Maintenance Dispatch Item",+ sourceDocumentId: maintenanceDispatchItemId,+ sourceDocumentReadableId: item.readableIdWithRevision ?? "",+ attributes: {+ "Maintenance Dispatch": dispatch.maintenanceDispatchId,+ "Maintenance Dispatch Item": dispatchItem.id,+ Employee: userId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const trackedActivityInputs: Database["public"]["Tables"]["trackedActivityInput"]["Insert"][] =+ [];+ const junctionInserts: {+ maintenanceDispatchItemId: string;+ trackedEntityId: string;+ quantity: number;+ companyId: string;+ createdBy: string;+ }[] = [];++ const splitEntities: Array<{+ originalId: string;+ newId: string;+ readableId: string;+ quantity: number;+ remainingQuantity: number;+ }> = [];++ // Process each child tracked entity+ for (const child of children) {+ const trackedEntity = trackedEntities.find(+ (entity) => entity.id === child.trackedEntityId+ );+ if (!trackedEntity) {+ throw new NotFoundError("Tracked entity not found");+ }+ const { trackedEntityId } = child;++ // Same canonical quantity as the job-consumption loop above: a+ // full draw books the lot's own rounded on-hand.+ const entityQuantity = round(Number(trackedEntity.quantity));+ const fullDraw = isFullDraw(entityQuantity, child.quantity);+ const quantity = fullDraw ? entityQuantity : round(child.quantity);++ // Book against the entity's ACTUAL bin (net on-hand), not an+ // arbitrary first ledger row — aligns with the job-consumption+ // path above.+ const entityBin = resolveTrackedEntityBin(+ itemLedgers,+ trackedEntityId+ );++ // Partial consume → split: the lineside entity keeps its id and+ // is decremented; a NEW child entity carries the consumed+ // quantity. EVERYTHING below (Consumed status, Consume input,+ // Maintenance Consumption ledger, junction row) books against+ // the child.+ let consumedEntityId = trackedEntityId;+ if (!fullDraw) {+ const consumedChildId = nanoid();+ consumedEntityId = consumedChildId;++ const split = buildBatchSplitRecords({+ parent: {+ id: trackedEntity.id!,+ readableId: trackedEntity.readableId,+ quantity: entityQuantity,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ itemId: trackedEntity.itemId ?? trackedEntity.sourceDocumentId,+ expirationDate: trackedEntity.expirationDate ?? null,+ attributes: trackedEntity.attributes as Record<+ string,+ unknown+ > | null+ },+ drawQuantity: quantity,+ childId: consumedChildId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Maintenance Dispatch Item",+ activitySourceDocumentId: maintenanceDispatchItemId,+ bin: {+ storageUnitId: entityBin,+ locationId+ },+ itemLedgerItemId: trackedEntity.sourceDocumentId,+ companyId,+ userId,+ postingDate: companyToday.toString(),+ // Created Available; the shared status update below flips the+ // child to Consumed in the same transaction.+ childStatus: "Available"+ });++ splitEntities.push({+ originalId: trackedEntityId,+ newId: consumedChildId,+ readableId: trackedEntity.sourceDocumentReadableId ?? "",+ quantity,+ remainingQuantity: split.parentUpdate.quantity+ });++ await trx+ .insertInto("trackedActivity")+ .values(+ split.activityInsert as Insertable<+ KyselyDatabase["trackedActivity"]+ >+ )+ .execute();++ await trx+ .insertInto("trackedEntity")+ .values(+ split.childEntityInsert as Insertable<+ KyselyDatabase["trackedEntity"]+ >+ )+ .execute();++ await trx+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert)+ .execute();++ await trx+ .insertInto("trackedActivityOutput")+ .values(split.activityOutputInsert)+ .execute();++ await trx+ .updateTable("trackedEntity")+ .set(split.parentUpdate)+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ itemLedgerInserts.push(+ ...(split.ledgerInserts as ItemLedgerInsert[])+ );+ }++ // Consume the drawn entity — the split child, or the whole+ // entity on a full draw.+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Consumed"+ })+ .where("id", "=", consumedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ trackedActivityInputs.push({+ trackedActivityId: activityId,+ trackedEntityId: consumedEntityId,+ quantity,+ companyId,+ createdBy: userId+ });++ // Add junction table entry+ junctionInserts.push({+ maintenanceDispatchItemId,+ trackedEntityId: consumedEntityId,+ quantity,+ companyId,+ createdBy: userId+ });++ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Maintenance Consumption",+ documentId: dispatch.id,+ documentLineId: maintenanceDispatchItemId,+ companyId,+ itemId: trackedEntity.sourceDocumentId,+ quantity: -quantity,+ locationId,+ // The split child has no rows in the pre-transaction ledger+ // snapshot — it sits at the parent's resolved bin.+ storageUnitId: entityBin,+ trackedEntityId: consumedEntityId,+ createdBy: userId+ });+ }++ if (trackedActivityInputs.length > 0) {+ await trx+ .insertInto("trackedActivityInput")+ .values(trackedActivityInputs)+ .execute();+ }++ if (junctionInserts.length > 0) {+ await trx+ .insertInto("maintenanceDispatchItemTrackedEntity")+ .values(junctionInserts)+ .execute();+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();++ // Only the consumption rows carry value; batch-split legs move+ // stock between entities at the same bin.+ await valueMaintenanceMovements(trx, {+ dispatch,+ movements: itemLedgerInserts+ .filter((l) => l.documentType === "Maintenance Consumption")+ .map((l) => ({+ itemId: l.itemId,+ quantity: Number(l.quantity)+ })),+ postingDate: companyToday.toString(),+ companyId,+ userId+ });++ // Update pickMethod defaultStorageUnitId if needed+ for (const ledger of itemLedgerInserts) {+ await updatePickMethodDefaultStorageUnitIfNeeded(+ trx,+ ledger.itemId,+ ledger.locationId,+ ledger.storageUnitId,+ companyId,+ userId+ );+ }+ }++ return splitEntities;+ });++ return {+ success: true,+ message: "Material issued successfully",+ splitEntities,+ warning: expiredWarning+ };+ }+ case "maintenanceDispatchUnconsume": {+ const { maintenanceDispatchItemId, children, companyId, userId } =+ validatedPayload;++ if (children.length === 0) {+ throw new Error("At least one tracked entity is required");+ }++ const postingDate = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ await db.transaction().execute(async (trx) => {+ // Get the maintenance dispatch item with related data+ const dispatchItem = await trx+ .selectFrom("maintenanceDispatchItem")+ .where("id", "=", maintenanceDispatchItemId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Get the maintenance dispatch to find the location+ const dispatch = await trx+ .selectFrom("maintenanceDispatch")+ .where("id", "=", dispatchItem.maintenanceDispatchId)+ .select(["id", "maintenanceDispatchId", "workCenterId", "locationId"])+ .executeTakeFirstOrThrow();++ const locationId = dispatch.locationId;++ // Get tracked entities+ const trackedEntities = await trx+ .selectFrom("trackedEntity")+ .where(+ "id",+ "in",+ children.map((child) => child.trackedEntityId)+ )+ .where("companyId", "=", companyId)+ .selectAll()+ .execute();++ // Get item ledgers for these tracked entities+ const itemLedgers = await trx+ .selectFrom("itemLedger")+ .where(+ "trackedEntityId",+ "in",+ children.map((child) => child.trackedEntityId)+ )+ .orderBy("createdAt", "desc")+ .selectAll()+ .execute();++ if (trackedEntities.length !== children.length) {+ throw new NotFoundError("Some tracked entities not found");+ }++ if (trackedEntities.some((entity) => entity.status !== "Consumed")) {+ throw new Error("Some tracked entities are not in consumed status");+ }++ // Get item details+ const item = await trx+ .selectFrom("item")+ .where("id", "=", dispatchItem.itemId)+ .select(["id", "readableIdWithRevision"])+ .executeTakeFirstOrThrow();++ // Create tracked activity for unconsume+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Unconsume",+ sourceDocument: "Maintenance Dispatch Item",+ sourceDocumentId: maintenanceDispatchItemId,+ sourceDocumentReadableId: item.readableIdWithRevision ?? "",+ attributes: {+ "Maintenance Dispatch": dispatch.maintenanceDispatchId,+ "Maintenance Dispatch Item": dispatchItem.id,+ Employee: userId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const trackedActivityOutputs: Database["public"]["Tables"]["trackedActivityOutput"]["Insert"][] =+ [];++ // Process each child tracked entity+ for (const child of children) {+ const trackedEntity = trackedEntities.find(+ (entity) => entity.id === child.trackedEntityId+ );+ if (!trackedEntity) {+ throw new NotFoundError("Tracked entity not found");+ }+ const { trackedEntityId, quantity } = child;++ // Update tracked entity status back to Available+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available"+ })+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ trackedActivityOutputs.push({+ trackedActivityId: activityId,+ trackedEntityId,+ quantity,+ companyId,+ createdBy: userId+ });++ // Remove from junction table+ await trx+ .deleteFrom("maintenanceDispatchItemTrackedEntity")+ .where("maintenanceDispatchItemId", "=", maintenanceDispatchItemId)+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ // Create reverse item ledger entry (positive to return to inventory)+ const existingLedger = itemLedgers.find(+ (l) => l.trackedEntityId === trackedEntityId+ );++ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Maintenance Consumption",+ documentId: dispatch.id,+ documentLineId: maintenanceDispatchItemId,+ companyId,+ itemId: trackedEntity.sourceDocumentId,+ quantity: quantity, // Positive to return to inventory+ locationId,+ storageUnitId: existingLedger?.storageUnitId,+ trackedEntityId,+ createdBy: userId+ });+ }++ if (trackedActivityOutputs.length > 0) {+ await trx+ .insertInto("trackedActivityOutput")+ .values(trackedActivityOutputs)+ .execute();+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();++ await valueMaintenanceMovements(trx, {+ dispatch,+ movements: itemLedgerInserts.map((l) => ({+ itemId: l.itemId,+ quantity: Number(l.quantity)+ })),+ postingDate,+ companyId,+ userId+ });++ // Update pickMethod defaultStorageUnitId if needed+ for (const ledger of itemLedgerInserts) {+ await updatePickMethodDefaultStorageUnitIfNeeded(+ trx,+ ledger.itemId,+ ledger.locationId,+ ledger.storageUnitId,+ companyId,+ userId+ );+ }+ }++ // Update the dispatch item quantity+ const totalChildQuantity = roundedChildTotal(children);++ const currentQuantity = round(Number(dispatchItem.quantity) || 0);+ const newQuantity = Math.max(+ 0,+ round(currentQuantity - totalChildQuantity)+ );++ await trx+ .updateTable("maintenanceDispatchItem")+ .set({+ quantity: newQuantity,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", maintenanceDispatchItemId)+ .where("companyId", "=", companyId)+ .execute();+ });++ return {+ success: true,+ message: "Material unconsumed successfully"+ };+ }+ case "maintenanceDispatchUnissue": {+ const { maintenanceDispatchItemId, companyId, userId } = validatedPayload;++ const postingDate = datetime+ .today(await getCompanyTimeZone(db, companyId))+ .toString();++ await db.transaction().execute(async (trx) => {+ // Get the maintenance dispatch item+ const dispatchItem = await trx+ .selectFrom("maintenanceDispatchItem")+ .where("id", "=", maintenanceDispatchItemId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Get the maintenance dispatch to find the location+ const dispatch = await trx+ .selectFrom("maintenanceDispatch")+ .where("id", "=", dispatchItem.maintenanceDispatchId)+ .select(["id", "maintenanceDispatchId", "workCenterId", "locationId"])+ .executeTakeFirstOrThrow();++ const locationId = dispatch.locationId;++ // Get item details+ const item = await trx+ .selectFrom("item")+ .where("id", "=", dispatchItem.itemId)+ .select(["id", "itemTrackingType", "readableIdWithRevision"])+ .executeTakeFirstOrThrow();++ // Check if this has tracked entities+ const trackedEntityJunctions = await trx+ .selectFrom("maintenanceDispatchItemTrackedEntity")+ .where("maintenanceDispatchItemId", "=", maintenanceDispatchItemId)+ .selectAll()+ .execute();++ if (trackedEntityJunctions.length > 0) {+ // Handle tracked entities - unconsume them+ const trackedEntityIds = trackedEntityJunctions.map(+ (j) => j.trackedEntityId+ );++ // Get tracked entities+ const trackedEntities = await trx+ .selectFrom("trackedEntity")+ .where("id", "in", trackedEntityIds)+ .selectAll()+ .execute();++ // Get item ledgers for these tracked entities+ const itemLedgers = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "in", trackedEntityIds)+ .orderBy("createdAt", "desc")+ .selectAll()+ .execute();++ // Create tracked activity for unconsume+ const activityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: activityId,+ type: "Unconsume",+ sourceDocument: "Maintenance Dispatch Item",+ sourceDocumentId: maintenanceDispatchItemId,+ sourceDocumentReadableId: item.readableIdWithRevision ?? "",+ attributes: {+ "Maintenance Dispatch": dispatch.maintenanceDispatchId,+ "Maintenance Dispatch Item": dispatchItem.id,+ Employee: userId+ },+ companyId,+ createdBy: userId+ })+ .execute();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const trackedActivityOutputs: Database["public"]["Tables"]["trackedActivityOutput"]["Insert"][] =+ [];++ // Process each tracked entity+ for (const junction of trackedEntityJunctions) {+ const trackedEntity = trackedEntities.find(+ (e) => e.id === junction.trackedEntityId+ );+ if (!trackedEntity) continue;++ const quantity = Number(junction.quantity);++ // Update tracked entity status back to Available+ await trx+ .updateTable("trackedEntity")+ .set({ status: "Available" })+ .where("id", "=", junction.trackedEntityId)+ .where("companyId", "=", companyId)+ .execute();++ trackedActivityOutputs.push({+ trackedActivityId: activityId,+ trackedEntityId: junction.trackedEntityId,+ quantity,+ companyId,+ createdBy: userId+ });++ // Create reverse item ledger entry (positive to return to inventory)+ const existingLedger = itemLedgers.find(+ (l) => l.trackedEntityId === junction.trackedEntityId+ );++ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Maintenance Consumption",+ documentId: dispatch.id,+ documentLineId: maintenanceDispatchItemId,+ companyId,+ itemId: trackedEntity.sourceDocumentId,+ quantity: quantity, // Positive to return to inventory+ locationId,+ storageUnitId: existingLedger?.storageUnitId,+ trackedEntityId: junction.trackedEntityId,+ createdBy: userId+ });+ }++ // Delete junction entries+ await trx+ .deleteFrom("maintenanceDispatchItemTrackedEntity")+ .where("maintenanceDispatchItemId", "=", maintenanceDispatchItemId)+ .where("companyId", "=", companyId)+ .execute();++ if (trackedActivityOutputs.length > 0) {+ await trx+ .insertInto("trackedActivityOutput")+ .values(trackedActivityOutputs)+ .execute();+ }++ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();++ await valueMaintenanceMovements(trx, {+ dispatch,+ movements: itemLedgerInserts.map((l) => ({+ itemId: l.itemId,+ quantity: Number(l.quantity)+ })),+ postingDate,+ companyId,+ userId+ });+ }+ } else if (+ item.itemTrackingType !== "Serial" &&+ item.itemTrackingType !== "Batch"+ ) {+ // Handle inventory items - create positive ledger entry to return to inventory+ const quantity = Number(dispatchItem.quantity);++ if (quantity > 0) {+ // Find the storage unit from the original consumption ledger entry+ const originalLedger = await trx+ .selectFrom("itemLedger")+ .where("documentLineId", "=", maintenanceDispatchItemId)+ .where("documentType", "=", "Maintenance Consumption")+ .orderBy("createdAt", "desc")+ .selectAll()+ .executeTakeFirst();++ await trx+ .insertInto("itemLedger")+ .values({+ entryType: "Consumption",+ documentType: "Maintenance Consumption",+ documentId: dispatch.id,+ documentLineId: maintenanceDispatchItemId,+ companyId,+ itemId: dispatchItem.itemId,+ quantity: quantity, // Positive to return to inventory+ locationId,+ storageUnitId: originalLedger?.storageUnitId,+ createdBy: userId+ })+ .execute();++ await valueMaintenanceMovements(trx, {+ dispatch,+ movements: [{ itemId: dispatchItem.itemId, quantity }],+ postingDate,+ companyId,+ userId+ });+ }+ }++ // Delete the dispatch item+ await trx+ .deleteFrom("maintenanceDispatchItem")+ .where("id", "=", maintenanceDispatchItemId)+ .where("companyId", "=", companyId)+ .execute();+ });++ return {+ success: true,+ message: "Item unissued and removed successfully"+ };+ }+ }++ return {+ success: true,+ message: "x"+ };+ }diff --cc apps/erp/app/modules/settings/settings.server.tsindex 26c42daa38,142df23dea..3ad74a6cad--- a/apps/erp/app/modules/settings/settings.server.ts+++ b/apps/erp/app/modules/settings/settings.server.ts@@@ -2,913 -2,3181 +2,3184 @@@// 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 { bustApiKeyCache } from "@carbon/auth/auth.server";- import { getCarbonServiceRole } from "@carbon/auth/client.server";- import type { Database, Json } from "@carbon/database";+ import { defineServiceFn } from "@carbon/api/service-fn.server";+ import { paged, payload, unwrap } from "@carbon/api/service-tools.server";+ import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";+ import { bustApiKeyCache, hashApiKey } from "@carbon/auth/auth.server";import {- getIntegrationConfigById,- getIntegrationIdsByRole,- type IntegrationHealthcheckResult,- type IntegrationID,- resolveIntegrationSecrets,- splitSecrets- } from "@carbon/ee";- import { isAccountingSyncEnabled } from "@carbon/ee/accounting";+ blockSchema,+ type DocumentBlock,+ type DocumentSettings,+ type DocumentTheme,+ documentSectionPlacementSchema,+ documentSettingsSchema,+ documentTemplateTypeSchema,+ sectionConfigSchema,+ themeSchema+ } from "@carbon/documents/template";+ import { integrations as availableIntegrations } from "@carbon/ee";+ import {+ getUnmappedRequiredAccounts,+ JOURNAL_ENTRY_SOURCE_TYPES,+ POSTING_POLICY,+ suggestAccountMatchesWithAI,+ upsertAccountMappings,+ upsertDimensionValueMapping,+ validateDimensionSlots+ } from "@carbon/ee/accounting";+ import { deleteApiKey, upsertApiKey } from "@carbon/ee/api-keys.server";+ import {+ disableAuditLog,+ enableAuditLog,+ getArchiveDownloadUrl+ } from "@carbon/ee/audit.server";+ import { updateConsoleSetting } from "@carbon/ee/console.server";+ import { EntitlementError } from "@carbon/ee/entitlements.server";import { getIntegrationServerHooks } from "@carbon/ee/hooks.server";+ import type { OeeDevice } from "@carbon/ee/oee";import {- isOnshapeOAuthIntegrationId,- patchOnshapeSettings- } from "@carbon/ee/onshape.server";- import { patchRampSettings } from "@carbon/ee/ramp.server";- import { redis } from "@carbon/kv";+ deleteWorkCenterDevice,+ upsertWorkCenterDevice+ } from "@carbon/ee/oee.server";+ import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape";+ import { isIntegrationWhitelisted } from "@carbon/ee/plan";+ import { companyHasFeature } from "@carbon/ee/plan.server";+ import { updateRequireMfaSetting } from "@carbon/ee/two-factor.server";+ import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";- import type { SupabaseClient } from "@supabase/supabase-js";- import type { z } from "zod";- import type { Integration } from "~/modules/settings/types";- import { sanitize } from "~/utils/supabase";- import { oeeDevicesCacheKey } from "./oee-devices-cache";- import type { customFieldValidator } from "./settings.models";-- const INTEGRATION_CACHE_TTL = 3600;- const logger = getLogger("erp", "settings");+ import {+ createPrintJob,+ deletePrinterRoute,+ getPrintingSettings,+ getPrintJob,+ getPrintJobContent,+ type PrintingSettings,+ printerRouteValidator,+ reprintValidator,+ setContextAssignment,+ updateAssignmentValidator,+ updatePrintingSettings,+ upsertPrinterRoute+ } from "@carbon/printing";+ import { invalidatePrinterCache } from "@carbon/printing/printing.server";+ import type { JSONContent } from "@carbon/react";+ import { getStripeConnectAccountId } from "@carbon/stripe/send-sales-invoice.server";+ import { getBillingPortalRedirectUrl } from "@carbon/stripe/stripe.server";+ import { datetime, unchecked } from "@carbon/utils";+ import { parseTime } from "@internationalized/date";+ import { nanoid } from "nanoid";+ import { z } from "zod";+ import { plmReleaseControl } from "~/modules/items/items.models";+ import {+ invalidateCompanyTimeZone,+ invokePosting,+ isActiveCompanyEmployee+ } from "~/modules/shared/shared.service";+ import { sendMfaRequiredEmails } from "~/services/mfa-email.server";+ import * as accountingPostings from "../accounting/accounting.service";+ import { fromServerFn } from "../shared/shared.service";+ import {+ accountMappingEntrySchema,+ apiKeyValidator,+ calculatedShelfLifeInputScopes,+ companyValidator,+ dimensionSlotEntrySchema,+ dimensionValueMappingEntrySchema,+ expiredEntityPolicies,+ incompletePickingListPolicies,+ invoiceAutomations,+ kanbanOutputTypes,+ purchasePriceUpdateTimingTypes,+ returnPickedMaterialTimings,+ subsidiaryValidator+ } from "./settings.models";+ import * as service from "./settings.service";+ const logger = getLogger("erp", "settings");+ // ─── Operations (`defineServiceFn`) ─────────────────────────────────────────+ // What the routes, the API and MCP all run. A settings page has ONE update+ // operation: it takes the page's fields, all optional, and writes the ones+ // sent. An absent field keeps its stored value, so one form never blanks a+ // neighbouring setting.+ const notificationGroup = z.array(z.string().min(1));++ const billingAddressInput = z.object({+ name: z.string().nullable().optional(),+ addressLine1: z.string().nullable().optional(),+ addressLine2: z.string().nullable().optional(),+ city: z.string().nullable().optional(),+ state: z.string().nullable().optional(),+ postalCode: z.string().nullable().optional(),+ countryCode: z.string().nullable().optional(),+ phone: z.string().nullable().optional(),+ fax: z.string().nullable().optional(),+ email: z.string().email().nullable().optional()+ });/**- * Drop the cached auth record for an API key so a scope change or revocation- * takes effect immediately in the common case. An in-flight auth read can still- * re-prime the cache with the pre-write row, so the hard bound is the 30s TTL —- * callers that delete the row should bust AGAIN after the delete commits, using- * the returned keyHash (unreadable from the DB once the row is gone).- *- * Service-role on purpose: apiKey's RLS SELECT requires `settings_view`, but the- * routes that revoke or rescope a key gate on `users_update`, so the caller's own- * client cannot see the row and the bust would silently do nothing.- */- export async function invalidateApiKeyCache(- id: string,- companyId: string- ): Promise<string | null> {- const { data, error } = await getCarbonServiceRole()- .from("apiKey")- .select("keyHash")- .eq("id", id)- .eq("companyId", companyId)- .maybeSingle();- // A failed lookup is indistinguishable from a missing row at the return type,- // and neither may block the revoke — log it so a stale scope surviving its TTL- // is diagnosable rather than silent.- if (error) {- logger.error("Failed to read api key for cache bust", {- error,- id,- companyId+ * Update the accounting settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: whether money shows its+ * trailing zeros, the fixed-asset tax depreciation (on or off, its rate, and+ * the deferred tax liability and expense accounts on the company's account+ * defaults), and the ASC 842 lease policy (the classification thresholds,+ * the default lessor discount rate and lessee incremental borrowing rate in+ * percentage points, the short-term lease expedient, and how many days ahead+ * a lease's owner is reminded). The lease policy applies to later lease+ * activations only.+ *+ * @mcp+ */+ export const updateAccountingSettings = defineServiceFn({+ input: z.object({+ showCurrencyTrailingZeros: z.boolean().optional(),+ assetTaxDepreciationEnabled: z.boolean().optional(),+ assetTaxRate: z.number().min(0).max(100).nullable().optional(),+ deferredTaxLiabilityAccountId: z.string().min(1).optional(),+ deferredTaxExpenseAccountId: z.string().min(1).optional(),+ leaseMajorPartThresholdPercent: z.number().gt(0).max(100).optional(),+ leaseSubstantiallyAllThresholdPercent: z.number().gt(0).max(100).optional(),+ leaseDefaultDiscountRate: z.number().min(0).optional(),+ leaseIncrementalBorrowingRate: z.number().min(0).optional(),+ leaseShortTermExpedient: z.boolean().optional(),+ leaseReminderDays: z.number().int().min(0).optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const {+ deferredTaxLiabilityAccountId,+ deferredTaxExpenseAccountId,+ ...settings+ } = input;++ const saved = await service.saveCompanySettings(+ ctx,+ settings,+ "Failed to update accounting settings"+ );+ if (saved) return saved;++ const accounts = service.sentFields({+ deferredTaxLiabilityAccountId,+ deferredTaxExpenseAccountId});+ if (Object.keys(accounts).length > 0) {+ const { error } = await ctx.asCaller.supabase+ .from("accountDefault")+ .update({ ...accounts, updatedBy: ctx.auditUserId })+ .eq("companyId", ctx.company.id);+ if (error) {+ return ctx.error(+ "internal",+ "Failed to update the deferred tax accounts",+ error+ );+ }+ }+ return input;}- if (!data?.keyHash) return null;- await bustApiKeyCache(data.keyHash);- return data.keyHash;- }-- export async function clearCustomFieldsCache(companyId?: string) {- const keys = companyId ? `customFields:${companyId}:*` : "customFields:*";- redis.keys(keys).then(function (keys) {- const pipeline = redis.pipeline();- keys.forEach(function (key) {- pipeline.del(key);- });- return pipeline.exec();- });- }-- export async function clearCompanyIntegrationCache(- companyId: string- ): Promise<void> {- const cacheKey = `integrations:${companyId}`;-- try {- // Clear both old and new key formats, and the OEE device lists: a new API- // key or environment can name different stations.- await redis.del(- cacheKey,- `json:${cacheKey}`,- ...getIntegrationIdsByRole("oee").map((integrationId) =>- oeeDevicesCacheKey(companyId, integrationId)- )+ });++ /**+ * Write the journals the accounting cutover would have written for documents posted without one.+ *+ * @remarks+ * A company that enabled accounting before the enable wrote journals has+ * documents posted on or after its cutover with no journal. This runs the+ * `journal-legacy-documents` posting, which journals each of them, and+ * returns how many documents it journaled. Not published: it needs two+ * modules' permissions, which the API gate cannot state yet.+ */+ export const writeMissingJournals = defineServiceFn({+ input: z.object({}),+ permission: { update: ["settings", "accounting"] },+ async run(ctx) {+ const result = await invokePosting(+ ctx,+ "journal-legacy-documents",+ {},+ accountingPostings.repairLegacyJournals);- } catch (error) {- logger.error("Redis cache invalidation error", { error });+ if (result.error) {+ return fromServerFn(+ ctx,+ result.error,+ "Failed to write the missing journals"+ );+ }+ const { movementCostRows: _, ...families } = result.data.legacyJournals;+ return {+ documents: Object.values(families).reduce((sum, count) => sum + count, 0)+ };}- }+ });- export async function clearAllIntegrationCaches(): Promise<void> {- try {- // Clear both old and new key patterns- const oldPattern = "integrations:*";- const newPattern = "json:integrations:*";+ /**+ * Update the inventory settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: what a kanban card prints+ * (label, QR code or URL), the shelf-life and expiry policy (the near-expiry+ * warning in days, null to turn the badges off; the default shelf life of a+ * new item; which inputs a calculated expiry reads; and what consuming an+ * expired entity does), whether finishing a picking list with unpicked+ * material warns or refuses, and when unconsumed picked material is returned- * (when the job completes, or when each operation is done).++ * (when the job completes, or when each operation is done), and whether a++ * new receipt's lines start at a received quantity of 0 instead of the++ * quantity still to receive.+ *+ * @mcp+ */+ export const updateInventorySettings = defineServiceFn({+ input: z.object({+ kanbanOutput: z.enum(kanbanOutputTypes).optional(),+ inventoryShelfLife: z+ .object({+ nearExpiryWarningDays: z.number().int().min(0).max(365).nullable(),+ defaultShelfLifeDays: z.number().int().min(1).max(3650),+ calculatedInputScope: z.enum(calculatedShelfLifeInputScopes),+ expiredEntityPolicy: z.enum(expiredEntityPolicies)+ })+ .optional(),+ incompletePickingListPolicy: z+ .enum(incompletePickingListPolicies)+ .optional(),- returnPickedMaterialTiming: z.enum(returnPickedMaterialTimings).optional()++ returnPickedMaterialTiming: z.enum(returnPickedMaterialTimings).optional(),++ receiptQuantitiesStartAtZero: z.boolean().optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const saved = await service.saveCompanySettings(+ ctx,+ input,+ "Failed to update inventory settings"+ );+ return saved ?? input;+ }+ });- const [oldKeys, newKeys] = await Promise.all([- redis.keys(oldPattern),- redis.keys(newPattern)- ]);+ /**+ * Update the invoicing settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: what happens to a recurring+ * invoice when the daily job creates it, the receivables email (the Reply-To+ * and a CC on automated invoice emails), who is also notified about+ * invoices, whether documents print the centralized receivables billing+ * address, that address itself (a null field clears it), and the default CC+ * on customer emails. "Post and Send via Stripe" is refused until Stripe is+ * connected in Integrations, or every recurring invoice would be held.+ *+ * @mcp+ */+ export const updateInvoicingSettings = defineServiceFn({+ input: z.object({+ invoiceAutomation: z.enum(invoiceAutomations).optional(),+ accountsReceivableEmail: z.string().email().nullable().optional(),+ invoiceNotificationGroup: notificationGroup.optional(),+ accountsReceivableAddress: z.boolean().optional(),+ accountsReceivableBillingAddress: billingAddressInput.optional(),+ defaultCustomerCc: z.array(z.string().email()).optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const { accountsReceivableBillingAddress, ...settings } = input;++ if (+ settings.invoiceAutomation === "Post and Send via Stripe" &&+ !(await getStripeConnectAccountId(ctx.asSystem.supabase, ctx.company.id))+ ) {+ return ctx.error("rule", "Connect Stripe in Integrations first");+ }- const allKeys = [...oldKeys, ...newKeys];- if (allKeys.length > 0) {- logger.info("Clearing integration cache entries", {- count: allKeys.length- });- await redis.del(...allKeys);+ const saved = await service.saveCompanySettings(+ ctx,+ settings,+ "Failed to update invoicing settings"+ );+ if (saved) return saved;++ if (accountsReceivableBillingAddress) {+ const { error } = await ctx.asCaller.supabase+ .from("companyAccountsReceivableBillingAddress")+ .upsert({+ id: ctx.company.id,+ ...service.sentFields(accountsReceivableBillingAddress),+ updatedBy: ctx.auditUserId+ });+ if (error) {+ return ctx.error(+ "internal",+ "Failed to update the accounts receivable billing address",+ error+ );+ }}- } catch (error) {- logger.error("Error clearing all integration caches", { error });+ return input;}- }+ });- export async function deactivateIntegration(- client: SupabaseClient<Database>,- args: {- id: string;- companyId: string;- updatedBy: string;+ /**+ * Update the items settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: whether material ids are+ * generated from their properties, whether material sizes use metric units,+ * whether item ids may contain lowercase letters, whether the BoM explorer+ * shows readable ids, and how strictly a released revision controls changes+ * (off, warn or enforce).+ *+ * @mcp+ */+ export const updateItemsSettings = defineServiceFn({+ input: z.object({+ materialGeneratedIds: z.boolean().optional(),+ useMetric: z.boolean().optional(),+ allowLowercaseItemIds: z.boolean().optional(),+ showBomExplorerReadableId: z.boolean().optional(),+ plmReleaseControl: z.enum(plmReleaseControl).optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const saved = await service.saveCompanySettings(+ ctx,+ input,+ "Failed to update items settings"+ );+ return saved ?? input;}- ) {- const { id, companyId, updatedBy } = args;+ });- const result = await client- .from("companyIntegration")- .update({- active: false,- updatedBy,- updatedAt: new Date().toISOString()- })- .eq("id", id)- .eq("companyId", companyId);-- if (result.error) {- return result;- }-- await clearCompanyIntegrationCache(companyId);-- return result;- }-- export async function deleteCustomField(- client: SupabaseClient<Database>,- id: string,- companyId: string- ) {- try {- clearCustomFieldsCache(companyId);- } finally {- return client.from("customField").delete().eq("id", id);- }- }-- interface CompanyIntegration {- id: string;- companyId: string;- metadata: Record<string, any>;- active: boolean;- }-- export async function getCompanyIntegrations(- client: SupabaseClient<Database>,- companyId: string- ): Promise<CompanyIntegration[]> {- const cacheKey = `integrations:${companyId}`;-- try {- // Try the new prefixed key first- let cached = await redis.get(`json:${cacheKey}`);- if (cached && typeof cached === "string") {- try {- return JSON.parse(cached);- } catch (parseError) {- logger.error("JSON parse error for prefixed cache key", {- cacheKey: `json:${cacheKey}`,- error: parseError- });- await redis.del(`json:${cacheKey}`);+ /**+ * Update the production settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: who is notified when an+ * inventory or a sales job completes, whether opening an operation starts its+ * timer, whether the job traveler lists materials and operations, whether+ * tracked material is pre-selected without a picking list, and whether one+ * location requires an assigned operator before the scheduler places work+ * there. The staffing rule lives on the location row and is written for the+ * company's own location only, so a settings admin without the resources+ * permission can still set it.+ *+ * @mcp+ */+ export const updateProductionSettings = defineServiceFn({+ input: z.object({+ inventoryJobCompletedNotificationGroup: notificationGroup.optional(),+ salesJobCompletedNotificationGroup: notificationGroup.optional(),+ autoStartOperationTimer: z.boolean().optional(),+ includeMaterialsOnTraveler: z.boolean().optional(),+ includeOperationsOnTraveler: z.boolean().optional(),+ autoSelectMaterialWithoutPickingList: z.boolean().optional(),+ locationStaffing: z+ .object({+ locationId: z.string().min(1),+ requiresStaffing: z.boolean()+ })+ .optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const { locationStaffing, ...settings } = input;++ const saved = await service.saveCompanySettings(+ ctx,+ settings,+ "Failed to update production settings"+ );+ if (saved) return saved;++ if (locationStaffing) {+ const { data, error } = await ctx.asSystem.supabase+ .from("location")+ .update({ requiresStaffing: locationStaffing.requiresStaffing })+ .eq("id", locationStaffing.locationId)+ .eq("companyId", ctx.company.id)+ .select("id");+ if (error) {+ return ctx.error(+ "internal",+ "Failed to update the staffing requirement",+ error+ );}+ if (data.length === 0) return ctx.error("notFound", "Location not found");}+ return input;+ }+ });- // Fallback to old key format for backwards compatibility- cached = await redis.get(cacheKey);- if (cached !== null && cached !== undefined) {- // Log the type and content for debugging- logger.info("Cache hit", {- cacheKey,- type: typeof cached,- isArray: Array.isArray(cached),- value: cached,- constructor: cached?.constructor?.name- });-- // Handle different response types from Upstash- if (Array.isArray(cached)) {- // Direct array return from Upstash- return cached as CompanyIntegration[];- } else if (typeof cached === "object" && cached !== null) {- // Object return from Upstash - could be a parsed JSON already- return cached as CompanyIntegration[];- } else if (typeof cached === "string") {- // String return - needs JSON parsing- try {- return JSON.parse(cached);- } catch (parseError) {- logger.error("JSON parse error for cache key", {- cacheKey,- error: parseError,- cached- });- await redis.del(cacheKey);- }- } else {- logger.warning("Unexpected cache format for key", {- cacheKey,- type: typeof cached,- cached- });- await redis.del(cacheKey);+ /**+ * Update the purchasing settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: whether documents print the+ * centralized payables billing address, that address itself (a null field+ * clears it), whether a supplier needs a contact with an email before its+ * documents issue, when a purchase updates the item's price (on invoice post+ * or on order finalize), whether a receipt updates the supplier lead time,+ * whether supplier readable ids show, who is notified about supplier quotes,+ * and the default CC on supplier emails.+ *+ * @mcp+ */+ export const updatePurchasingSettings = defineServiceFn({+ input: z.object({+ accountsPayableAddress: z.boolean().optional(),+ accountsPayableBillingAddress: billingAddressInput.optional(),+ requireSupplierContactAndLocation: z.boolean().optional(),+ purchasePriceUpdateTiming: z+ .enum(purchasePriceUpdateTimingTypes)+ .optional(),+ updateLeadTimesOnReceipt: z.boolean().optional(),+ showSupplierReadableId: z.boolean().optional(),+ supplierQuoteNotificationGroup: notificationGroup.optional(),+ defaultSupplierCc: z.array(z.string().email()).optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const { accountsPayableBillingAddress, ...settings } = input;++ const saved = await service.saveCompanySettings(+ ctx,+ settings,+ "Failed to update purchasing settings"+ );+ if (saved) return saved;++ if (accountsPayableBillingAddress) {+ const { error } = await ctx.asCaller.supabase+ .from("companyAccountsPayableBillingAddress")+ .update({+ ...service.sentFields(accountsPayableBillingAddress),+ updatedBy: ctx.auditUserId+ })+ .eq("id", ctx.company.id);+ if (error) {+ return ctx.error(+ "internal",+ "Failed to update the accounts payable billing address",+ error+ );}}- } catch (error) {- logger.error("Redis cache read error", { error });- // Clear the corrupted cache entry- try {- await redis.del(cacheKey);- } catch (deleteError) {- logger.error("Failed to delete corrupted cache entry", {- error: deleteError- });- }+ return input;+ }+ });++ /**+ * Update the quality settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: whether an inspection needs a+ * second person to sign it off, the sampling standard inspection plans use,+ * the open-issue target on the quality dashboard, and who is notified when a+ * gauge goes out of calibration.+ *+ * @mcp+ */+ export const updateQualitySettings = defineServiceFn({+ input: z.object({+ enforceInspectionFourEyes: z.boolean().optional(),+ samplingStandard: z.enum(["ANSI_Z1_4", "ISO_2859_1"]).optional(),+ qualityIssueTarget: z.number().int().min(0).optional(),+ gaugeCalibrationExpiredNotificationGroup: notificationGroup.optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const saved = await service.saveCompanySettings(+ ctx,+ input,+ "Failed to update quality settings"+ );+ return saved ?? input;}+ });++ /**+ * Update the resources settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: who is notified about a new+ * suggestion, and who is notified about a maintenance, quality, operations or+ * other dispatch.+ *+ * @mcp+ */+ export const updateResourcesSettings = defineServiceFn({+ input: z.object({+ suggestionNotificationGroup: notificationGroup.optional(),+ maintenanceDispatchNotificationGroup: notificationGroup.optional(),+ qualityDispatchNotificationGroup: notificationGroup.optional(),+ operationsDispatchNotificationGroup: notificationGroup.optional(),+ otherDispatchNotificationGroup: notificationGroup.optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const { suggestionNotificationGroup, ...settings } = input;++ // The suggestion group lives on the company row, not its settings.+ if (suggestionNotificationGroup) {+ const { error } = await ctx.asCaller.supabase+ .from("company")+ .update({ suggestionNotificationGroup })+ .eq("id", ctx.company.id);+ if (error) {+ return ctx.error(+ "internal",+ "Failed to update suggestion notifications",+ error+ );+ }+ }- const { data, error } = await client- .from("companyIntegration")- .select("*")- .eq("companyId", companyId);+ const saved = await service.saveCompanySettings(+ ctx,+ settings,+ "Failed to update dispatch notifications"+ );+ return saved ?? input;+ }+ });- if (error) {- throw error;+ /**+ * Update the sales settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: whether a customer needs a+ * contact and location, whether customer readable ids show, the digital quote+ * (on or off, who is notified, and whether accepting one asks for a purchase+ * order), who is notified when an RFQ is ready and when a sales rule is+ * broken, and the default markup per cost category on a quote line.+ *+ * @mcp+ */+ export const updateSalesSettings = defineServiceFn({+ input: z.object({+ requireCustomerContactAndLocation: z.boolean().optional(),+ showCustomerReadableId: z.boolean().optional(),+ digitalQuoteEnabled: z.boolean().optional(),+ digitalQuoteNotificationGroup: notificationGroup.optional(),+ digitalQuoteIncludesPurchaseOrders: z.boolean().optional(),+ rfqReadyNotificationGroup: notificationGroup.optional(),+ salesRuleNotificationGroup: notificationGroup.optional(),+ quoteLineCategoryMarkups: z+ .object({+ materialCost: z.number().min(0),+ partCost: z.number().min(0),+ toolCost: z.number().min(0),+ consumableCost: z.number().min(0),+ laborCost: z.number().min(0),+ machineCost: z.number().min(0),+ overheadCost: z.number().min(0),+ outsideCost: z.number().min(0)+ })+ .optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const saved = await service.saveCompanySettings(+ ctx,+ input,+ "Failed to update sales settings"+ );+ return saved ?? input;}+ });- // Secret material must never reach Redis. Strip each integration's secret keys- // into the vault-backed shape (config only) before caching AND returning, so no- // consumer of this function depends on a plaintext secret in `metadata` (secret- // reads go through resolveIntegrationSecrets against the row, not this cache).- const integrations = (data || []).map((integration) => ({- ...integration,- metadata: splitSecrets(integration.id, integration.metadata).config- }));+ /**+ * Update the people settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest: whether timecards are on, and+ * whether console (kiosk) mode is on. Console mode is a Business plan+ * feature. Turning it on creates the "Console Operator" employee type, and+ * for a signed-in user who has no console PIN yet it generates one: `pin` is+ * returned once and can never be read back. `pinError` says why that PIN+ * could not be created; console mode is on regardless. A key caller gets no+ * PIN.+ */+ export const updatePeopleSettings = defineServiceFn({+ input: z.object({+ timeCardEnabled: z.boolean().optional(),+ consoleEnabled: z.boolean().optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const { consoleEnabled, ...settings } = input;++ const saved = await service.saveCompanySettings(+ ctx,+ settings,+ "Failed to update timecard settings"+ );+ if (saved) return saved;+ if (consoleEnabled === undefined) {+ return { ...input, pin: null, pinError: null };+ }- try {- // Force string storage to avoid Upstash automatic deserialization issues- const serializedData = JSON.stringify(integrations);- if (typeof serializedData === "string" && serializedData.length > 0) {- // Use a prefixed key to ensure we know this is a JSON string- await redis.setex(- `json:${cacheKey}`,- INTEGRATION_CACHE_TTL,- serializedData- );- } else {- logger.error("Failed to serialize integrations data for cache");- }- } catch (error) {- logger.error("Redis cache write error", { error });- }-- return integrations as CompanyIntegration[];- }-- export async function hasIntegration(- client: SupabaseClient<Database>,- companyId: string,- integrationId: string- ): Promise<boolean> {- const integrations = await getCompanyIntegrations(client, companyId);- return integrations.some((i) => i.id === integrationId && i.active === true);- }-- export async function getCompanyIntegration(- client: SupabaseClient<Database>,- companyId: string,- integrationId: string- ): Promise<CompanyIntegration | null> {- const integrations = await getCompanyIntegrations(client, companyId);- return (- integrations.find((i) => i.id === integrationId && i.active === true) ||- null- );- }-- export async function getSlackIntegration(- client: SupabaseClient<Database>,- companyId: string- ): Promise<{ token: string; channelId?: string } | null> {- // The Redis cache (getCompanyIntegration) no longer holds secret material, so- // read the row directly with a service-role client — required both to resolve- // the vaulted access_token and, in the transitional window, to see the plaintext- // still in the column.- const serviceRole = getCarbonServiceRole();- const { data: integration } = await serviceRole- .from("companyIntegration")- .select("metadata, secretRef, active")- .eq("companyId", companyId)- .eq("id", "slack")- .maybeSingle();-- if (!integration?.active || !integration.metadata) {- return null;- }-- const metadata = (await resolveIntegrationSecrets(- serviceRole,- companyId,- "slack",- integration.metadata,- integration.secretRef- )) as any;-- if (!metadata.access_token) {- return null;- }-- return {- token: metadata.access_token,- channelId: metadata.channel_id || metadata.default_channel_id- };- }-- export async function hasSlackIntegration(- client: SupabaseClient<Database>,- companyId: string- ): Promise<boolean> {- return hasIntegration(client, companyId, "slack");- }-- export async function upsertCompanyIntegration(- client: SupabaseClient<Database>,- update: {- id: string;- active: boolean;- metadata: Json;- companyId: string;- updatedBy: string;- }- ) {- if (update.id === "ramp") {+ let update: Awaited<ReturnType<typeof updateConsoleSetting>>;try {- const data = await patchRampSettings(- getCarbonServiceRole(),- update.companyId,- {- metadata: update.metadata as Record<string, unknown>,- active: update.active,- updatedBy: update.updatedBy- }+ update = await updateConsoleSetting(+ ctx.asCaller.supabase,+ ctx.asSystem.pg,+ ctx.company.id,+ consoleEnabled,+ ctx.actor.type === "user" ? ctx.actor.userId : undefined+ );+ } catch (err) {+ if (!(err instanceof EntitlementError)) throw err;+ return ctx.error(+ "entitlement",+ "Console mode requires the Business plan");- await clearCompanyIntegrationCache(update.companyId);- return { data, error: null };- } catch (error) {- logger.error("Failed to atomically patch Ramp settings", {- error,- companyId: update.companyId- });- return { data: null, error };}+ if (update.error) {+ return ctx.error(+ "internal",+ "Failed to update console mode",+ update.error+ );+ }+ return { ...input, pin: update.pin, pinError: update.pinError };}+ });- // The Onshape rows are shared with the token refresh, the OAuth callback and- // the panel's property map, so a settings save patches only its own keys.- if (isOnshapeOAuthIntegrationId(update.id)) {+ /**+ * Turn the company-wide two-factor requirement on or off.+ *+ * @remarks+ * Requiring two-factor authentication is a Business plan feature; turning it+ * off is always allowed, so a downgraded company is never locked out. When it+ * goes from off to on, every active employee is emailed. It is not announced+ * when the stored value was already on, when the stored value cannot be read,+ * or in a controlled environment, where two-factor is mandatory from the day+ * of deployment.+ *+ * @mcp+ */+ export const updateSecuritySettings = defineServiceFn({+ input: z.object({ requireMfa: z.boolean() }),+ permission: { update: "settings" },+ async run(ctx, { requireMfa }) {+ // Read first: the switch re-submits on every flip, and a toggle that+ // lands on the value it already had must not re-announce.+ const previous = await ctx.asCaller.supabase+ .from("companySettings")+ .select("requireMfa")+ .eq("id", ctx.company.id)+ .single();++ let update: Awaited<ReturnType<typeof updateRequireMfaSetting>>;try {- const data = await patchOnshapeSettings(- getCarbonServiceRole(),- update.companyId,- update.id,- {- metadata: update.metadata as Record<string, unknown>,- active: update.active,- updatedBy: update.updatedBy- }+ update = await updateRequireMfaSetting(+ ctx.asCaller.supabase,+ ctx.company.id,+ requireMfa+ );+ } catch (err) {+ if (!(err instanceof EntitlementError)) throw err;+ return ctx.error(+ "entitlement",+ "Upgrade to Business to require two-factor authentication"+ );+ }+ if (update.error) {+ return ctx.error(+ "internal",+ "Failed to update two-factor requirement",+ update.error);- await clearCompanyIntegrationCache(update.companyId);- return { data, error: null };- } catch (error) {- logger.error("Failed to patch Onshape settings", {- error,- companyId: update.companyId,- integrationId: update.id- });- return { data: null, error };}- }-- // Split secret material out of the metadata: only the non-secret config is- // written to the column; the secrets go to Supabase Vault. The row is upserted- // FIRST (so it exists), then the vault RPC stamps `secretRef` onto it.- // `secrets` is a PARTIAL bag — splitSecrets omits untouched masked fields — so- // `upsert_integration_secret` MERGES it into the stored bag (an omitted secret- // keeps its value). A full replace here silently wiped a multi-secret- // integration's other credential on a partial save.- const { config, secrets } = splitSecrets(update.id, update.metadata);-- const result = await client- .from("companyIntegration")- .upsert([{ ...update, metadata: config as Json }], {- onConflict: "id,companyId"- })- .select()- .single();-- if (result.error) {- return result;- }- if (Object.keys(secrets).length > 0) {- const serviceRole = getCarbonServiceRole();- const { error: vaultError } = await serviceRole.rpc(- "upsert_integration_secret",- {- p_company_id: update.companyId,- p_integration_id: update.id,- p_secret: secrets as never- }- );- if (vaultError) {- logger.error("Failed to persist integration secret to vault", {- error: vaultError,- id: update.id- });- return { ...result, data: null, error: vaultError };+ if (+ !CONTROLLED_ENVIRONMENT &&+ requireMfa &&+ previous.data?.requireMfa === false+ ) {+ await sendMfaRequiredEmails(ctx.asSystem.supabase, ctx.company.id);}+ return { requireMfa };}+ });- await clearCompanyIntegrationCache(update.companyId);+ const employeeOrNone = z.string().min(1).nullable();- return result;- }-- export async function upsertCustomField(- client: SupabaseClient<Database>,- customField:- | (Omit<z.infer<typeof customFieldValidator>, "id"> & {- companyId: string;- createdBy: string;+ /**+ * Update the planning settings.+ *+ * @remarks+ * Writes the fields sent and leaves the rest. The planning action owner+ * ladder: the company default responsible employee, one location's+ * responsible employee, and one item group's at a location (null clears a+ * rung, so it inherits from the one above). Each employee must be an active+ * employee of the company. A location is a resources record: without the+ * resources update permission it is refused. Then whether purchase orders+ * the planning pages raise skip approval, the reschedule tolerance in days,+ * the default planning horizon in days (null for no time fence), the forecast+ * consumption window in weekly periods back and forward, and the time of day+ * scheduled MRP runs on the company's clock ("HH:MM" or "HH:MM:SS"; null runs+ * it every 3 hours).+ *+ * @mcp+ */+ export const updatePlanningSettings = defineServiceFn({+ input: z.object({+ defaultResponsibleEmployee: employeeOrNone.optional(),+ locationResponsibleEmployee: z+ .object({+ locationId: z.string().min(1),+ responsibleEmployee: employeeOrNone})- | (Omit<z.infer<typeof customFieldValidator>, "id"> & {- id: string;- updatedBy: string;+ .optional(),+ itemGroupResponsibleEmployee: z+ .object({+ locationId: z.string().min(1),+ itemPostingGroupId: z.string().min(1),+ responsibleEmployee: employeeOrNone})- ) {- try {- clearCustomFieldsCache();- } finally {- if ("createdBy" in customField) {- const sortOrders = await client- .from("customField")- .select("sortOrder")- .eq("table", customField.table);-- if (sortOrders.error) return sortOrders;- const maxSortOrder = sortOrders.data.reduce((max, item) => {- return Math.max(max, item.sortOrder);- }, 0);-- return client- .from("customField")- .insert([{ ...customField, sortOrder: maxSortOrder + 1 }]);- }- return client- .from("customField")- .update(- sanitize({- ...customField,- updatedBy: customField.updatedBy- })- )- .eq("id", customField.id);- }- }-- export async function updateCustomFieldsSortOrder(- client: SupabaseClient<Database>,- updates: {- id: string;- sortOrder: number;- updatedBy: string;- }[]- ) {- try {- clearCustomFieldsCache();- } finally {- const updatePromises = updates.map(({ id, sortOrder, updatedBy }) =>- client.from("customField").update({ sortOrder, updatedBy }).eq("id", id)- );- return Promise.all(updatePromises);- }- }-- export type IntegrationHealthStatus =- | "healthy"- | "unhealthy"- | "inactive"- | "sync-off";-- type IntegrationHealthFields = {- health: IntegrationHealthStatus;- /** Why an unhealthy check failed, when the integration says. */- healthReason: string | null;- };+ .optional(),+ skipApprovalForPlanningPurchaseOrders: z.boolean().optional(),+ rescheduleToleranceDays: z.number().int().min(0).max(365).optional(),+ defaultPlanningHorizonDays: z+ .number()+ .int()+ .min(0)+ .max(3650)+ .nullable()+ .optional(),+ forecastConsumptionBackwardPeriods: z+ .number()+ .int()+ .min(0)+ .max(52)+ .optional(),+ forecastConsumptionForwardPeriods: z+ .number()+ .int()+ .min(0)+ .max(52)+ .optional(),+ mrpRunTime: z+ .string()+ .regex(/^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/, {+ message: "Choose a time for the daily MRP run"+ })+ .nullable()+ .optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const refused = service.nothingSent(ctx, input);+ if (refused) return refused;+ const {+ locationResponsibleEmployee: location,+ itemGroupResponsibleEmployee: itemGroup,+ mrpRunTime,+ ...settings+ } = input;++ const employees = [+ settings.defaultResponsibleEmployee,+ location?.responsibleEmployee,+ itemGroup?.responsibleEmployee+ ].filter((id): id is string => !!id);+ for (const employeeId of new Set(employees)) {+ if (+ !(await isActiveCompanyEmployee(+ ctx.asCaller.supabase,+ ctx.company.id,+ employeeId+ ))+ ) {+ return ctx.error("rule", "Choose an employee of this company");+ }+ }++ const saved = await service.saveCompanySettings(+ ctx,+ {+ ...settings,+ mrpRunTime:+ mrpRunTime === undefined+ ? undefined+ : mrpRunTime && parseTime(mrpRunTime).toString()+ },+ "Failed to update planning settings"+ );+ if (saved) return saved;++ if (location) {+ const result = await service.setLocationResponsibleEmployee(+ ctx.asCaller.supabase,+ {+ companyId: ctx.company.id,+ locationId: location.locationId,+ employeeId: location.responsibleEmployee,+ userId: ctx.auditUserId+ }+ );+ if (result.error) {+ return ctx.error(+ "internal",+ "Failed to update location ownership",+ result.error+ );+ }+ // No row back: the location is not this company's, or the caller lacks+ // resources_update and row-level security matched nothing.+ if ((result.data?.length ?? 0) === 0) {+ return ctx.error(+ "forbidden",+ "You do not have permission to change this location"+ );+ }+ }+ if (itemGroup) {+ const result = await service.upsertItemPostingGroupResponsibility(+ ctx.asCaller.supabase,+ {+ companyId: ctx.company.id,+ locationId: itemGroup.locationId,+ itemPostingGroupId: itemGroup.itemPostingGroupId,+ employeeId: itemGroup.responsibleEmployee,+ userId: ctx.auditUserId+ }+ );+ if (result.error) {+ return ctx.error(+ "internal",+ "Failed to update item group ownership",+ result.error+ );+ }+ }+ return input;+ }+ });/**- * Connection health, plus `sync-off` for an accounting integration whose- * connection works but whose sync switch is off (a new connection still being- * set up, or one switched off since). A broken connection still reads- * `unhealthy` — that is the more urgent thing to show.- */- export async function getIntegrationHealth(- companyId: string,- integration: Integration- ): Promise<Integration & IntegrationHealthFields> {- const result = await getConnectionHealth(companyId, integration);- if (- result.health === "healthy" &&- (getIntegrationIdsByRole("accounting") as string[]).includes(- integration.id ?? ""- ) &&- !isAccountingSyncEnabled(integration.metadata)- ) {- return { ...result, health: "sync-off" };- }- return result;- }-- async function getConnectionHealth(- companyId: string,- integration: Integration- ): Promise<- Integration &- IntegrationHealthFields & { health: "healthy" | "unhealthy" | "inactive" }- > {- if (!integration.active) {- return {- ...integration,- health: "inactive",- healthReason: null- };+ * Update the company's details.+ *+ * @remarks+ * Writes the company's name, address, time zone, base currency, tax and+ * registration numbers and contact details. Changing the base currency also+ * deletes every exchange-rate override, in the same transaction: an override+ * is denominated in the old base and would rate every new document wrong.+ * The company's cached time zone is dropped, so a new one applies at once.+ *+ * @mcp+ */+ export const updateCompanyDetails = defineServiceFn({+ input: companyValidator,+ permission: { update: "settings" },+ async run(ctx, company) {+ const existing = await ctx.asCaller.supabase+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", ctx.company.id)+ .single();++ const baseCurrencyChanged =+ !!existing.data?.baseCurrencyCode &&+ existing.data.baseCurrencyCode !== company.baseCurrencyCode;++ if (baseCurrencyChanged) {+ try {+ await service.updateCompanyWithBaseCurrencyChange(+ ctx.asSystem.pg,+ ctx.company.id,+ { ...company, updatedBy: ctx.auditUserId }+ );+ } catch (err) {+ return ctx.error("internal", "Failed to update company", err);+ }+ } else {+ const update = await service.updateCompany(+ ctx.asCaller.supabase,+ ctx.company.id,+ { ...company, updatedBy: ctx.auditUserId }+ );+ if (update.error) {+ return ctx.error("internal", "Failed to update company", update.error);+ }+ }++ await invalidateCompanyTimeZone(ctx.company.id);+ return { id: ctx.company.id };}+ });+ /**+ * Create a company in a new company group, for the caller.+ *+ * @remarks+ * Inserts the company, seeds it (chart of accounts, sequences, the caller's+ * employee record and permissions), creates its Headquarters location at the+ * company's address and the caller's job there. In a controlled environment+ * audit logging is on from the start. Returns the new company and its group,+ * so the caller can switch to it.+ */+ export const createCompany = defineServiceFn({+ input: companyValidator,+ permission: { update: ["settings", "users"] },+ async run(ctx, company) {+ const client = ctx.asSystem.supabase;+ const inserted = await service.insertCompany(client, company);+ if (inserted.error || !inserted.data?.id) {+ return ctx.error("internal", "Failed to create company", inserted.error);+ }+ const companyId = inserted.data.id;- const serverHooks = getIntegrationServerHooks(integration.id!);- const config = getIntegrationConfigById(integration.id as IntegrationID);- const healthcheck = serverHooks?.onHealthcheck ?? config?.onHealthcheck;+ const seed = await invokePosting(+ { db: ctx.asSystem.pg, companyId, userId: ctx.auditUserId },+ "seed-company",+ { identityOnly: false },+ service.seedCompany+ );+ if (seed.error) {+ return ctx.error("internal", "Failed to seed company", seed.error);+ }- if (!healthcheck) {- return {- ...integration,- health: "healthy",- healthReason: null- };+ const { baseCurrencyCode: _, ...location } = company;+ const headquarters = await service.createHeadquarters(+ ctx,+ companyId,+ location+ );+ if (headquarters) return headquarters;++ const { data } = await client+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();+ return { companyId, companyGroupId: data?.companyGroupId ?? "" };}+ });- const key = `integrations:${companyId}:${integration.id}:health`;+ /**+ * Create a company in the caller's company group.+ *+ * @remarks+ * Open to internal users only, for now. The parent must be a company of the+ * caller's own group: seeding joins the new company to its parent's group,+ * so a parent from another group would place it inside another tenant. Then+ * as for a new company: insert, seed, the Headquarters location and the+ * caller's job there.+ */+ export const createSubsidiary = defineServiceFn({+ input: subsidiaryValidator,+ permission: { create: "settings" },+ async run(ctx, subsidiary) {+ const refused = await service.refuseUnlessInternalUser(ctx);+ if (refused) return refused;++ const { id: _, parentCompanyId, ...company } = subsidiary;+ const client = ctx.asSystem.supabase;++ if (parentCompanyId) {+ const parent = await client+ .from("company")+ .select("id")+ .eq("id", parentCompanyId)+ .eq("companyGroupId", ctx.company.groupId)+ .maybeSingle();+ if (parent.error || !parent.data) {+ return ctx.error("notFound", "Parent company not found", parent.error);+ }+ }- const cached = await redis.get(key);+ const inserted = await service.insertCompany(client, company);+ if (inserted.error || !inserted.data?.id) {+ return ctx.error("internal", "Failed to create company", inserted.error);+ }+ const companyId = inserted.data.id;- // Only cache healthy status- if (cached === "1") {- return {- ...integration,- health: "healthy",- healthReason: null- };- }+ const seed = await invokePosting(+ { db: ctx.asSystem.pg, companyId, userId: ctx.auditUserId },+ "seed-company",+ { parentCompanyId, identityOnly: false },+ service.seedCompany+ );+ if (seed.error) {+ return ctx.error("internal", "Failed to seed company", seed.error);+ }- // Resolve vaulted secrets back into the metadata before the healthcheck- // builds its provider/client. Since the secret-vault refactor, credentials no- // longer live in the plaintext `metadata` column, so an unresolved metadata- // authenticates with nothing and every secret-bearing healthcheck (Rillet,- // Xero, Email) would read "unhealthy". `resolveIntegrationSecrets` looks up- // the row's `secretRef` itself (the `integrations` view doesn't expose it) and- // throws when the secret can't be read — treat that as unhealthy rather than- // crashing the whole settings page.- let resolvedMetadata: Record<string, any>;- try {- resolvedMetadata = (await resolveIntegrationSecrets(- getCarbonServiceRole(),+ const { baseCurrencyCode: __, ...location } = company;+ const headquarters = await service.createHeadquarters(+ ctx,companyId,- integration.id!,- (integration.metadata as Record<string, any>) ?? {}- )) as Record<string, any>;- } catch {- return {- ...integration,- health: "unhealthy",- healthReason: null- };+ location+ );+ return headquarters ?? { companyId };}+ });- const result = await (- healthcheck as (- companyId: string,- metadata: Record<string, any>- ) => Promise<boolean | IntegrationHealthcheckResult>- )(companyId, resolvedMetadata);- const healthy = typeof result === "boolean" ? result : result.healthy;- const reason = typeof result === "boolean" ? null : (result.reason ?? null);-- await redis.set(key, healthy ? "1" : "0", "EX", INTEGRATION_CACHE_TTL * 5); // Cache for 5 hours-- return {- ...integration,- health: healthy ? "healthy" : "unhealthy",- healthReason: healthy ? null : reason- };- }-- export async function getIntegrationsWithHealth(- client: SupabaseClient<Database>,- companyId: string- ) {- const results = await client- .from("integrations")- .select("*")- .eq("companyId", companyId);-- if (results.error) return results;-- const integrations = results.data;-- const withHealth = await Promise.all(- integrations.map((i) => getIntegrationHealth(companyId, i))- );-- return {- data: withHealth,- error: null- };- }-- export async function invalidateIntegrationHealthCache(- integrationId: string,- companyId: string- ) {- const key = `integrations:${companyId}:${integrationId}:health`;-- return await redis.del(key);- }-- // Server-only (needs the service-role client for the Vault RPC). Lives here rather- // than in settings.service.ts because that file is re-exported by the client barrel;- // a client.server import there would leak the service-role client into the browser- // bundle. Reached by the Carbon API registry (api+/v1+/lib/registry.server.ts),- // which imports this module server-side.- export async function updateIntegrationMetadata(- client: SupabaseClient<Database>,- companyId: string,- integrationId: string,- metadata: any,- updatedBy?: string- ) {- if (integrationId === "ramp") {- try {- const data = await patchRampSettings(getCarbonServiceRole(), companyId, {- metadata: metadata as Record<string, unknown>,- updatedBy- });- await clearCompanyIntegrationCache(companyId);- return { data, error: null };- } catch (error) {- return { data: null, error };+ /**+ * Update a company of the caller's company group.+ *+ * @remarks+ * Open to internal users only, for now. Writes the company's details and its+ * parent, then drops its cached time zone.+ */+ export const updateSubsidiaryDetails = defineServiceFn({+ input: subsidiaryValidator.safeExtend({ id: z.string() }),+ permission: { update: "settings" },+ async run(ctx, { id, ...subsidiary }) {+ const refused = await service.refuseUnlessInternalUser(ctx);+ if (refused) return refused;++ const result = await service.updateSubsidiary(ctx.asCaller.supabase, id, {+ ...subsidiary,+ updatedBy: ctx.auditUserId+ });+ if (result.error) {+ return ctx.error("internal", "Failed to update subsidiary", result.error);}+ await invalidateCompanyTimeZone(id);+ return { id };}-- if (isOnshapeOAuthIntegrationId(integrationId)) {- try {- const data = await patchOnshapeSettings(- getCarbonServiceRole(),- companyId,- integrationId,- { metadata: metadata as Record<string, unknown>, updatedBy }- );- await clearCompanyIntegrationCache(companyId);- return { data, error: null };- } catch (error) {- return { data: null, error };- }- }-- // Split secret material out to Supabase Vault; only the non-secret config is- // written to the column. The row already exists (this is an update), so vault- // FIRST (fail-closed: if the vault write fails, the plaintext is left intact- // rather than stripped-and-lost), then write the stripped config.- const { config, secrets } = splitSecrets(integrationId, metadata);-- if (Object.keys(secrets).length > 0) {- const serviceRole = getCarbonServiceRole();- const { error } = await serviceRole.rpc("upsert_integration_secret", {- p_company_id: companyId,- p_integration_id: integrationId,- p_secret: secrets as never+ });+ /**+ * Create or update a printer route.+ *+ * @remarks+ * A printer route is a printer the company prints to: its name, format (ZPL+ * labels or PDF documents), media size, URL and optional API key, location+ * and template. With an `id` the company's route is updated, without one a+ * route is created. The cached printer routing is dropped, so the change+ * applies to the next print. Not published: the server POSTs to the URL it+ * saves, so an API caller could aim it at any address.+ */+ export const savePrinterRoute = defineServiceFn({+ input: printerRouteValidator,+ permission: { update: "settings" },+ async run(ctx, route) {+ const result = await upsertPrinterRoute(ctx.asCaller.supabase, {+ id: route.id || undefined,+ companyId: ctx.company.id,+ name: route.name,+ format: route.format,+ mediaSizeId: route.mediaSizeId || null,+ printerUrl: route.printerUrl,+ apiKey: route.apiKey || null,+ locationId: route.locationId || null,+ templateId: route.templateId || null});- if (error) {- return { data: null, error };+ if (result.error) {+ return ctx.error(+ "internal",+ "Failed to save printer route",+ result.error+ );}+ await invalidatePrinterCache(ctx.company.id);+ return { created: !route.id };}+ });- return client- .from("companyIntegration")- .update(- sanitize({- metadata: config as Json,- updatedAt: new Date().toISOString(),- updatedBy- })- )- .eq("companyId", companyId)- .eq("id", integrationId);- }-- /**- * Where a sync operation's `entityId` resolves to a human-readable document- * number, per `entityType` (the keys of the accounting sync engine's- * `ENTITY_DEFINITIONS`). `employee` and `inventoryAdjustment` are absent on- * purpose: the first is a `user` id with no readable column of its own, the- * second an `itemLedger` row with no document number at all.- */- const SYNC_ENTITY_READABLE_ID_SOURCES: Record<- string,- { table: string; column: string }- > = {- customer: { table: "customer", column: "name" },- vendor: { table: "supplier", column: "name" },- item: { table: "item", column: "readableId" },- purchaseOrder: { table: "purchaseOrder", column: "purchaseOrderId" },- bill: { table: "purchaseInvoice", column: "invoiceId" },- salesOrder: { table: "salesOrder", column: "salesOrderId" },- invoice: { table: "salesInvoice", column: "invoiceId" },- payment: { table: "payment", column: "paymentId" },- charge: { table: "charge", column: "chargeId" },- reimbursement: { table: "reimbursement", column: "reimbursementId" },- journalEntry: { table: "journal", column: "journalEntryId" },- // One table, two entity types — the sweep splits `memo` by party.- creditMemo: { table: "memo", column: "memoId" },- supplierCredit: { table: "memo", column: "memoId" }- };+ /**+ * Send a test label to a printer route.+ *+ * @remarks+ * Prints one ZPL test label, sized to the route's media, on the company's+ * printer route. Only a ZPL route with a media size can print one. The+ * printer must answer within 10 seconds.+ */+ export const testPrinterRoute = defineServiceFn({+ input: z.object({ routeId: z.string().min(1) }),+ permission: { update: "settings" },+ async run(ctx, { routeId }) {+ const { data: route } = await ctx.asCaller.supabase+ .from("printerRoute")+ .select("printerUrl, format, mediaSizeId, apiKey")+ .eq("id", routeId)+ .eq("companyId", ctx.company.id)+ .single();+ if (!route) return ctx.error("notFound", "Printer route not found");++ const testLabel = service.generateTestLabel(+ route.format,+ route.mediaSizeId+ );+ if (!testLabel) {+ return ctx.error(+ "rule",+ "Test print is only supported for ZPL label printers with a media size configured."+ );+ }- const JOURNAL_REVERSAL_SUFFIX = ":reversal";- const DAILY_CONSOLIDATION_PREFIX = "daily:";+ const headers: Record<string, string> = {+ "Content-Type": "application/octet-stream"+ };+ if (route.apiKey) headers["X-API-Key"] = route.apiKey;- /** The fields of a sync operation this resolver reads. */- type SyncOperationReference = {- integration: string;- entityType: string;- entityId: string;- direction: string;- };+ try {+ const response = await fetch(route.printerUrl, {+ method: "POST",+ headers,+ body: testLabel,+ signal: AbortSignal.timeout(10_000)+ });+ if (!response.ok) {+ return ctx.error(+ "unavailable",+ `Print failed (${response.status} ${response.statusText})`+ );+ }+ } catch (err) {+ return ctx.error(+ "unavailable",+ `Print failed: ${err instanceof Error ? err.message : "Unknown error"}`,+ err+ );+ }+ return { routeId };+ }+ });/**- * The lookup key, built identically here and in `SyncActivity`'s- * `getEntityReference`.- */- function syncOperationReadableIdKey(operation: {- entityType: string;- entityId: string;- }) {- return `${operation.entityType}:${operation.entityId}`;- }-- /**- * A pulled operation is keyed by the PROVIDER's remote id, so it only- * reaches a Carbon row through `externalIntegrationMapping`. One query for- * the whole page, keyed back by `entityType:externalId`.- */- async function getPulledEntityIds(- client: SupabaseClient<Database>,- companyId: string,- operations: SyncOperationReference[]- ): Promise<Map<string, string>> {- const pulled = operations.filter(- (operation) =>- operation.direction === "pull-from-accounting" &&- operation.entityType in SYNC_ENTITY_READABLE_ID_SOURCES- );- if (pulled.length === 0) return new Map();-- const { data, error } = await client- .from("externalIntegrationMapping")- .select("entityType, entityId, externalId")- .eq("companyId", companyId)- .in("integration", [- ...new Set(pulled.map((operation) => operation.integration))- ])- .in("entityType", [- ...new Set(pulled.map((operation) => operation.entityType))- ])- .in("externalId", [- ...new Set(pulled.map((operation) => operation.entityId))- ]);+ * Delete a printer route.+ *+ * @remarks+ * Deletes the company's printer route, then clears it from every printer+ * assignment that named it (a location's default, its shipping and receiving+ * printers, and its work centers), so no assignment points at a printer that+ * is gone. The cached printer routing is dropped.+ *+ * @mcp destructive+ */+ export const removePrinterRoute = defineServiceFn({+ input: z.object({ id: z.string().min(1) }),+ permission: { update: "settings" },+ async run(ctx, { id }) {+ const client = ctx.asCaller.supabase;+ const result = await deletePrinterRoute(client, id, ctx.company.id);+ if (result.error) {+ return ctx.error(+ "internal",+ "Failed to delete printer route",+ result.error+ );+ }- if (error || !data) return new Map();-- return new Map(- data.map((row) => [`${row.entityType}:${row.externalId}`, row.entityId])- );- }-- /**- * Resolve one page of sync operations to the document numbers a human reads- * — `PO000001` rather than `po_6UyRfXggN6YrmCSauBaVf1`. One query per entity- * type on the page (plus one for pulled records' mappings), never one per- * row.- *- * Silently incomplete by design, and the caller falls back to the raw id: a- * pulled record that never landed a Carbon row has only the provider's- * remote id, a pulled payment's id is a composite of two remote ids, and a- * daily-consolidation journal marker backs no row at all.- *- * `recordId` is the CARBON row id — the same as `entityId` for a push, the- * mapped id for a pull — so the table's link goes somewhere real instead of- * to the provider's remote id.- */- export async function getSyncOperationReadableIds(- client: SupabaseClient<Database>,- companyId: string,- operations: SyncOperationReference[]- ): Promise<Record<string, { label: string; recordId: string }>> {- const pulledEntityIds = await getPulledEntityIds(- client,- companyId,- operations- );-- // entityType -> the ids to look up, mapped back to the operation keys they- // came from (a journal reversal's id is the journal's id plus a suffix, so- // one row can answer two keys).- const byEntityType = new Map<string, Map<string, string[]>>();-- for (const operation of operations) {- if (!(operation.entityType in SYNC_ENTITY_READABLE_ID_SOURCES)) continue;-- let lookupId =- pulledEntityIds.get(syncOperationReadableIdKey(operation)) ??- operation.entityId;-- if (operation.entityType === "journalEntry") {- if (lookupId.startsWith(DAILY_CONSOLIDATION_PREFIX)) continue;- if (lookupId.endsWith(JOURNAL_REVERSAL_SUFFIX)) {- lookupId = lookupId.slice(0, -JOURNAL_REVERSAL_SUFFIX.length);+ const { data: existing } = await getPrintingSettings(+ client,+ ctx.company.id+ );+ const current = existing?.printing as PrintingSettings | null;+ if (current?.assignments) {+ let dirty = false;+ const assignments = { ...current.assignments };+ for (const [locationId, location] of Object.entries(assignments)) {+ if (!location) continue;+ const next = { ...location };+ if (next.defaultPrinterRouteId === id) {+ next.defaultPrinterRouteId = null;+ dirty = true;+ }+ if (next.shipping?.printerRouteId === id) {+ next.shipping = { ...next.shipping, printerRouteId: null };+ dirty = true;+ }+ if (next.receiving?.printerRouteId === id) {+ next.receiving = { ...next.receiving, printerRouteId: null };+ dirty = true;+ }+ if (next.workCenters) {+ const workCenters = { ...next.workCenters };+ for (const [workCenterId, workCenter] of Object.entries(+ workCenters+ )) {+ if (workCenter?.printerRouteId === id) {+ workCenters[workCenterId] = {+ ...workCenter,+ printerRouteId: null+ };+ dirty = true;+ }+ }+ next.workCenters = workCenters;+ }+ assignments[locationId] = next;+ }+ if (dirty) {+ await updatePrintingSettings(client, ctx.company.id, {+ ...current,+ assignments+ });}- } else if (lookupId.includes(":")) {- // A pulled payment's composite remote id — no Carbon row behind it.- continue;}- const ids = byEntityType.get(operation.entityType) ?? new Map();- ids.set(lookupId, [- ...(ids.get(lookupId) ?? []),- syncOperationReadableIdKey(operation)- ]);- byEntityType.set(operation.entityType, ids);- }-- if (byEntityType.size === 0) return {};-- const results = await Promise.all(- Array.from(byEntityType.entries()).map(async ([entityType, ids]) => {- const source = SYNC_ENTITY_READABLE_ID_SOURCES[entityType]!;- // The table and column are chosen from the const map above, never from- // request input — but they are values, so the select string can't be- // typed. Cast, the same way the tie-out read in the route does.- const { data, error } = (await (client.from(source.table as any) as any)- .select(`id, ${source.column}`)- .eq("companyId", companyId)- .in("id", Array.from(ids.keys()))) as {- data: { id: string }[] | null;- error: unknown;- };-- if (error || !data)- return [] as [string, { label: string; recordId: string }][];-- return data.flatMap((row) => {- const value = (row as Record<string, unknown>)[source.column];- if (typeof value !== "string" || value.length === 0) return [];- return (ids.get(row.id) ?? []).map(- (key): [string, { label: string; recordId: string }] => [- key,- {- label: key.endsWith(JOURNAL_REVERSAL_SUFFIX)- ? `${value} (reversal)`- : value,- recordId: row.id- }- ]- );- });- })- );+ await invalidatePrinterCache(ctx.company.id);+ return { id };+ }+ });- return Object.fromEntries(results.flat());- }+ /**+ * Assign a printer to a location, one of its contexts or a work center.+ *+ * @remarks+ * Sets which printer route a location prints to by default, for shipping,+ * for receiving, or at one of its work centers (`contextId` names the work+ * center), and whether it prints automatically. An empty route clears the+ * assignment, so the context falls back to the location's default. The+ * cached printer routing is dropped.+ *+ * @mcp+ */+ export const assignPrinter = defineServiceFn({+ input: updateAssignmentValidator,+ permission: { update: "settings" },+ async run(ctx, assignment) {+ const client = ctx.asCaller.supabase;+ const { data: existing } = await getPrintingSettings(+ client,+ ctx.company.id+ );+ const current = (existing?.printing as PrintingSettings | null) ?? {+ assignments: {}+ };+ const updated = setContextAssignment(+ current,+ assignment.locationId,+ assignment.context,+ {+ printerRouteId: assignment.printerRouteId || null,+ autoPrint: assignment.autoPrint+ },+ assignment.contextId+ );++ const result = await updatePrintingSettings(+ client,+ ctx.company.id,+ updated+ );+ if (result.error) {+ return ctx.error(+ "internal",+ "Failed to update the printer assignment",+ result.error+ );+ }+ await invalidatePrinterCache(ctx.company.id);+ return { locationId: assignment.locationId };+ }+ });++ /**+ * Print a print job again.+ *+ * @remarks+ * Queues a new print job with the company's original job's content, to its+ * printer or to `printerUrl` when given, and starts its delivery. A job still+ * generating has no content and cannot be reprinted. Not published: the+ * server POSTs to `printerUrl`, so an API caller could aim it at any address.+ */+ export const reprintPrintJob = defineServiceFn({+ input: reprintValidator,+ permission: { update: "settings" },+ async run(ctx, { printJobId, printerUrl }) {+ const client = ctx.asCaller.supabase;+ const [original, originalMeta] = await Promise.all([+ getPrintJobContent(client, printJobId, ctx.company.id),+ getPrintJob(client, printJobId, ctx.company.id)+ ]);+ if (+ original.error ||+ !original.data ||+ originalMeta.error ||+ !originalMeta.data+ ) {+ return ctx.error(+ "notFound",+ "Failed to load print job",+ original.error ?? originalMeta.error+ );+ }+ if (!original.data.content || !original.data.contentType) {+ return ctx.error("rule", "Cannot reprint a job that is still generating");+ }++ const job = await createPrintJob(client, {+ companyId: ctx.company.id,+ contentType: original.data.contentType as "zpl" | "pdf",+ content: original.data.content,+ printerUrl: printerUrl || originalMeta.data.printerUrl,+ sourceDocument: originalMeta.data.sourceDocument,+ sourceDocumentId: originalMeta.data.sourceDocumentId,+ sourceDocumentReadableId:+ originalMeta.data.sourceDocumentReadableId ?? undefined,+ description: originalMeta.data.description,+ status: "queued",+ origin: "reprint",+ createdBy: ctx.auditUserId+ });+ if (job.error || !job.data) {+ return ctx.error("internal", "Failed to create reprint", job.error);+ }++ try {+ await trigger("print-job-deliver", {+ printJobId: job.data.id,+ companyId: ctx.company.id+ });+ } catch (err) {+ logger.error("Failed to trigger delivery", {+ companyId: ctx.company.id,+ error: err+ });+ }+ return { printJobId: job.data.id };+ }+ });++ /**+ * Delete a print job.+ *+ * @remarks+ * Deletes the company's print job from the print queue history.+ *+ * @mcp destructive+ */+ export const deletePrintJob = defineServiceFn({+ input: z.object({ printJobId: z.string().min(1) }),+ permission: { update: "settings" },+ async run(ctx, { printJobId }) {+ const { error } = await ctx.asCaller.supabase+ .from("printJob")+ .delete()+ .eq("id", printJobId)+ .eq("companyId", ctx.company.id);+ if (error) return ctx.error("internal", "Failed to delete job", error);+ return { id: printJobId };+ }+ });++ /** What a print job printed: its ZPL or PDF content. */+ export const viewPrintJobContent = defineServiceFn({+ input: z.object({ printJobId: z.string().min(1) }),+ permission: { update: "settings" },+ async run(ctx, { printJobId }) {+ const content = await getPrintJobContent(+ ctx.asCaller.supabase,+ printJobId,+ ctx.company.id+ );+ if (content.error || !content.data) {+ return ctx.error("notFound", "Failed to load content", content.error);+ }+ return {+ printJobId: content.data.id,+ content: content.data.content,+ contentType: content.data.contentType+ };+ }+ });++ /**+ * Save a document's layout.+ *+ * @remarks+ * Writes the company's template for one document type: its blocks, theme,+ * settings and the header and footer sections it uses. The logo and header+ * layout (`headerConfig`) is edited with the template but lives on the+ * company-wide header section, so it is saved onto that section first, with+ * the section's name and content kept, and applies wherever the header is+ * used. A built-in header section is forked into the company's own copy.+ *+ * @mcp+ */+ export const saveDocumentTemplate = defineServiceFn({+ input: z.object({+ documentType: documentTemplateTypeSchema,+ blocks: z.array(blockSchema),+ theme: themeSchema,+ settings: documentSettingsSchema,+ headerSectionId: z.string().optional(),+ footerSectionId: z.string().optional(),+ headerConfig: sectionConfigSchema.optional()+ }),+ permission: { update: "settings" },+ async run(ctx, template) {+ const client = ctx.asCaller.supabase;+ const { headerConfig, headerSectionId } = template;++ if (headerConfig && headerSectionId) {+ const resolved = await service.resolveSections(client, ctx.company.id, [+ headerSectionId+ ]);+ const header = resolved[headerSectionId];+ const section = await service.upsertDocumentSection(client, {+ id: headerSectionId,+ companyId: ctx.company.id,+ name: header?.name ?? "Default Header",+ placement: "header",+ content: (header?.content ?? {+ type: "doc",+ content: []+ }) as JSONContent,+ config: headerConfig as Record<string, unknown>,+ createdBy: ctx.auditUserId,+ updatedBy: ctx.auditUserId+ });+ if (section.error) {+ return ctx.error("internal", "Failed to save header", section.error);+ }+ }++ const upsert = await service.upsertDocumentTemplate(client, {+ companyId: ctx.company.id,+ documentType: template.documentType,+ blocks: template.blocks as DocumentBlock[],+ theme: template.theme as DocumentTheme,+ settings: template.settings as DocumentSettings,+ headerSectionId: headerSectionId || null,+ footerSectionId: template.footerSectionId || null,+ createdBy: ctx.auditUserId,+ updatedBy: ctx.auditUserId+ });+ if (upsert.error) {+ return ctx.error(+ "internal",+ "Failed to save document layout",+ upsert.error+ );+ }+ return { documentType: template.documentType };+ }+ });++ /**+ * Create or update a shared document section.+ *+ * @remarks+ * A section is company-wide rich text placed in a document's header, body or+ * footer. With an `id` the section is updated; editing a built-in section+ * forks it into the company's own copy under the same id, which then+ * overrides the built-in everywhere it is used. Without an `id` a section is+ * created.+ *+ * @mcp+ */+ export const saveDocumentSection = defineServiceFn({+ input: z.object({+ id: z.string().optional(),+ name: z.string().min(1),+ placement: documentSectionPlacementSchema,+ content: z.record(z.string(), z.unknown()),+ config: sectionConfigSchema.optional()+ }),+ permission: { update: "settings" },+ async run(ctx, { id, name, placement, content, config }) {+ const result = await service.upsertDocumentSection(ctx.asCaller.supabase, {+ id,+ companyId: ctx.company.id,+ name,+ placement,+ content: content as JSONContent,+ config: config as Record<string, unknown> | undefined,+ ...(id ? { updatedBy: ctx.auditUserId } : { createdBy: ctx.auditUserId })+ });+ if (result.error) {+ return ctx.error("internal", "Failed to save section", result.error);+ }+ return { saved: true };+ }+ });++ /**+ * Delete a shared document section.+ *+ * @remarks+ * Templates refer to their header and footer sections without a foreign+ * key: a template that used the deleted section renders without it.+ *+ * @mcp destructive+ */+ export const removeDocumentSection = defineServiceFn({+ input: z.object({ id: z.string().min(1) }),+ permission: { update: "settings" },+ async run(ctx, { id }) {+ const result = await service.deleteDocumentSection(+ ctx.asCaller.supabase,+ id,+ ctx.company.id+ );+ if (result.error) {+ return ctx.error("internal", "Failed to delete section", result.error);+ }+ return { id };+ }+ });++ const apiKeyFields = {+ name: apiKeyValidator.shape.name,+ expiresAt: apiKeyValidator.shape.expiresAt,+ /** Per module, the actions the key may run: `{ "sales": ["view"] }`. */+ scopes: z.record(z.string(), z.array(z.string()))+ };+ /**+ * Create an API key.+ *+ * @remarks+ * Generates the key, stores only its hash and last five characters, and+ * returns the raw key once: it can never be read back. API keys are a+ * Business plan feature.+ */+ export const createApiKey = defineServiceFn({+ input: z.object(apiKeyFields),+ permission: { update: "users" },+ async run(ctx, { name, scopes, expiresAt }) {+ const rawKey = `crbn_${nanoid()}`;+ let created: Awaited<ReturnType<typeof upsertApiKey>>;+ try {+ created = await upsertApiKey(ctx.asCaller.supabase, {+ name,+ scopes,+ expiresAt: expiresAt || undefined,+ rawKey,+ keyHash: hashApiKey(rawKey),+ keyPreview: rawKey.slice(-5),+ companyId: ctx.company.id,+ createdBy: ctx.auditUserId+ });+ } catch (err) {+ return service.apiKeysEntitlement(ctx, err);+ }+ const key = created.data && "key" in created.data ? created.data.key : null;+ if (created.error || !key) {+ return ctx.error("internal", "Failed to create API key", created.error);+ }+ return { key };+ }+ });++ /**+ * Update an API key's name, scopes and expiry.+ *+ * @remarks+ * The key itself never changes. Its cached authentication is dropped, so a+ * narrower scope or an earlier expiry applies at once.+ */+ export const updateApiKey = defineServiceFn({+ input: z.object({ id: z.string().min(1), ...apiKeyFields }),+ permission: { update: "users" },+ async run(ctx, { id, name, scopes, expiresAt }) {+ let updated: Awaited<ReturnType<typeof upsertApiKey>>;+ try {+ updated = await upsertApiKey(ctx.asCaller.supabase, {+ id,+ name,+ scopes,+ expiresAt: expiresAt || undefined+ });+ } catch (err) {+ return service.apiKeysEntitlement(ctx, err);+ }+ if (updated.error) {+ return ctx.error("internal", "Failed to update API key", updated.error);+ }+ // A scope or expiry edit must not keep authenticating from the 30s cache.+ await service.invalidateApiKeyCache(id, ctx.company.id);+ return { id };+ }+ });++ /**+ * Delete an API key.+ *+ * @remarks+ * The key stops authenticating: its cached authentication is dropped before+ * the delete (the key's hash cannot be read once the row is gone) and again+ * after it, in case a request re-cached the live row in between.+ */+ export const revokeApiKey = defineServiceFn({+ input: z.object({ id: z.string().min(1) }),+ permission: { update: "users" },+ async run(ctx, { id }) {+ const keyHash = await service.invalidateApiKeyCache(id, ctx.company.id);+ let deleted: Awaited<ReturnType<typeof deleteApiKey>>;+ try {+ deleted = await deleteApiKey(ctx.asCaller.supabase, id);+ } catch (err) {+ return service.apiKeysEntitlement(ctx, err);+ }+ if (deleted.error) {+ return ctx.error("internal", "Failed to delete API key", deleted.error);+ }+ if (keyHash) await bustApiKeyCache(keyHash);+ return { id };+ }+ });++ /**+ * Disconnect an integration.+ *+ * @remarks+ * Marks the company's integration inactive, runs the integration's own+ * uninstall step (removing its webhooks, for example) and drops its cached+ * health. Integrations outside the always-available set need the plan's+ * integrations feature.+ *+ * @mcp destructive+ */+ export const deactivateCompanyIntegration = defineServiceFn({+ input: z.object({ id: z.string().min(1) }),+ permission: { update: "settings" },+ async run(ctx, { id }) {+ if (+ !isIntegrationWhitelisted(id) &&+ !(await companyHasFeature(ctx.asCaller.supabase, ctx.company.id, {+ feature: "INTEGRATIONS"+ }))+ ) {+ return ctx.error("entitlement", "Integrations require an upgraded plan");+ }++ const integration = availableIntegrations.find((i) => i.id === id);+ if (!integration) return ctx.error("notFound", "Integration not found");++ const update = await service.deactivateIntegration(ctx.asCaller.supabase, {+ id,+ companyId: ctx.company.id,+ updatedBy: ctx.auditUserId+ });+ if (update.error) {+ return ctx.error(+ "internal",+ "Failed to disconnect integration",+ update.error+ );+ }++ const hooks = getIntegrationServerHooks(id);+ if (hooks?.onUninstall) await hooks.onUninstall(ctx.company.id);++ await service.invalidateIntegrationHealthCache(id, ctx.company.id);+ return { id, name: integration.name };+ }+ });++ /**+ * Turn audit logging on.+ *+ * @remarks+ * Records every change to the company's audited tables from now on. Audit+ * logging is a Business plan feature.+ *+ * @mcp+ */+ export const enableCompanyAuditLog = defineServiceFn({+ input: z.object({}),+ permission: { update: "settings" },+ async run(ctx) {+ try {+ await enableAuditLog(ctx.asCaller.supabase, ctx.company.id);+ } catch (err) {+ if (err instanceof EntitlementError) {+ return ctx.error(+ "entitlement",+ "Upgrade to Business to enable audit logging"+ );+ }+ return ctx.error("internal", "Failed to enable audit logging", err);+ }+ return { auditLogEnabled: true };+ }+ });++ /**+ * Turn audit logging off.+ *+ * @remarks+ * Stops recording changes; the log written so far is kept. A controlled+ * environment cannot turn audit logging off.+ *+ * @mcp destructive+ */+ export const disableCompanyAuditLog = defineServiceFn({+ input: z.object({}),+ permission: { update: "settings" },+ async run(ctx) {+ if (CONTROLLED_ENVIRONMENT) {+ return ctx.error(+ "rule",+ "Audit logging cannot be disabled in a controlled environment"+ );+ }+ try {+ await disableAuditLog(ctx.asCaller.supabase, ctx.company.id);+ } catch (err) {+ return ctx.error("internal", "Failed to disable audit logging", err);+ }+ return { auditLogEnabled: false };+ }+ });++ /** A signed URL that downloads one of the company's audit log archives. */+ export const getAuditArchiveDownloadUrl = defineServiceFn({+ input: z.object({ archiveId: z.string().min(1) }),+ permission: { update: "settings" },+ async run(ctx, { archiveId }) {+ try {+ const url = await getArchiveDownloadUrl(+ ctx.asSystem.supabase,+ archiveId,+ ctx.company.id+ );+ return { url };+ } catch (err) {+ return ctx.error("internal", "Failed to generate download URL", err);+ }+ }+ });++ /** A Stripe billing portal session for the company, for its subscription. */+ export const getBillingPortalUrl = defineServiceFn({+ input: z.object({}),+ permission: { update: "settings" },+ async run(ctx) {+ try {+ const plans = await ctx.asCaller.supabase+ .from("plan")+ .select("stripePriceId")+ .eq("userBasedPricing", true);+ const priceIds = plans.data?.map((plan) => plan.stripePriceId);+ const url = await getBillingPortalRedirectUrl({+ companyId: ctx.company.id,+ priceIds+ });+ return { url };+ } catch (err) {+ return ctx.error("internal", "Failed to access billing portal", err);+ }+ }+ });++ /**+ * Transfer ownership of the company group to another user.+ *+ * @remarks+ * The owner holds billing and the group's administrative settings.+ */+ export const transferCompanyOwnership = defineServiceFn({+ input: z.object({ newOwnerId: z.string().min(1) }),+ permission: { update: "settings" },+ async run(ctx, { newOwnerId }) {+ const { error } = await ctx.asCaller.supabase+ .from("companyGroup")+ .update({ ownerId: newOwnerId })+ .eq("id", ctx.company.groupId);+ if (error) {+ return ctx.error("internal", "Failed to transfer ownership", error);+ }+ return { ownerId: newOwnerId };+ }+ });++ /**+ * Set the tags of some records of one table.+ *+ * @remarks+ * Replaces the `tags` of each record. Row-level security decides which+ * records the caller may change.+ */+ export const setRecordTags = defineServiceFn({+ input: z.object({+ table: z.string().min(1),+ ids: z.array(z.string()),+ tags: z.array(z.string())+ }),+ permission: {},+ async run(ctx, { table, ids, tags }) {+ const { error } = await ctx.asCaller.supabase+ // @ts-expect-error: the table is the caller's, for any taggable record+ .from(table)+ .update(+ unchecked({+ tags,+ updatedBy: ctx.auditUserId,+ updatedAt: datetime.timestamp()+ })+ )+ .in(unchecked("id"), ids);+ if (error) return ctx.error("internal", "Failed to update tags", error);+ return { ids };+ }+ });++ /**+ * Set the custom field values of some records of one table.+ *+ * @remarks+ * Replaces the `customFields` of each record. Row-level security decides+ * which records the caller may change.+ */+ export const setRecordCustomFields = defineServiceFn({+ input: z.object({+ table: z.string().min(1),+ ids: z.array(z.string()),+ customFields: z.record(z.string(), z.unknown())+ }),+ permission: {},+ async run(ctx, { table, ids, customFields }) {+ const { error } = await ctx.asCaller.supabase+ // @ts-expect-error: the table is the caller's, for any record with custom fields+ .from(table)+ .update(+ unchecked({+ customFields,+ updatedBy: ctx.auditUserId,+ updatedAt: datetime.timestamp()+ })+ )+ .in(unchecked("id"), ids);+ if (error) {+ return ctx.error("internal", "Failed to update custom fields", error);+ }+ return { ids };+ }+ });++ /**+ * Retry, re-send or skip accounting sync operations.+ *+ * @remarks+ * "Pending" queues each operation for sync again (retry, re-send);+ * "Skipped" drops it from the inbox. Each operation's transition is checked+ * against its current status, and one that cannot move is reported.+ *+ * @mcp+ */+ export const transitionSyncOperations = defineServiceFn({+ input: z.object({+ ids: z+ .array(z.string().min(1))+ .min(1, { message: "No operations selected" })+ .max(500, { message: "Select at most 500 operations at once" }),+ to: z.enum(["Pending", "Skipped"])+ }),+ permission: { update: "settings" },+ async run(ctx, { ids, to }) {+ const result = await service.transitionSyncOperations(+ ctx.asCaller.supabase,+ { ids, companyId: ctx.company.id, to, userId: ctx.auditUserId }+ );+ if (result.error) {+ return ctx.error(+ "internal",+ "Failed to update sync operations",+ result.error+ );+ }+ if (result.failures.length > 0) {+ logger.warn("Sync operations were not transitioned", {+ companyId: ctx.company.id,+ to,+ failures: result.failures+ });+ return ctx.error(+ "rule",+ result.moved > 0+ ? `Updated ${result.moved} of ${result.moved + result.failures.length} sync operations`+ : "Failed to update sync operation",+ result.failures+ );+ }+ return { count: result.moved, to };+ }+ });++ /** Propose provider accounts for unmapped Carbon accounts, with AI. Writes nothing. */+ export const suggestAccountMappings = defineServiceFn({+ input: z.object({+ accounts: z.array(+ z.object({+ id: z.string().min(1),+ number: z.string().nullable(),+ name: z.string()+ })+ ),+ providerAccounts: z.array(+ z.object({+ id: z.string().min(1),+ code: z.string().nullable().optional(),+ name: z.string().nullable().optional()+ })+ )+ }),+ permission: { update: "settings" },+ async run(ctx, { accounts, providerAccounts }) {+ const result = await suggestAccountMatchesWithAI({+ accounts,+ providerAccounts+ });+ if (result.error || !result.data) {+ return ctx.error(+ "internal",+ "Failed to suggest account mappings",+ result.error+ );+ }+ return { proposals: result.data };+ }+ });++ /** Map Carbon accounts to an accounting integration's accounts. */+ export const saveAccountMappings = defineServiceFn({+ input: z.object({+ integrationId: z.string().min(1),+ mappings: z+ .array(accountMappingEntrySchema)+ .min(1, { message: "No account mappings to save" })+ }),+ permission: { update: "settings" },+ async run(ctx, { integrationId, mappings }) {+ const result = await upsertAccountMappings(ctx.asSystem.pg, {+ companyId: ctx.company.id,+ integration: integrationId,+ userId: ctx.auditUserId,+ mappings+ });+ if (result.error) {+ return ctx.error(+ "internal",+ "Failed to save account mappings",+ result.error+ );+ }+ return { count: mappings.length };+ }+ });+ /**+ * Set which Carbon dimensions ride along on the journals pushed to an accounting integration.+ *+ * @remarks+ * Each slot pairs a Carbon dimension with one of the provider's analytics+ * targets; the slots are checked against the targets the provider declares+ * and its slot limit. No slots turns dimension sync off. Unmapped values are+ * warned about or dropped.+ *+ * @mcp+ */+ export const updateDimensionSync = defineServiceFn({+ input: z.object({+ integrationId: z.string().min(1),+ slots: z.array(dimensionSlotEntrySchema),+ onUnmappedDimensionValue: z.enum(["warn", "drop"])+ }),+ permission: { update: "settings" },+ async run(ctx, { integrationId, slots, onUnmappedDimensionValue }) {+ const providerTargets = await service.getProviderDimensionTargets(+ ctx.asCaller.supabase,+ ctx.company.id,+ integrationId+ );+ if (!providerTargets.supported) {+ return ctx.error(+ "rule",+ "This integration does not support dimension sync"+ );+ }+ // Clearing every slot is always allowed; validating a non-empty config+ // against a failed target fetch would reject every target as unknown.+ if (slots.length > 0 && providerTargets.targetsError) {+ return ctx.error(+ "unavailable",+ "Couldn't load the provider's dimension targets — try again"+ );+ }+ const slotErrors = validateDimensionSlots({+ slots,+ targets: providerTargets.targets,+ maxSlots: providerTargets.maxSlots ?? undefined+ });+ if (slotErrors.length > 0) {+ return ctx.error(+ "rule",+ "Invalid dimension slot configuration",+ slotErrors.join(" ")+ );+ }++ const existing = await service.integrationSettings(ctx, integrationId);+ if (!existing) {+ return ctx.error("notFound", "Failed to load integration settings");+ }+ const postingSync =+ (existing.settings.postingSync as Record<string, unknown> | undefined) ??+ {};++ // The v2 shim-marker keys are deliberately left in place: this does not+ // write the v3 sourceTypes record, so stripping them would make the+ // schema shim lose the stored v2 enabled set on the next read.+ const saved = await service.saveIntegrationMetadata(+ ctx,+ integrationId,+ existing.active ?? true,+ {+ ...existing.metadata,+ settings: {+ ...existing.settings,+ postingSync: {+ ...postingSync,+ dimensionSlots: slots,+ onUnmappedDimensionValue+ }+ }+ },+ "Failed to update dimension sync settings"+ );+ return saved ?? { integrationId };+ }+ });++ /** Map Carbon dimension values to an accounting integration's analytics values. */+ export const saveDimensionValueMappings = defineServiceFn({+ input: z.object({+ integrationId: z.string().min(1),+ mappings: z+ .array(dimensionValueMappingEntrySchema)+ .min(1, { message: "No dimension value mappings to save" })+ }),+ permission: { update: "settings" },+ async run(ctx, { integrationId, mappings }) {+ const failures: string[] = [];+ // ponytail: one upsert per value, as the match drawer confirms a page of+ // names; a batched upsert in the engine when it confirms thousands.+ for (const mapping of mappings) {+ const result = await upsertDimensionValueMapping(ctx.asSystem.pg, {+ companyId: ctx.company.id,+ integration: integrationId,+ ...mapping,+ userId: ctx.auditUserId+ });+ if (result.error) failures.push(result.error);+ }+ if (failures.length > 0) {+ const succeeded = mappings.length - failures.length;+ return ctx.error(+ succeeded > 0 ? "rule" : "internal",+ succeeded > 0+ ? `Saved ${succeeded} of ${mappings.length} dimension value mappings`+ : mappings.length === 1+ ? "Failed to save dimension value mapping"+ : "Failed to save dimension value mappings",+ failures[0]+ );+ }+ return { count: mappings.length };+ }+ });++ /**+ * Turn an accounting integration's sync on or off.+ *+ * @remarks+ * A new connection starts with sync off. Turning it on is refused until+ * every required account is mapped, so the first push cannot park a wall of+ * unmapped-account warnings.+ *+ * @mcp+ */+ export const setIntegrationSyncEnabled = defineServiceFn({+ input: z.object({+ integrationId: z.string().min(1),+ syncEnabled: z.boolean()+ }),+ permission: { update: "settings" },+ async run(ctx, { integrationId, syncEnabled }) {+ const existing = await service.integrationSettings(ctx, integrationId);+ if (!existing?.active) {+ return ctx.error("notFound", "Failed to load integration settings");+ }++ if (syncEnabled) {+ const unmapped = await getUnmappedRequiredAccounts(ctx.asSystem.pg, {+ companyId: ctx.company.id,+ integration: integrationId+ });+ if (unmapped.error || !unmapped.data) {+ return ctx.error(+ "internal",+ "Failed to check the account mapping",+ unmapped.error+ );+ }+ if (unmapped.data.length > 0) {+ return ctx.error(+ "rule",+ `Map the remaining ${unmapped.data.length} required account${+ unmapped.data.length === 1 ? "" : "s"+ } before turning on sync`+ );+ }+ }++ const saved = await service.saveIntegrationMetadata(+ ctx,+ integrationId,+ existing.active,+ {+ ...existing.metadata,+ settings: { ...existing.settings, syncEnabled }+ },+ "Failed to update sync"+ );+ return saved ?? { syncEnabled };+ }+ });++ /**+ * Set how an accounting integration receives postings.+ *+ * @remarks+ * Posting sync is always on. Each journal-represented source type except+ * Manual is sent, individually or as a daily summary (`sourceTypeConfigs`:+ * "<source type>|individual" or "|daily-summary"; an unlisted type takes its+ * default). Receivables, payables, credit memos and supplier credits each go+ * as documents, as journals or not at all. A posting into a locked provider+ * period is parked or redated, and `lockDate` is the provider's lock date.+ * Keys this form does not own (the weekly reconciliation's) are kept.+ *+ * @mcp+ */+ export const updatePostingSync = defineServiceFn({+ input: z.object({+ integrationId: z.string().min(1),+ sourceTypeConfigs: z.array(+ z+ .string()+ .regex(+ /^[^|]+\|(individual|daily-summary)$/,+ "Malformed source-type config"+ )+ ),+ familyAr: z.enum(["documents", "journals", "none"]),+ familyAp: z.enum(["documents", "journals", "none"]),+ familyCreditMemo: z.enum(["documents", "journals", "none"]),+ familySupplierCredit: z.enum(["documents", "journals", "none"]),+ periodLockPolicy: z.enum(["park", "redate"]),+ lockDate: z.string().optional()+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ const granularityBySourceType = new Map(+ input.sourceTypeConfigs.map((config) => {+ const separator = config.lastIndexOf("|");+ return [+ config.slice(0, separator),+ config.slice(separator + 1) as "individual" | "daily-summary"+ ] as const;+ })+ );+ const sourceTypes: Record<+ string,+ { enabled: boolean; granularity: "individual" | "daily-summary" }+ > = {};+ for (const sourceType of JOURNAL_ENTRY_SOURCE_TYPES) {+ if (POSTING_POLICY[sourceType].representation !== "journal") continue;+ if (sourceType === "Manual") continue;+ sourceTypes[sourceType] = {+ enabled: true,+ granularity:+ granularityBySourceType.get(sourceType) ??+ POSTING_POLICY[sourceType].defaultGranularity+ };+ }++ const existing = await service.integrationSettings(+ ctx,+ input.integrationId+ );+ if (!existing) {+ return ctx.error("notFound", "Failed to load integration settings");+ }++ // Saving writes the v3 shape: the v2 shim markers (includeManual,+ // consolidation, the legacy sourceTypes array) and the old master+ // `enabled` are dropped, or the schema shim would read the fragment as v2.+ const {+ includeManual: _includeManual,+ consolidation: _consolidation,+ sourceTypes: _legacySourceTypes,+ enabled: _enabled,+ ...postingSync+ } = (existing.settings.postingSync as+ | Record<string, unknown>+ | undefined) ?? {};++ const saved = await service.saveIntegrationMetadata(+ ctx,+ input.integrationId,+ existing.active ?? true,+ {+ ...existing.metadata,+ settings: {+ ...existing.settings,+ postingSync: {+ ...postingSync,+ families: {+ ar: input.familyAr,+ ap: input.familyAp,+ creditMemo: input.familyCreditMemo,+ supplierCredit: input.familySupplierCredit+ },+ sourceTypes,+ periodLockPolicy: input.periodLockPolicy,+ ...(input.lockDate ? { lockDate: input.lockDate } : {})+ }+ }+ },+ "Failed to update posting sync settings"+ );+ return saved ?? { integrationId: input.integrationId };+ }+ });++ /**+ * Map an OEE integration's device to a work center, or unmap it.+ *+ * @remarks+ * Only a station the current connection reports can be mapped: a list read+ * before the API key changed could name a station the provider does not+ * have, whose mapping would never sync. The stored name, site and time zone+ * are the provider's. No work center unmaps the device. OEE integrations are+ * a commercial feature.+ */+ export const saveOeeDeviceMapping = defineServiceFn({+ input: z.object({+ integrationId: z.string().min(1),+ externalDeviceId: z.string().min(1),+ deviceName: z.string().min(1),+ workCenterId: z.string().optional()+ }),+ permission: { update: "settings" },+ async run(+ ctx,+ { integrationId, externalDeviceId, deviceName, workCenterId }+ ) {+ let device: OeeDevice | undefined;+ if (workCenterId) {+ const provider = await service.listOeeDevices(+ ctx.company.id,+ integrationId+ );+ device = provider.devices.find(+ (candidate) => candidate.externalDeviceId === externalDeviceId+ );+ if (!device) {+ return ctx.error(+ "rule",+ `Failed to save device mapping: ${+ provider.error ?? `${deviceName} is not a station of this provider`+ }`+ );+ }+ }++ let result: { error: string | null };+ try {+ result =+ workCenterId && device+ ? await upsertWorkCenterDevice(+ ctx.asCaller.supabase,+ ctx.asSystem.pg,+ {+ companyId: ctx.company.id,+ userId: ctx.auditUserId,+ integration: integrationId,+ externalDeviceId,+ externalSiteId: device.externalSiteId,+ siteTimezone: device.siteTimezone,+ deviceName: device.name,+ workCenterId+ }+ )+ : await deleteWorkCenterDevice(+ ctx.asCaller.supabase,+ ctx.asSystem.pg,+ {+ companyId: ctx.company.id,+ userId: ctx.auditUserId,+ integration: integrationId,+ externalDeviceId+ }+ );+ } catch (err) {+ if (!(err instanceof EntitlementError)) throw err;+ return ctx.error(+ "entitlement",+ `Failed to save device mapping: ${err.message}`+ );+ }+ if (result.error) {+ return ctx.error(+ "rule",+ `Failed to save device mapping: ${result.error}`+ );+ }+ return { externalDeviceId, workCenterId: workCenterId ?? null };+ }+ });+ /**+ * Get accounts payable billing address+ *+ * @mcp read+ */+ export const getAccountsPayableBillingAddress = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getAccountsPayableBillingAddress(+ ctx.asCaller.supabase,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get accounts receivable billing address+ *+ * @mcp read+ */+ export const getAccountsReceivableBillingAddress = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getAccountsReceivableBillingAddress(+ ctx.asCaller.supabase,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get api keys+ *+ * @mcp+ */+ export const getApiKeys = defineServiceFn({+ input: z.looseObject({+ limit: z+ .number()+ .int()+ .describe("Rows per page. Left out, the read is not paged.")+ .optional(),+ offset: z.number().int().default(0),+ search: z.string().nullable().optional()+ }),+ permission: { update: "users" },+ async run(ctx, input) {+ return paged(+ ctx,+ await service.getApiKeys(+ ctx.asCaller.supabase,+ ctx.company.id,+ payload(ctx, input).build() as never+ )+ );+ }+ });++ /**+ * List the companies the caller belongs to, with their logo URLs.+ *+ * @mcp read+ */+ export const getCompanies = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getCompanies(ctx.asCaller.supabase, ctx.auditUserId)+ );+ }+ });++ /**+ * The companies a user can enter in the ERP+ *+ * @mcp read+ */+ export const getEmployeeCompanies = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getEmployeeCompanies(ctx.asCaller.supabase, ctx.auditUserId)+ );+ }+ });++ /**+ * Get industries+ *+ * @mcp read+ */+ export const getIndustries = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(ctx, await service.getIndustries(ctx.asCaller.supabase));+ }+ });++ /**+ * Get company+ *+ * @mcp read+ */+ export const getCompany = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getCompany(ctx.asCaller.supabase, ctx.company.id)+ );+ }+ });++ /**+ * Get company settings+ *+ * @mcp read+ */+ export const getCompanySettings = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getCompanySettings(ctx.asCaller.supabase, ctx.company.id)+ );+ }+ });++ /**+ * Get config+ *+ * @mcp read+ */+ export const getConfig = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(ctx, await service.getConfig(ctx.asCaller.supabase));+ }+ });++ /**+ * Get current sequence+ *+ * @mcp read+ */+ export const getCurrentSequence = defineServiceFn({+ input: z.looseObject({ table: z.string() }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getCurrentSequence(+ ctx.asCaller.supabase,+ input.table as never,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get custom field+ *+ * @mcp read+ */+ export const getCustomField = defineServiceFn({+ input: z.looseObject({ id: z.string() }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getCustomField(ctx.asCaller.supabase, input.id as never)+ );+ }+ });++ /**+ * Get custom fields+ *+ * @mcp read+ */+ export const getCustomFields = defineServiceFn({+ input: z.looseObject({ table: z.string() }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getCustomFields(+ ctx.asCaller.supabase,+ input.table as never,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get custom fields tables+ *+ * @mcp read+ */+ export const getCustomFieldsTables = defineServiceFn({+ input: z.looseObject({+ limit: z+ .number()+ .int()+ .describe("Rows per page. Left out, the read is not paged.")+ .optional(),+ offset: z.number().int().default(0),+ search: z.string().nullable().optional()+ }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return paged(+ ctx,+ await service.getCustomFieldsTables(+ ctx.asCaller.supabase,+ ctx.company.id,+ payload(ctx, input).build() as never+ )+ );+ }+ });++ /**+ * Get integration+ *+ * @mcp read+ */+ export const getIntegration = defineServiceFn({+ input: z.looseObject({ id: z.string() }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getIntegration(+ ctx.asCaller.supabase,+ input.id as never,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get kanban output setting+ *+ * @mcp read+ */+ export const getKanbanOutputSetting = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getKanbanOutputSetting(+ ctx.asCaller.supabase,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Takes the next number of a sequence, which advances it+ *+ * @mcp+ */+ export const getNextSequence = defineServiceFn({+ input: z.looseObject({ table: z.string() }),+ permission: { update: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getNextSequence(+ ctx.asCaller.supabase,+ input.table as never,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get plans+ *+ * @mcp read+ */+ export const getPlans = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(ctx, await service.getPlans(ctx.asCaller.supabase));+ }+ });++ /**+ * Get sequence+ *+ * @mcp read+ */+ export const getSequence = defineServiceFn({+ input: z.looseObject({ table: z.string() }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getSequence(+ ctx.asCaller.supabase,+ input.table as never,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get sequences+ *+ * @mcp read+ */+ export const getSequences = defineServiceFn({+ input: z.looseObject({+ limit: z+ .number()+ .int()+ .describe("Rows per page. Left out, the read is not paged.")+ .optional(),+ offset: z.number().int().default(0),+ search: z.string().nullable().optional()+ }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return paged(+ ctx,+ await service.getSequences(+ ctx.asCaller.supabase,+ ctx.company.id,+ payload(ctx, input).build() as never+ )+ );+ }+ });++ /**+ * Get sequences list+ *+ * @mcp read+ */+ export const getSequencesList = defineServiceFn({+ input: z.looseObject({ table: z.string() }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getSequencesList(+ ctx.asCaller.supabase,+ input.table as never,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get item serial sequences+ *+ * @mcp read+ */+ export const getItemSerialSequences = defineServiceFn({+ input: z.looseObject({+ limit: z+ .number()+ .int()+ .describe("Rows per page. Left out, the read is not paged.")+ .optional(),+ offset: z.number().int().default(0),+ search: z.string().nullable().optional()+ }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return paged(+ ctx,+ await service.getItemSerialSequences(+ ctx.asCaller.supabase,+ ctx.company.id,+ payload(ctx, input).build() as never+ )+ );+ }+ });++ /**+ * Get item serial sequence+ *+ * @mcp read+ */+ export const getItemSerialSequence = defineServiceFn({+ input: z.looseObject({ id: z.string() }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getItemSerialSequence(+ ctx.asCaller.supabase,+ input.id as never,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Create a item serial sequence+ *+ * @remarks+ * Upsert item serial sequence+ *+ * @mcp+ */+ export const createItemSerialSequence = defineServiceFn({+ input: z.looseObject({+ itemId: z.string().min(1),+ prefix: z.string().optional(),+ suffix: z.string().optional(),+ next: z.number().min(0),+ step: z.number().min(1),+ size: z.number().min(1).max(20),+ id: z+ .string()+ .describe("Send to update that record; omit to create a new one.")+ .optional()+ }),+ permission: { create: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.upsertItemSerialSequence(+ ctx.asCaller.supabase,+ payload(ctx, input).forCreate() as never+ )+ );+ }+ });++ /**+ * Update a item serial sequence+ *+ * @remarks+ * Upsert item serial sequence+ *+ * @mcp+ */+ export const updateItemSerialSequence = defineServiceFn({+ input: z+ .looseObject({+ itemId: z.string().min(1),+ prefix: z.string().optional(),+ suffix: z.string().optional(),+ next: z.number().min(0),+ step: z.number().min(1),+ size: z.number().min(1).max(20),+ id: z+ .string()+ .describe("Send to update that record; omit to create a new one.")+ .optional()+ })+ .required({ id: true }),+ permission: { update: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.upsertItemSerialSequence(+ ctx.asCaller.supabase,+ payload(ctx, input).forUpdate() as never+ )+ );+ }+ });++ /**+ * Delete item serial sequence+ *+ * @mcp destructive+ */+ export const deleteItemSerialSequence = defineServiceFn({+ input: z.looseObject({ id: z.string() }),+ permission: { delete: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.deleteItemSerialSequence(+ ctx.asCaller.supabase,+ input.id as never,+ ctx.company.id+ )+ );+ }+ });++ /**+ * Get subsidiaries+ *+ * @mcp read+ */+ export const getSubsidiaries = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getSubsidiaries(ctx.asCaller.supabase, ctx.company.groupId)+ );+ }+ });++ /**+ * Get subsidiary+ *+ * @mcp read+ */+ export const getSubsidiary = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getSubsidiary(ctx.asCaller.supabase, ctx.company.id)+ );+ }+ });++ /**+ * Get terms+ *+ * @mcp read+ */+ export const getTerms = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getTerms(ctx.asCaller.supabase, ctx.company.id)+ );+ }+ });++ /**+ * Get document template+ *+ * @mcp read+ */+ export const getDocumentTemplate = defineServiceFn({+ input: z.looseObject({+ documentType: z.enum([+ "purchaseOrder",+ "salesOrder",+ "stockTransfer",+ "salesInvoice",+ "quote",+ "purchaseReturnOrder",+ "salesReturnOrder",+ "issue",+ "packingSlip",+ "jobTraveler",+ "trackingLabel"+ ])+ }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getDocumentTemplate(+ ctx.asCaller.supabase,+ ctx.company.id,+ input.documentType as never+ )+ );+ }+ });++ /**+ * Load a stored document template as a `DocumentTemplate | null` ready to pass to a PDF (which runs it through `resolveTemplate`)+ *+ * @mcp read+ */+ export const getDocumentTemplateConfig = defineServiceFn({+ input: z.looseObject({+ documentType: z.enum([+ "purchaseOrder",+ "salesOrder",+ "stockTransfer",+ "salesInvoice",+ "quote",+ "purchaseReturnOrder",+ "salesReturnOrder",+ "issue",+ "packingSlip",+ "jobTraveler",+ "trackingLabel"+ ])+ }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return await service.getDocumentTemplateConfig(+ ctx.asCaller.supabase,+ ctx.company.id,+ input.documentType as never+ );+ }+ });++ /**+ * Get document sections+ *+ * @mcp read+ */+ export const getDocumentSections = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(+ ctx,+ await service.getDocumentSections(ctx.asCaller.supabase, ctx.company.id)+ );+ }+ });++ /**+ * Fetch the given section ids and return them keyed by id for rendering+ *+ * @mcp+ */+ export const resolveSections = defineServiceFn({+ input: z.looseObject({ ids: z.array(z.string()) }),+ permission: { update: "settings" },+ async run(ctx, input) {+ return await service.resolveSections(+ ctx.asCaller.supabase,+ ctx.company.id,+ payload(ctx, input.ids).build() as never+ );+ }+ });++ /**+ * Get webhook+ *+ * @mcp read+ */+ export const getWebhook = defineServiceFn({+ input: z.looseObject({ id: z.string() }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.getWebhook(ctx.asCaller.supabase, input.id as never)+ );+ }+ });++ /**+ * Get webhooks+ *+ * @mcp read+ */+ export const getWebhooks = defineServiceFn({+ input: z.looseObject({+ limit: z+ .number()+ .int()+ .describe("Rows per page. Left out, the read is not paged.")+ .optional(),+ offset: z.number().int().default(0),+ search: z.string().nullable().optional()+ }),+ permission: { view: "settings" },+ async run(ctx, input) {+ return paged(+ ctx,+ await service.getWebhooks(+ ctx.asCaller.supabase,+ ctx.company.id,+ payload(ctx, input).build() as never+ )+ );+ }+ });++ /**+ * Get webhook tables+ *+ * @mcp read+ */+ export const getWebhookTables = defineServiceFn({+ input: z.record(z.string(), z.unknown()),+ permission: { view: "settings" },+ async run(ctx) {+ return unwrap(ctx, await service.getWebhookTables(ctx.asCaller.supabase));+ }+ });++ /**+ * Update sequence+ *+ * @mcp+ */+ export const updateSequence = defineServiceFn({+ input: z.looseObject({+ table: z.string(),+ sequence: z.looseObject({+ table: z.string().min(1).optional(),+ prefix: z.string().optional(),+ suffix: z.string().optional(),+ next: z.number().min(0).optional(),+ step: z.number().min(1).optional(),+ size: z.number().min(1).max(20).optional()+ })+ }),+ permission: { update: "settings" },+ async run(ctx, input) {+ return unwrap(+ ctx,+ await service.updateSequence(+ ctx.asCaller.supabase,+ input.table as never,+ ctx.company.id,+ payload(ctx, input.sequence).forUpdate() as never+ )+ );+ }+ });++ /**+ * Detach an item from the Onshape panel+ *+ * @remarks+ * Removes the item's `onshape-v2` link. The item keeps its model, documents+ * and fields. A sync connection's `onshape` row is bill-of-materials import+ * bookkeeping that the BoM Explorer reads, so it is never removed here.+ */+ export const detachOnshapeItem = defineServiceFn({+ input: z.object({ itemId: z.string().min(1) }),+ permission: { update: "parts" },+ async run(ctx, { itemId }) {+ const removed = await ctx.asSystem.supabase+ .from("externalIntegrationMapping")+ .delete()+ .eq("companyId", ctx.company.id)+ .eq("integration", ONSHAPE_V2_INTEGRATION_ID)+ .eq("entityType", "item")+ .eq("entityId", itemId)+ .select("id");+ if (removed.error) {+ return ctx.error(+ "internal",+ "Failed to detach from Onshape",+ removed.error+ );+ }+ if (removed.data.length === 0) {+ return ctx.error("notFound", "This item is not linked to Onshape");+ }+ return { itemId };+ }+ });++ /**+ * Save the Onshape panel's property map+ *+ * @remarks+ * Replaces the property map, the description modes and the push defaults.+ * Answers in the panel's own reply shape.+ */+ export const saveOnshapePropertyMap = defineServiceFn({+ input: service.onshapePropertyMapInput,+ permission: { update: "settings" },+ run: (ctx, input) => service.saveOnshapePropertyMap(ctx, input)+ });++ /**+ * Push reviewed Onshape parts+ *+ * @remarks+ * Applies a part review from the Onshape panel: creates or adopts items,+ * links them, and queues their model exports. Answers in the panel's own+ * reply shape.+ */+ export const pushOnshapePart = defineServiceFn({+ input: service.onshapePartPushInput,+ permission: { create: "parts", update: "parts" },+ run: (ctx, input) => service.pushOnshapePart(ctx, input)+ });++ /**+ * Push a reviewed Onshape assembly+ *+ * @remarks+ * Applies an assembly review from the Onshape panel: items, bill of material+ * lines per method, links and the model export. Re-pushing replaces the lines+ * an earlier push wrote. Answers in the panel's own reply shape.+ */+ export const pushOnshapeAssembly = defineServiceFn({+ input: service.onshapeAssemblyPushInput,+ permission: { create: "parts", update: "parts", delete: "parts" },+ run: (ctx, input) => service.pushOnshapeAssembly(ctx, input)+ });++ /**+ * Push a reviewed Onshape release+ *+ * @remarks+ * Applies a release review from the Onshape panel. Carbon's state when it+ * applies outranks the review. Answers in the panel's own reply shape.+ */+ export const pushOnshapeRelease = defineServiceFn({+ input: service.onshapeReleasePushInput,+ permission: { create: "parts", update: "parts", delete: "parts" },+ run: (ctx, input) => service.pushOnshapeRelease(ctx, input)+ });diff --cc apps/erp/app/modules/shared/shared.service.tsindex 975302d78a,4bf0282422..2149de8b77--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@@ -670,3 -702,15605 +702,15631 @@@ export async function getEnforcementRulreturn { data: counts, error: null };}+ /**+ * Resolve the location a location-scoped screen should render.+ *+ * Precedence: the `?location=` search param, then the user's default location,+ * then the company's first location. Each of the six planning/scheduling+ * screens carried its own copy of this, differing only in where they redirect+ * on failure.+ *+ * The steps run sequentially on purpose: each one usually resolves the id, so+ * running them concurrently would add queries to the common path to save a+ * round-trip on the rare one.+ *+ * The returned id always belongs to `companyId` — callers rely on that, because+ * several run with `bypassRls: true` and then filter only on the location.+ */+ export async function resolveLocationId(+ client: SupabaseClient<Database>,+ request: Request,+ args: {+ searchParams: URLSearchParams;+ userId: string;+ companyId: string;+ /** Where to send the user if their defaults can't be read. */+ onDefaultsError: string;+ /** Where to send the user if the company has no locations. */+ onNoLocations: string;+ }+ ): Promise<string> {+ const { searchParams, userId, companyId, onDefaultsError, onNoLocations } =+ args;++ let locationId = searchParams.get("location");++ // `?location=` is attacker-controlled and five of the six callers run with+ // `bypassRls: true`, over queries that filter on the location with no company+ // predicate of their own (`get_jobs_by_date_range`, `get_unscheduled_jobs`,+ // `get_active_job_operations_by_location`, the `workCenters` reads) — so a+ // foreign id here would return another tenant's rows. Falls back to the+ // user's default rather than 404ing, which is what a stale bookmark should do.+ if (locationId) {+ const requested = await client+ .from("location")+ .select("id")+ .eq("id", locationId)+ .eq("companyId", companyId)+ .maybeSingle();++ if (requested.error || !requested.data) {+ locationId = null;+ }+ }++ if (!locationId) {+ const userDefaults = await getUserDefaults(client, userId, companyId);+ if (userDefaults.error) {+ throw redirect(+ onDefaultsError,+ await flash(+ request,+ error(userDefaults.error, "Failed to load default location")+ )+ );+ }++ locationId = userDefaults.data?.locationId ?? null;+ }++ if (!locationId) {+ const locations = await getLocationsList(client, companyId);+ if (locations.error || !locations.data?.length) {+ throw redirect(+ onNoLocations,+ await flash(+ request,+ error(locations.error, "Failed to load any locations")+ )+ );+ }+ locationId = locations.data[0].id as string;+ }++ return locationId;+ }+ type PublicTables = Database["public"]["Tables"];++ type Views = Database["public"]["Views"];++ export async function assign(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ table: string;+ assignee: string;+ }+ ) {+ const { id, table, assignee } = args;++ return (+ client+ // @ts-expect-error+ .from(table)+ .update(unchecked({ assignee: assignee ? assignee : null }))+ .eq(unchecked("id"), id)+ );+ }++ export async function getCustomFieldsCacheKey(args?: {+ companyId?: string;+ module?: string;+ table?: string;+ }) {+ return `customFields:${args?.companyId}:${args?.module ?? ""}:${+ args?.table ?? ""+ }`;+ }++ export async function getCustomFieldsSchemas(+ client: SupabaseClient<Database>,+ args?: {+ companyId: string;+ module?: string;+ table?: string;+ }+ ) {+ const key = await getCustomFieldsCacheKey(args);++ // redis.get returns null on a cache miss (or when Redis is unreachable — the+ // @carbon/kv resilience wrapper fails soft). Treat both, and a malformed+ // cached payload, as a miss and fall through to the database.+ const cachedSchema = await redis.get(key);+ if (cachedSchema) {+ try {+ return {+ data: JSON.parse(cachedSchema) as CustomFieldsTableType[],+ error: null+ };+ } catch {+ // Corrupt cache entry — fall through to the source of truth.+ }+ }++ const query = client.from("customFieldTables").select("*");++ if (args?.companyId) {+ query.eq("companyId", args.companyId);+ }++ if (args?.module) {+ query.eq("module", args.module as any);+ }++ if (args?.table) {+ query.eq("table", args.table);+ }++ const result = await query;+ if (result.data) {+ await redis.set(key, JSON.stringify(result.data));+ }++ return result;+ }++ // tzdata only changes when the Postgres image is upgraded — a day-long TTL+ // keeps the pg_timezone_names scan (~1ms but per-request) off the hot path+ // while still picking up a DB upgrade within 24h.+ const TIMEZONES_CACHE_TTL_MS = 24 * 60 * 60 * 1000;++ let cachedTimezoneNames: {+ data: { name: string; utcOffset: string }[];+ fetchedAt: number;+ } | null = null;++ /**+ * In-memory memo of the get_timezone_names RPC (pg_timezone_names). The list+ * is global (not company-scoped), identical for every tenant, and never+ * invalidated by user action — so a per-process memo beats Redis: no network+ * round-trip, nothing to invalidate, and a cold start simply refetches+ * (~1ms scan). A failed fetch is returned as-is and not cached.+ */+ export async function getCachedTimezoneNames(client: SupabaseClient<Database>) {+ if (+ cachedTimezoneNames &&+ Date.now() - cachedTimezoneNames.fetchedAt < TIMEZONES_CACHE_TTL_MS+ ) {+ return { data: cachedTimezoneNames.data, error: null };+ }++ const result = await getTimezoneNames(client);+ if (result.data?.length) {+ cachedTimezoneNames = { data: result.data, fetchedAt: Date.now() };+ }++ return result;+ }++ /**+ * Sends a sales order confirmation email with the PDF attached.+ *+ * This mirrors the email-sending logic originally in the confirm action+ * and can be reused by the quote-to-order conversion flow.+ */+ export async function sendSalesOrderEmail(args: {+ salesOrderId: string;+ companyId: string;+ companyGroupId: string;+ userId: string;+ customerContactId: string;+ cc?: string[];+ documentFilePath: string;+ fileName: string;+ serviceRole: SupabaseClient<Database>;+ locales: string[];+ }): Promise<{ success: boolean; message?: string }> {+ const {+ salesOrderId,+ companyId,+ companyGroupId,+ userId,+ customerContactId,+ cc: ccSelections,+ documentFilePath,+ fileName,+ serviceRole,+ locales+ } = args;++ const [+ company,+ customer,+ salesOrder,+ salesOrderLines,+ salesOrderLocations,+ seller,+ paymentTerms+ ] = await Promise.all([+ getCompany(serviceRole, companyId),+ // customerContactId comes from the form and the service role bypasses+ // RLS — scope it so another company's contact is never read or emailed.+ getCustomerContact(serviceRole, customerContactId, companyId),+ getSalesOrder(serviceRole, salesOrderId),+ getSalesOrderLines(serviceRole, salesOrderId),+ getSalesOrderCustomerDetails(serviceRole, salesOrderId),+ getUser(serviceRole, userId),+ getPaymentTermsList(serviceRole, companyId)+ ]);++ if (!customer?.data?.contact) {+ return { success: false, message: "Failed to get customer contact" };+ }+ if (!company.data) {+ return { success: false, message: "Failed to get company" };+ }+ if (!seller.data) {+ return { success: false, message: "Failed to get user" };+ }+ if (!salesOrder.data) {+ return { success: false, message: "Failed to get sales order" };+ }+ if (!salesOrderLocations.data) {+ return { success: false, message: "Failed to get sales order locations" };+ }+ if (!paymentTerms.data) {+ return { success: false, message: "Failed to get payment terms" };+ }++ // Amounts render at the ORDER currency's decimals, same as the PDF of the+ // same order — otherwise the two disagree about the width of a total.+ const currencyRow = salesOrder.data.currencyCode+ ? await getCurrencyByCode(+ serviceRole,+ companyGroupId,+ salesOrder.data.currencyCode+ )+ : null;++ const emailTemplate = SalesOrderEmail({+ currencyDecimals: currencyRow?.data?.decimalPlaces ?? null,+ company: company.data as any,+ locale: locales?.[0] ?? "en-US",+ salesOrder: salesOrder.data,+ salesOrderLines: salesOrderLines.data ?? [],+ salesOrderLocations: salesOrderLocations.data,+ recipient: {+ email: customer.data.contact.email!,+ firstName: customer.data.contact.firstName ?? undefined,+ lastName: customer.data.contact.lastName ?? undefined+ },+ sender: {+ email: seller.data.email,+ firstName: seller.data.firstName,+ lastName: seller.data.lastName+ },+ paymentTerms: paymentTerms.data+ });++ const html = await renderAsync(emailTemplate);+ const text = await renderAsync(emailTemplate, { plainText: true });+ const signed = await storage(serviceRole)+ .company(companyId)+ .createSignedUrl(documentFilePath, 3600);++ await trigger("send-email", {+ to: [seller.data.email, customer.data.contact.email!],+ cc: ccSelections?.length ? ccSelections : undefined,+ from: seller.data.email,+ subject: `Order ${salesOrder.data.salesOrderId} from ${company.data.name}`,+ html,+ text,+ attachments: signed.data+ ? [+ {+ path: signed.data.signedUrl,+ filename: fileName+ }+ ]+ : undefined,+ companyId+ });++ return { success: true };+ }++ export async function getOrCreatePeriods(+ db: Kysely<KyselyDatabase>,+ today: CalendarDate,+ weeksToProject: number+ ) {+ const start = startOfWeek(today, "en-US");++ // Generate weekly date ranges+ const ranges: { startDate: string; endDate: string }[] = [];+ let currentStart = start;+ for (let i = 0; i < weeksToProject; i++) {+ const periodEnd = currentStart.add({ days: 6 });+ ranges.push({+ startDate: currentStart.toString(),+ endDate: periodEnd.toString()+ });+ currentStart = periodEnd.add({ days: 1 });+ }++ // Check which periods already exist+ const existingPeriods = await db+ .selectFrom("period")+ .selectAll()+ .where(+ "startDate",+ "in",+ ranges.map((r) => r.startDate)+ )+ .where("periodType", "=", "Week")+ .execute();++ if (existingPeriods.length === ranges.length) {+ return existingPeriods.map(toPlainPeriod);+ }++ // Find missing periods+ const existingStartDates = new Set(+ existingPeriods.map((p) => dateToString(p.startDate))+ );++ const periodsToCreate = ranges.filter(+ (r) => !existingStartDates.has(r.startDate)+ );++ // Create missing periods in a transaction+ const created = await db.transaction().execute(async (trx) => {+ return await trx+ .insertInto("period")+ .values(+ periodsToCreate.map((p) => ({+ startDate: p.startDate,+ endDate: p.endDate,+ periodType: "Week" as const,+ createdAt: new Date().toISOString()+ }))+ )+ .returningAll()+ .execute();+ });++ return [...existingPeriods, ...created].map(toPlainPeriod);+ }++ /** Convert a pg DATE value (Date object or string) to an ISO date string. */+ function dateToString(value: Date | string): string {+ if (value instanceof Date) {+ // Use local date parts to avoid timezone shift from toISOString()+ const y = value.getFullYear();+ const m = String(value.getMonth() + 1).padStart(2, "0");+ const d = String(value.getDate()).padStart(2, "0");+ return `${y}-${m}-${d}`;+ }+ return String(value);+ }++ /** Return a plain JSON-safe object with only the fields consumers need. */+ function toPlainPeriod(p: {+ id: string;+ startDate: Date | string;+ endDate: Date | string;+ periodType: string;+ }) {+ return {+ id: String(p.id),+ startDate: dateToString(p.startDate),+ endDate: dateToString(p.endDate),+ periodType: p.periodType+ };+ }++ /**+ * Every table with a string `id` and a `companyId` column. A nullable+ * `companyId` (e.g. `item`) is fine: global rows never match `.eq("companyId")`.+ */+ type CompanyScopedTable = {+ [K in keyof PublicTables]: PublicTables[K]["Row"] extends {+ id: string;+ companyId: string | null;+ }+ ? K+ : never;+ }[keyof PublicTables];++ /**+ * Throws a 404 `Response` naming the record unless a row of `table` in `companyId` matches every+ * column in `match` — e.g. `{ id: lineId, quoteId }` proves the line exists,+ * belongs to the company AND hangs off that quote. One query.+ *+ * Record ids in a URL or form body prove nothing about tenancy:+ * `requirePermissions` authorizes the CALLER for `companyId`, not the ids it+ * sends. Most tables have single-column foreign keys, so a service-role or+ * Kysely write happily accepts another company's row as a parent. Call this+ * before any RLS-bypassing read or write keyed on a caller-supplied id.+ */+ export async function requireCompanyRecord(+ client: SupabaseClient<Database>,+ table: CompanyScopedTable,+ companyId: string,+ match: { id: string } & Record<string, string>+ ): Promise<void> {+ // Every table in the union has `id` + `companyId`; the cast only narrows the+ // union so supabase-js can type the builder.+ const { data, error } = await client+ .from(table as "quoteLine")+ .select("id")+ .match(match)+ .eq("companyId", companyId)+ .maybeSingle();++ if (error) {+ logger.error("Failed to verify {table} for company", {+ table,+ companyId,+ match,+ error+ });+ // The check itself failed: nothing is known about the record.+ throw new Response(`Failed to verify the ${recordName(table)}`, {+ status: 500+ });+ }+ if (!data) {+ logger.error("{table} not found for company", { table, companyId, match });+ // One message for a missing row and another company's row: the caller+ // must not learn which.+ throw new Response(+ `The ${recordName(table)} could not be found. It may have been deleted, or it belongs to another company.`,+ { status: 404 }+ );+ }+ }++ /**+ * `requireCompanyRecord` for a service function: a refusal instead of a thrown+ * `Response`. Checked with the service role, so it holds for an RLS-bypassing+ * write that follows.+ */+ export async function refuseUnlessOwned(+ ctx: ServiceContext,+ table: CompanyScopedTable,+ match: { id: string } & Record<string, string>+ ): Promise<CarbonError | null> {+ try {+ await requireCompanyRecord(+ ctx.asSystem.supabase,+ table,+ ctx.company.id,+ match+ );+ return null;+ } catch (thrown) {+ if (!(thrown instanceof Response)) throw thrown;+ return ctx.error(+ thrown.status === 404 ? "notFound" : "internal",+ await thrown.text()+ );+ }+ }++ /**+ * Whether `userId` is an ACTIVE employee of `companyId` — the check every+ * user-id field that names a person in the company needs before it is saved+ * (a planning action's assignee, a responsible employee). Those columns+ * reference the global `user` table, so the database accepts anyone's id,+ * including a person from another company or one since deactivated. One query;+ * a failed read is logged and answered false (fail closed).+ */+ export async function isActiveCompanyEmployee(+ client: SupabaseClient<Database>,+ companyId: string,+ userId: string+ ): Promise<boolean> {+ const { data, error } = await client+ .from("employee")+ .select("id")+ .eq("id", userId)+ .eq("companyId", companyId)+ .eq("active", true)+ .maybeSingle();++ if (error) {+ logger.error("Failed to verify employee for company", {+ companyId,+ userId,+ error+ });+ return false;+ }+ return data !== null;+ }++ /** `quoteLine` → `quote line`, for a message a person reads. */+ function recordName(table: string): string {+ return table.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();+ }++ // What `get_app_shell` returns: the rows the shell used to read with nine+ // requests. Each key holds what `select("*")` on that table returned.+ type AppShellRows = {+ companies: Views["companies"]["Row"][];+ companyIntegrations: PublicTables["companyIntegration"]["Row"][];+ companySettings: PublicTables["companySettings"]["Row"] | null;+ savedViews: PublicTables["tableView"]["Row"][];+ user: PublicTables["user"]["Row"] | null;+ groups: string[];+ defaults: Views["userDefaults"]["Row"] | null;+ modulePreferences: Pick<+ PublicTables["userModulePreference"]["Row"],+ "module" | "position" | "hidden"+ >[];+ printerRoutes: PrinterRoute[];+ implementationHub: PublicTables["implementationHub"]["Row"] | null;+ };++ /**+ * Everything the app shell reads about the user and the company, in one round+ * trip. `client` is the user's own client: the function runs as them, so each+ * table's RLS applies as it did when these were separate requests.+ */+ export async function getAppShell(+ client: SupabaseClient<Database>,+ // Absent for someone who has signed in and has no company yet.+ companyId: string | null | undefined,+ userId: string+ ) {+ const result = await client.rpc("get_app_shell", {+ // Sent as null, never left out. An undefined key is dropped from the+ // request, the API then looks for a `get_app_shell(user_id)` that does+ // not exist, and a first sign-in was logged straight back out instead+ // of being sent to onboarding. With null the function runs and returns+ // the user with no company rows.+ company_id: (companyId ?? null) as string,+ user_id: userId+ });+ if (result.error || !result.data) {+ return { data: null, error: result.error ?? new Error("Empty app shell") };+ }+ const rows = result.data as unknown as AppShellRows;+ return {+ data: { ...rows, companies: rows.companies.map(withLogoUrls) },+ error: null+ };+ }++ const signalsLogger = getLogger("erp", "implementation-signals");++ // A day, not forever: wiping a company's data (a demo template revert, a+ // restore) can make a signal false again, and this bounds how long the hub+ // would keep showing that step as done.+ const IMPLEMENTATION_SIGNALS_TTL_SECONDS = 60 * 60 * 24;++ const implementationSignalsKey = (companyId: string) =>+ `implementation:signals:${companyId}`;++ /**+ * The hub's product signals, probing only the ones not already seen true.+ *+ * The app shell loads these on every page for an enrolled company — five+ * existence queries each time. A signal that is true stays true, so it is+ * remembered per company and its probe is skipped; a company that has done+ * all five steps costs one Redis read instead.+ */+ export async function getImplementationSignals(+ client: SupabaseClient<Database>,+ companyId: string+ ): Promise<Signals> {+ let known: Partial<Signals> = {};+ try {+ const cached = await redis.get(implementationSignalsKey(companyId));+ if (cached) known = JSON.parse(cached) as Partial<Signals>;+ } catch (error) {+ // Redis is an optimisation here; without it, probe everything.+ signalsLogger.warn("Could not read cached implementation signals", {+ companyId,+ error+ });+ }++ const signals = await detectImplementationSignals(client, companyId, known);++ const seen = Object.fromEntries(+ Object.entries(signals).filter(([, value]) => value)+ ) as Partial<Signals>;+ if (Object.keys(seen).length > Object.keys(known).length) {+ try {+ await redis.set(+ implementationSignalsKey(companyId),+ JSON.stringify(seen),+ "EX",+ IMPLEMENTATION_SIGNALS_TTL_SECONDS+ );+ } catch (error) {+ signalsLogger.warn("Could not cache implementation signals", {+ companyId,+ error+ });+ }+ }+ return signals;+ }++ // The readable identifier on each action task's parent, used for the Linear+ // attachment / Jira remote-link title.+ const actionTaskParents: Record<+ ActionTaskEntityType,+ { parentTable: string; readableColumn: string }+ > = {+ nonConformanceActionTask: {+ parentTable: "nonConformance",+ readableColumn: "nonConformanceId"+ },+ changeOrderActionTask: {+ parentTable: "changeOrder",+ readableColumn: "changeOrderId"+ }+ };++ export type ActionTaskWithParent = {+ id: string | null;+ notes: unknown;+ parentId: string | null;+ parentReadableId: string | null;+ };++ // Entity-aware action-task read: resolves the task plus its parent (NCR or change notice) — reads an action+ // task and its parent's readable id from whichever table the entity type names.+ export async function getActionTaskWithParent(+ client: SupabaseClient<Database>,+ entityType: ActionTaskEntityType,+ taskId: string,+ companyId: string+ ): Promise<ActionTaskWithParent> {+ const { table, parentColumn } = actionTaskEntities[entityType];+ const { parentTable, readableColumn } = actionTaskParents[entityType];++ const result = await client+ .from(table)+ .select(`id, notes, ${parentColumn}, ${parentTable}(${readableColumn})`)+ .eq("id", taskId)+ .eq("companyId", companyId)+ .maybeSingle();++ // The select string is built from the entity map, which erases Supabase's row typing+ const row = result.data as Record<string, any> | null;++ return {+ id: row?.id ?? null,+ notes: row?.notes ?? null,+ parentId: row?.[parentColumn] ?? null,+ parentReadableId: row?.[parentTable]?.[readableColumn] ?? null+ };+ }++ const ONBOARDING_DRAFT_KEY = "onboarding-draft";++ const onboardingDraftStorage = createCookieSessionStorage({+ cookie: {+ name: ONBOARDING_DRAFT_KEY,+ path: "/",+ secrets: [SESSION_SECRET!],+ secure: false,+ httpOnly: true,+ sameSite: "lax",+ maxAge: 60 * 60 * 24 // 24 hours+ }+ });++ export type OnboardingDraft = {+ industry?: {+ industryId: string;+ customIndustryDescription?: string;+ };+ company?: {+ name?: string;+ addressLine1?: string;+ addressLine2?: string;+ city?: string;+ stateProvince?: string;+ postalCode?: string;+ countryCode?: string;+ baseCurrencyCode?: string;+ timezone?: string;+ website?: string;+ };+ };++ export async function getOnboardingDraft(+ request: Request+ ): Promise<OnboardingDraft | null> {+ const session = await onboardingDraftStorage.getSession(+ request.headers.get("Cookie")+ );+ const draft = session.get(ONBOARDING_DRAFT_KEY) as+ | OnboardingDraft+ | undefined;+ return draft ?? null;+ }++ export async function setOnboardingDraft(+ request: Request,+ draft: Partial<OnboardingDraft>+ ): Promise<string> {+ const session = await onboardingDraftStorage.getSession(+ request.headers.get("Cookie")+ );+ const existingDraft =+ (session.get(ONBOARDING_DRAFT_KEY) as OnboardingDraft | undefined) ?? {};+ const updatedDraft = { ...existingDraft, ...draft };+ session.set(ONBOARDING_DRAFT_KEY, updatedDraft);+ return onboardingDraftStorage.commitSession(session);+ }++ export async function clearOnboardingDraft(request: Request): Promise<string> {+ const session = await onboardingDraftStorage.getSession(+ request.headers.get("Cookie")+ );+ session.set(ONBOARDING_DRAFT_KEY, undefined);+ return onboardingDraftStorage.commitSession(session);+ }++ // For a list that is the same for every company and changes only with a deploy+ // or the database's own reference data. `private`: the route still needs a+ // session, so no shared cache may hold it.+ export const DAY_CACHE_HEADERS = { "Cache-Control": "private, max-age=86400" };++ /**+ * A global `{ data, error }` list the browser keeps for a day, across page+ * loads. An empty or failed read is not kept: it would stick for the day.+ */+ export function keptForADay<T extends { data: unknown[] | null }>(result: T) {+ return data(+ result,+ result.data?.length ? { headers: DAY_CACHE_HEADERS } : undefined+ );+ }++ /** The notification an assignment on `table` sends its assignee, if any. */+ export function assignmentEvent(table: string): NotificationEvent | null {+ switch (table) {+ case "purchasingRfq":+ return NotificationEvent.PurchasingRfqAssignment;+ case "salesRfq":+ return NotificationEvent.SalesRfqAssignment;+ case "quote":+ return NotificationEvent.QuoteAssignment;+ case "salesOrder":+ return NotificationEvent.SalesOrderAssignment;+ case "job":+ return NotificationEvent.JobAssignment;+ case "jobCompleted":+ return NotificationEvent.JobCompleted;+ case "jobOperation":+ return NotificationEvent.JobOperationAssignment;+ case "maintenanceDispatch":+ return NotificationEvent.MaintenanceDispatchAssignment;+ case "nonConformanceInvestigationTask":+ case "nonConformanceActionTask":+ case "nonConformanceApprovalTask":+ case "nonConformance":+ return NotificationEvent.NonConformanceAssignment;+ case "procedure":+ return NotificationEvent.ProcedureAssignment;+ case "purchaseOrder":+ return NotificationEvent.PurchaseOrderAssignment;+ case "purchaseInvoice":+ return NotificationEvent.PurchaseInvoiceAssignment;+ case "riskRegister":+ return NotificationEvent.RiskAssignment;+ case "supplierQuote":+ return NotificationEvent.SupplierQuoteAssignment;+ case "stockTransfer":+ return NotificationEvent.StockTransferAssignment;+ case "pickingList":+ return NotificationEvent.PickingListAssignment;+ case "training":+ return NotificationEvent.ResourceTrainingAssignment;+ case "trainingAssignment":+ return NotificationEvent.TrainingAssignment;+ default:+ return null;+ }+ }++ export const normalizeLookupName = (value: string) =>+ value.toLowerCase().trim();++ /** Email the company's active admins that their hub is ready. Never throws. */+ export async function notifyImplementationHubAdmins(ctx: ServiceContext) {+ const serviceRole = ctx.asSystem.supabase;+ const companyId = ctx.company.id;+ try {+ const adminTypes = await serviceRole+ .from("employeeType")+ .select("id")+ .eq("companyId", companyId)+ .eq("systemType", "Admin");+ if (adminTypes.error) throw adminTypes.error;++ const adminTypeIds = (adminTypes.data ?? []).map((type) => type.id);+ if (adminTypeIds.length === 0) {+ logger.info(+ "No Admin employee type found for company; skipping enrollment notification"+ );+ return;+ }++ const admins = await serviceRole+ .from("employees")+ .select("id, email, name")+ .eq("companyId", companyId)+ .eq("active", true)+ .in("employeeTypeId", adminTypeIds);+ if (admins.error) throw admins.error;++ const hubUrl = `${ERP_URL}${path.to.getStarted}`;+ for (const admin of admins.data ?? []) {+ if (!admin.email) continue;+ try {+ const email = ImplementationHubEmail({+ recipientName: admin.name ?? undefined,+ hubUrl+ });+ await trigger("send-email", {+ to: [admin.email],+ subject: "Your Implementation Hub is ready",+ html: await render(email),+ text: await render(email, { plainText: true }),+ companyId+ });+ } catch (error) {+ logger.error("Failed to send Implementation Hub email to admin", {+ adminId: admin.id ?? "unknown",+ error+ });+ }+ }+ } catch (error) {+ logger.error("Failed to notify admins of Implementation Hub enrollment", {+ companyId,+ error+ });+ }+ }++ /**+ * The action task an integration acts on, or a refusal when it hangs off a+ * change notice whose workflow can no longer change.+ */+ export async function editableActionTask(+ ctx: ServiceContext,+ entityType: ActionTaskEntityType,+ actionId: string+ ): Promise<ActionTaskWithParent | CarbonError> {+ const client = ctx.asCaller.supabase;+ const task = await getActionTaskWithParent(+ client,+ entityType,+ actionId,+ ctx.company.id+ );+ if (entityType !== "changeOrderActionTask") return task;++ const notFound = ctx.error("notFound", "Could not find change notice");+ if (!task.parentId) return notFound;+ const notice = await client+ .from("changeOrder")+ .select("status")+ .eq("id", task.parentId)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (notice.error || !notice.data) return notFound;+ if (!canEditChangeNoticeWorkflow(notice.data.status)) {+ return ctx.error("rule", changeNoticeLockedMessage(notice.data.status));+ }+ return task;+ }++ /** Where the action task's parent opens in Carbon, for the link back. */+ export function actionTaskUrl(+ rows: unknown,+ entityType: ActionTaskEntityType+ ): string {+ const parentId = actionTaskParentId(rows, entityType) ?? "";+ return `${getAppUrl()}${actionTaskEntities[entityType].detailPath(parentId)}/details`;+ }+ // Timezones change only when someone edits Settings → Company or a location, so+ // a long TTL is fine — writes invalidate the key explicitly (below). The+ // @carbon/kv resilience wrapper fails soft: a Redis miss/outage/corrupt value+ // just falls through to the database read.+ const TTL_SECONDS = 60 * 60 * 24 * 7;++ // 7 days+ const companyKey = (companyId: string) => `timezone:company:${companyId}`;++ const locationKey = (companyId: string, locationId: string) =>+ `timezone:location:${companyId}:${locationId}`;++ // Cached marker for "this location defines no timezone of its own". The+ // location cache must never store an INHERITED company timezone: that copy+ // would survive invalidateCompanyTimeZone for up to 7 days. Instead the+ // inherit case is cached as this sentinel and the fallback flows through the+ // (invalidatable) company cache on every read.+ const INHERIT = "__inherit__";++ /** Redis-cached {@link resolveCompanyTimeZone}. */+ export async function getCompanyTimeZone(+ db: AnyPostgresClient,+ companyId: string+ ): Promise<string> {+ const key = companyKey(companyId);+ const cached = await redis.get(key);+ if (cached) return cached;++ const tz = await resolveCompanyTimeZone(db, companyId);+ await redis.set(key, tz, "EX", TTL_SECONDS);+ return tz;+ }++ /**+ * Redis-cached location timezone with company fallback. Only the location's+ * OWN timezone is cached under the location key (company-scoped); a location+ * that inherits resolves through {@link getCompanyTimeZone} on every call, so+ * a company-timezone change takes effect immediately after its invalidation.+ */+ export async function getLocationTimeZone(+ db: AnyPostgresClient,+ locationId: string,+ companyId: string+ ): Promise<string> {+ const key = locationKey(companyId, locationId);+ const cached = await redis.get(key);+ if (cached !== null) {+ return cached === INHERIT ? getCompanyTimeZone(db, companyId) : cached;+ }++ const own = await getLocationOwnTimeZone(db, locationId, companyId);+ await redis.set(key, own ?? INHERIT, "EX", TTL_SECONDS);+ return own ?? getCompanyTimeZone(db, companyId);+ }++ /** Drop the cached company timezone — call after writing `company.timezone`. */+ export async function invalidateCompanyTimeZone(+ companyId: string+ ): Promise<void> {+ await redis.del(companyKey(companyId));+ }++ /** Drop the cached location timezone — call after writing `location.timezone`. */+ export async function invalidateLocationTimeZone(+ locationId: string,+ companyId: string+ ): Promise<void> {+ await redis.del(locationKey(companyId, locationId));+ }++ export type { PostingHandles };++ type PostingRule<I> = PermissionRule<I> | ((input: I) => Permissions);+ type PostingBody<I, R> = (ctx: ServiceContext, input: I) => Promise<R>;+ type PostingResult<R> =+ | { data: R; error: null }+ | { data: null; error: ServerFnError };+ type PostingSchema = { parse(value: unknown): unknown };+ type PostingOptions<I> = {+ as?: PostingRule<I>;+ schema?: PostingSchema;+ defaultStatus?: number;+ };+ /** Handles that carry the caller's client must name the permission to check. */+ type PostingOptionsFor<H, I> = H extends { client: SupabaseClient<Database> }+ ? [+ options: {+ as: PostingRule<I>;+ schema?: PostingSchema;+ defaultStatus?: number;+ }+ ]+ : [options?: PostingOptions<I>];++ /**+ * What a posting asks of the runner beyond the defaults, by name, so that no+ * caller can leave it out.+ */+ const POSTING_DEFAULTS: Partial<+ Record<string, { defaultStatus?: number; groupless?: true }>+ > = {+ // Its engine refuses with plain `Error`s written for the operator (an+ // unavailable or expired lot, a part already scrapped): a refusal, not a+ // failure, as its server function's `defaultStatus: 400` read them.+ issue: { defaultStatus: 400 },+ // Runs on the company `insertCompany` just made, which has no group yet:+ // the posting creates it.+ "seed-company": { groupless: true }+ };++ /**+ * Run a posting body and read it as `{ data, error }`, with the+ * `ServerFnError` it refused with.+ *+ * - From an operation, pass its `ctx` and no `as`: its own gate already+ * checked the caller.+ * - From handles that carry the caller's `client`, `as` is required (the+ * body's permission rule, or what the input requires): the caller must hold+ * it first — a user's claims, an API key's+ * scopes, nothing for the service role. With the body's input `schema`, the+ * input is parsed first and the rule reads it as the body will. The body+ * then runs as the system+ * on the user's behalf, over that same `db` (a transaction stays one).+ * - From handles without a client, the body runs as the system.+ */+ export function invokePosting<I, R>(+ from: ServiceContext,+ name: string,+ input: I,+ run: PostingBody<I, R>,+ options?: { defaultStatus?: number }+ ): Promise<PostingResult<R>>;+ export function invokePosting<I, R, H extends PostingHandles>(+ from: H,+ name: string,+ input: I,+ run: PostingBody<I, R>,+ ...options: PostingOptionsFor<H, I>+ ): Promise<PostingResult<R>>;+ export function invokePosting<I, R>(+ from: ServiceContext | PostingHandles,+ name: string,+ input: I,+ run: PostingBody<I, R>,+ options: PostingOptions<I> = {}+ ): Promise<PostingResult<R>> {+ return runPosting(from, name, input, run, options);+ }++ /** {@link invokePosting}, throwing its refusal, as `invokeOrThrow` did. */+ export function invokePostingOrThrow<I, R>(+ from: ServiceContext,+ name: string,+ input: I,+ run: PostingBody<I, R>,+ options?: { defaultStatus?: number }+ ): Promise<R>;+ export function invokePostingOrThrow<I, R, H extends PostingHandles>(+ from: H,+ name: string,+ input: I,+ run: PostingBody<I, R>,+ ...options: PostingOptionsFor<H, I>+ ): Promise<R>;+ export async function invokePostingOrThrow<I, R>(+ from: ServiceContext | PostingHandles,+ name: string,+ input: I,+ run: PostingBody<I, R>,+ options: PostingOptions<I> = {}+ ): Promise<R> {+ const result = await runPosting(from, name, input, run, options);+ if (result.error) throw result.error;+ return result.data;+ }++ /** {@link invokePosting} for `create`, with the result its document type returns. */+ export function invokeCreate<I extends CreateInput>(+ from: ServiceContext | PostingHandles,+ input: I+ ): Promise<PostingResult<CreateResultFor<I["type"]>>> {+ return runPosting(from, "create", input, createDocument, {}) as Promise<+ PostingResult<CreateResultFor<I["type"]>>+ >;+ }++ async function runPosting<I, R>(+ from: ServiceContext | PostingHandles,+ name: string,+ input: I,+ run: PostingBody<I, R>,+ { as, schema, defaultStatus }: PostingOptions<I>+ ): Promise<PostingResult<R>> {+ const posting = POSTING_DEFAULTS[name];+ const status = defaultStatus ?? posting?.defaultStatus;+ if ("actor" in from) {+ return attempt(from, name, () => run(from, input), status);+ }+ const handles = from;+ if (handles.client && !as) {+ throw new Error(+ `invokePosting("${name}"): handles with a caller's client need \`as\`, the permission to check the caller against`+ );+ }+ const actor: Actor = { type: "system", onBehalfOf: handles.userId };+ return attempt(+ { actor },+ name,+ async (span) => {+ if (handles.client && as) {+ const parsed = (schema ? schema.parse(input) : input) as I;+ const caller = postingCaller(handles.client, handles.userId);+ span.setAttribute("carbon.function.actor", caller.type);+ await authorizePostingCaller(+ handles,+ caller,+ typeof as === "function" ? as(parsed) : resolvePermissions(as, parsed)+ );+ }+ const ctx = createServiceContext({+ actor,+ company: await postingCompany(handles, posting?.groupless === true),+ caller: handles.client ?? getCarbonServiceRole(),+ system: getCarbonServiceRole,+ pg: () => handles.db,+ kv: () => redis+ });+ return run(ctx, input);+ },+ status+ );+ }++ async function postingCompany(+ { db, companyId, companyGroupId }: PostingHandles,+ groupless: boolean+ ): Promise<ServiceContext["company"]> {+ if (companyGroupId) return { id: companyId, groupId: companyGroupId };+ const company = await db+ .selectFrom("company")+ .select("companyGroupId")+ .where("id", "=", companyId)+ .executeTakeFirst();+ // An unknown company is the caller's mistake; a company with no group is ours.+ if (!company) throw new NotFoundError(`Company ${companyId} not found`);+ if (company.companyGroupId) {+ return { id: companyId, groupId: company.companyGroupId };+ }+ const noGroup = new ServerFnError(+ `Company ${companyId} has no company group`,+ 500+ );+ if (!groupless) throw noGroup;+ // A body that reads the group anyway is refused when it does.+ return {+ id: companyId,+ get groupId(): string {+ throw noGroup;+ }+ };+ }++ // Rows per INSERT. Every multi-row insert is bound by Postgres' 65535 bind+ // parameters: the widest table written (itemLedger, 14 columns) is ~7k+ // parameters at this size.+ const INSERT_CHUNK_SIZE = 500;++ export function chunked<T>(rows: T[], size = INSERT_CHUNK_SIZE): T[][] {+ const chunks: T[][] = [];+ for (let i = 0; i < rows.length; i += size) {+ chunks.push(rows.slice(i, i + size));+ }+ return chunks;+ }++ /**+ * Runs `insert` once per chunk of `rows`, one after another (they share a+ * transaction), and returns every chunk's RETURNING rows in input order.+ */+ export async function inChunks<T, R>(+ rows: T[],+ insert: (chunk: T[]) => Promise<R[]>+ ): Promise<R[]> {+ const results: R[] = [];+ for (const chunk of chunked(rows)) {+ results.push(...(await insert(chunk)));+ }+ return results;+ }+ // Pure per-row decision for supplier/customer CSV import. No DB, no I/O — so it+ // is unit-testable. The driver loop owns the running `seenIds`+ // / `seenNames` sets and applies the returned action.+ //+ // Root-cause fix: a blank CSV id must NEVER participate in in-file dedup. The+ // previous loop added "" to a Set and then treated every later blank-id row as a+ // duplicate, silently dropping them (1 of 58 imported). Here, dedup keys are the+ // non-empty id and the (always-present) name.++ export type RowDecision =+ | { action: "insert" }+ | { action: "update"; entityId: string }+ | { action: "skip"; reason: string; category: "error" | "skipped" };++ export function classifyImportRow(params: {+ id: string;+ name: string;+ externalIdMap: Map<string, string>;+ nameMap: Map<string, string>;+ seenIds: Set<string>;+ seenNames: Set<string>;+ }): RowDecision {+ const { id, name, externalIdMap, nameMap, seenIds, seenNames } = params;++ // `name` can be undefined at runtime when the CSV's Name column is unmapped.+ if (!name || name.trim() === "") {+ return {+ action: "skip",+ reason: "Missing required Name",+ category: "error"+ };+ }+ if (id && seenIds.has(id)) {+ return {+ action: "skip",+ reason: `Duplicate ID "${id}" in file`,+ category: "skipped"+ };+ }+ if (seenNames.has(name)) {+ return {+ action: "skip",+ reason: `Duplicate name "${name}" in file`,+ category: "skipped"+ };+ }++ // The CSV name is matched as-is. Whitespace/case normalization is intentionally+ // out of scope for this data-loss fix and is handled by the later identity redesign.+ const matchedById = id ? externalIdMap.get(id) : undefined;+ const matchedByName =+ matchedById === undefined ? nameMap.get(name) : undefined;+ const existingEntityId = matchedById ?? matchedByName;++ if (existingEntityId !== undefined) {+ return { action: "update", entityId: existingEntityId };+ }+ return { action: "insert" };+ }+ export type StockImportTable =+ | "inventoryQuantity"+ | "batchQuantity"+ | "serialQuantity";++ // The item tracking type each import accepts.+ export const STOCK_IMPORT_TRACKING_TYPE: Record<StockImportTable, string> = {+ inventoryQuantity: "Inventory",+ batchQuantity: "Batch",+ serialQuantity: "Serial"+ };++ // The import a user should reach for, per tracking type, for the mismatch+ // error message.+ const IMPORT_LABEL_BY_TRACKING_TYPE: Record<string, string> = {+ Inventory: "Inventory Quantities",+ Batch: "Batch Quantities",+ Serial: "Serial Quantities"+ };++ export type StockItemInfo = {+ // More than one item shares this part number + revision AND this import's+ // tracking type, so the row cannot name one item. Reported per row rather+ // than resolved arbitrarily: posting opening stock to the wrong item is+ // silent and expensive to unwind.+ ambiguous?: boolean;+ id: string;+ itemTrackingType: string | null;+ hasItemCost: boolean;+ };++ export type StockRowResolved = {+ itemId: string;+ locationId: string;+ storageUnitId: string | null;+ quantity: number;+ // Batch / serial number; null for Inventory rows.+ readableId: string | null;+ expirationDate: string | null;+ comment: string | null;+ // In-file / existing dedup key for Batch / Serial rows; null for Inventory.+ trackedKey: string | null;+ };++ export type StockRowDecision =+ | { action: "post"; row: StockRowResolved }+ | { action: "skip"; reason: string; category: "error" | "skipped" };++ const text = (s: string | undefined): string => (s ?? "").trim();++ // Same shape as method-import.ts: readableId + revision, blank revision → "0".+ export const itemKey = (readableId: string, revision: string) =>+ `${readableId} ${revision || "0"}`;++ // readableId + revision → item (method-import key). item_unique also includes+ // `type`, so two items (e.g. a Part and a Tool) can share the key. Ties break+ // deterministically: the candidate whose tracking type matches this import+ // wins; otherwise the first candidate in input order (the driver orders the+ // query by type, id).+ export function buildStockItemMap(+ table: StockImportTable,+ candidates: Array<{+ id: string;+ readableId: string;+ revision: string | null;+ itemTrackingType: string | null;+ hasItemCost: boolean;+ }>+ ): Map<string, StockItemInfo> {+ const expected = STOCK_IMPORT_TRACKING_TYPE[table];+ const map = new Map<string, StockItemInfo>();+ for (const c of candidates) {+ const key = itemKey(c.readableId, c.revision ?? "0");+ const current = map.get(key);+ if (!current) {+ map.set(key, {+ id: c.id,+ itemTrackingType: c.itemTrackingType,+ hasItemCost: c.hasItemCost+ });+ continue;+ }+ const currentMatches = current.itemTrackingType === expected;+ const candidateMatches = c.itemTrackingType === expected;+ if (candidateMatches && currentMatches) {+ // Two items of this import's tracking type share the identity: neither+ // can be chosen, so mark the key and let classifyStockRow reject rows.+ map.set(key, { ...current, ambiguous: true });+ continue;+ }+ if (candidateMatches && !currentMatches) {+ map.set(key, {+ id: c.id,+ itemTrackingType: c.itemTrackingType,+ hasItemCost: c.hasItemCost+ });+ }+ }+ return map;+ }++ // Storage unit names are unique per location (storageUnit_name_locationId_key)+ // and resolved case-insensitively — the storageUnit import's natural key.+ export const storageUnitKey = (locationId: string, name: string) =>+ `${locationId}::${name.trim().toLowerCase()}`;++ // A batch / serial number is unique per item, not per company: the same serial+ // on two different items is allowed.+ export const trackedKey = (itemId: string, readableId: string) =>+ `${itemId}::${readableId}`;++ // ISO calendar date (YYYY-MM-DD) that actually exists. Hand-rolled rather than+ // JS Date, which silently rolls 2026-02-30 over to March.+ export function isIsoDate(value: string): boolean {+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);+ if (!match) return false;+ const year = Number(match[1]);+ const month = Number(match[2]);+ const day = Number(match[3]);+ if (month < 1 || month > 12 || day < 1) return false;+ const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;+ const daysInMonth = [+ 31,+ leap ? 29 : 28,+ 31,+ 30,+ 31,+ 30,+ 31,+ 31,+ 30,+ 31,+ 30,+ 31+ ];+ return day <= daysInMonth[month - 1]!;+ }++ export function classifyStockRow(params: {+ table: StockImportTable;+ record: Record<string, string>;+ itemMap: Map<string, StockItemInfo>;+ locationIds: Set<string>;+ storageUnitMap: Map<string, string>;+ existingTrackedKeys: Set<string>;+ seenTrackedKeys: Set<string>;+ }): StockRowDecision {+ const {+ table,+ record,+ itemMap,+ locationIds,+ storageUnitMap,+ existingTrackedKeys,+ seenTrackedKeys+ } = params;+ const error = (reason: string): StockRowDecision => ({+ action: "skip",+ reason,+ category: "error"+ });++ const readableId = text(record.readableId);+ const revision = text(record.revision) || "0";+ if (!readableId) return error("Missing required Part Number");++ const item = itemMap.get(itemKey(readableId, revision));+ if (!item) return error(`Item ${readableId} rev ${revision} not found`);++ const expectedTrackingType = STOCK_IMPORT_TRACKING_TYPE[table];+ if (item.ambiguous) {+ return error(+ `More than one item is ${expectedTrackingType} tracked with part number ${readableId} rev ${revision}`+ );+ }+ if (item.itemTrackingType !== expectedTrackingType) {+ const other = IMPORT_LABEL_BY_TRACKING_TYPE[item.itemTrackingType ?? ""];+ return error(+ other+ ? `Item ${readableId} rev ${revision} is ${item.itemTrackingType} tracked; use the ${other} import`+ : `Item ${readableId} rev ${revision} is ${+ item.itemTrackingType ?? "not"+ } tracked and holds no stock`+ );+ }++ const locationId = text(record.locationId);+ if (!locationId) return error("Missing required Location");+ if (!locationIds.has(locationId)) return error("Location not found");++ const storageUnitName = text(record.storageUnitName);+ let storageUnitId: string | null = null;+ if (storageUnitName) {+ storageUnitId =+ storageUnitMap.get(storageUnitKey(locationId, storageUnitName)) ?? null;+ if (!storageUnitId) {+ return error(+ `Storage unit "${storageUnitName}" not found in this location`+ );+ }+ }++ // Serial rows carry no Quantity: each row is exactly one unit.+ let quantity = 1;+ if (table !== "serialQuantity") {+ const raw = text(record.quantity);+ const parsed = raw === "" ? Number.NaN : Number(raw);+ // Round to posting precision BEFORE validating, and carry the rounded+ // value: buildItemLedgerRow rounds the same way, so a quantity finer than+ // the scale (0.000001) would otherwise report an inserted movement that+ // adds nothing, and leave trackedEntity.quantity disagreeing with the+ // ledger.+ quantity = round(parsed);+ if (!Number.isFinite(parsed) || quantity <= 0) {+ return error("Quantity must be a positive number");+ }+ }++ let trackedNumber: string | null = null;+ if (table === "batchQuantity") {+ trackedNumber = text(record.batchNumber);+ if (!trackedNumber) return error("Missing required Batch Number");+ } else if (table === "serialQuantity") {+ trackedNumber = text(record.serialNumber);+ if (!trackedNumber) return error("Missing required Serial Number");+ }++ let expirationDate: string | null = null;+ if (table !== "inventoryQuantity") {+ const raw = text(record.expirationDate);+ if (raw) {+ if (!isIsoDate(raw)) {+ return error(+ `Expiration Date "${raw}" is not a valid date (use YYYY-MM-DD)`+ );+ }+ expirationDate = raw;+ }+ }++ if (!item.hasItemCost) {+ return error(`Item ${readableId} rev ${revision} has no item cost record`);+ }++ let key: string | null = null;+ if (trackedNumber) {+ const label = table === "serialQuantity" ? "Serial number" : "Batch number";+ key = trackedKey(item.id, trackedNumber);+ if (existingTrackedKeys.has(key)) {+ return {+ action: "skip",+ reason: `${label} "${trackedNumber}" already exists for this item`,+ category: "skipped"+ };+ }+ if (seenTrackedKeys.has(key)) {+ return {+ action: "skip",+ reason: `Duplicate ${label.toLowerCase()} "${trackedNumber}" for this item in file`,+ category: "skipped"+ };+ }+ }++ return {+ action: "post",+ row: {+ itemId: item.id,+ locationId,+ storageUnitId,+ quantity,+ readableId: trackedNumber,+ expirationDate,+ comment: text(record.comment) || null,+ trackedKey: key+ }+ };+ }+ const importCsvTableLogger = getLogger("server-functions", "import-csv");++ type Rec = Record<string, string>;++ type Summary = {+ inserted: number;+ updated: number;+ errors: Array<{ row: number; reason: string }>;+ skipped: Array<{ row: number; reason: string }>;+ };++ // Company-scoped configuration lookups: small, flat, name-keyed tables a+ // customer fills in once during onboarding. They share create-only,+ // skip-duplicate semantics with the material-taxonomy imports+ // (`material-property-import.ts`) rather than the id-mapped upsert the+ // workCenter/process/item paths use, because none of them carries a natural+ // external id — a customer's UoM list is a column of codes, not a keyed+ // export. Every one of these tables has a UNIQUE (name, companyId) constraint,+ // so a duplicate row would otherwise abort the whole transaction instead of+ // reporting one skipped row.+ export type ConfigLookupTable =+ | "unitOfMeasure"+ | "itemPostingGroup"+ | "storageType"+ | "scrapReason"+ | "department";++ const norm = (s: string | undefined) => (s ?? "").trim().toLowerCase();++ const requireName = (r: Rec) => (!r.name?.trim() ? "Name is required" : null);++ type TableConfig = {+ // Row-level validation. Returns a reason string, or null when the row is fine.+ validate: (r: Rec) => string | null;+ // The natural keys used for both in-file dedup and match-against-existing.+ // A table with two unique constraints yields two keys, so a row colliding on+ // either is reported rather than dropped by the ON CONFLICT clause.+ keysOf: (r: Rec) => string[];+ // The same keys, read off a row already in the database.+ keysOfExisting: (r: {+ name: string | null;+ code?: string | null;+ }) => string[];+ // The columns to read off the mapped record, beyond the audit fields.+ values: (r: Rec) => Record<string, string>;+ // Set when the table carries a self-referencing parent applied in a second+ // pass (see `applyParents` below).+ parentField?: "parentDepartmentId";+ };++ // Exported for `config-lookup-import.test.ts` — the validation rules and+ // dedup keys are the parts that fail silently.+ export const CONFIGS: Record<ConfigLookupTable, TableConfig> = {+ unitOfMeasure: {+ validate: (r) => {+ if (!r.code?.trim()) return "Code is required";+ if (r.code.trim().length > 10)+ return "Code must be 10 characters or fewer";+ if (!r.name?.trim()) return "Name is required";+ if (r.name.trim().length > 50)+ return "Name must be 50 characters or fewer";+ return null;+ },+ // `code` and `name` are BOTH unique per company, so both are dedup keys —+ // importing "Each" against an existing EA/Each is a skip with a reason,+ // not a row silently swallowed by ON CONFLICT.+ keysOf: (r) => [`c:${norm(r.code)}`, `n:${norm(r.name)}`],+ keysOfExisting: (r) => [+ `c:${norm(r.code ?? "")}`,+ `n:${norm(r.name ?? "")}`+ ],+ values: (r) => ({ code: r.code!.trim(), name: r.name!.trim() })+ },+ itemPostingGroup: {+ validate: (r) => {+ const reason = requireName(r);+ if (reason) return reason;+ if (r.name!.trim().length > 255)+ return "Name must be 255 characters or fewer";+ return null;+ },+ keysOf: (r) => [norm(r.name)],+ keysOfExisting: (r) => [norm(r.name ?? "")],+ values: (r) => {+ const values: Record<string, string> = { name: r.name!.trim() };+ if (r.description?.trim()) values.description = r.description.trim();+ return values;+ }+ },+ storageType: {+ validate: requireName,+ keysOf: (r) => [norm(r.name)],+ keysOfExisting: (r) => [norm(r.name ?? "")],+ values: (r) => ({ name: r.name!.trim() })+ },+ scrapReason: {+ validate: requireName,+ keysOf: (r) => [norm(r.name)],+ keysOfExisting: (r) => [norm(r.name ?? "")],+ values: (r) => ({ name: r.name!.trim() })+ },+ department: {+ validate: requireName,+ keysOf: (r) => [norm(r.name)],+ keysOfExisting: (r) => [norm(r.name ?? "")],+ values: (r) => ({ name: r.name!.trim() }),+ parentField: "parentDepartmentId"+ }+ };++ const loadExisting = async (+ trx: Kysely<KyselyDatabase> | Transaction<KyselyDatabase>,+ table: ConfigLookupTable,+ companyId: string+ ) => {+ const rows = await trx+ .selectFrom(table)+ .select(table === "unitOfMeasure" ? ["id", "name", "code"] : ["id", "name"])+ .where("companyId", "=", companyId)+ .execute();+ return rows as Array<{ id: string; name: string | null; code?: string }>;+ };++ // Parents are applied AFTER every insert, as individual UPDATEs outside the+ // insert transaction, so a parent defined further down the same file still+ // resolves and an unresolved or self-referencing parent reports one row error+ // instead of rolling the whole import back. Mirrors the storage-unit parent+ // pass in `index.ts`.+ const applyParents = async (+ db: Kysely<KyselyDatabase>,+ table: ConfigLookupTable,+ parentField: "parentDepartmentId",+ pending: Array<{ row: number; name: string; parentName: string }>,+ companyId: string,+ summary: Summary+ ) => {+ if (pending.length === 0) return;++ const idsByName = new Map<string, string>();+ for (const row of await loadExisting(db, table, companyId)) {+ idsByName.set(norm(row.name ?? ""), row.id);+ }++ for (const { row, name, parentName } of pending) {+ const id = idsByName.get(norm(name));+ if (!id) continue;++ if (norm(parentName) === norm(name)) {+ summary.errors.push({ row, reason: "A record cannot be its own parent" });+ continue;+ }++ const parentId = idsByName.get(norm(parentName));+ if (!parentId) {+ summary.errors.push({+ row,+ reason: `Parent "${parentName}" was not found`+ });+ continue;+ }++ try {+ await db+ .updateTable(table)+ .set({ [parentField]: parentId } as never)+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ } catch (err) {+ summary.errors.push({ row, reason: (err as Error).message });+ }+ }+ };++ export async function importConfigLookups(+ db: Kysely<KyselyDatabase>,+ {+ table,+ mappedRecords,+ companyId,+ userId,+ summary+ }: {+ table: ConfigLookupTable;+ mappedRecords: Rec[];+ companyId: string;+ userId: string;+ summary: Summary;+ }+ ) {+ const config = CONFIGS[table];+ const pendingParents: Array<{+ row: number;+ name: string;+ parentName: string;+ }> = [];++ await db.transaction().execute(async (trx) => {+ const existingKeys = new Set(+ (await loadExisting(trx, table, companyId)).flatMap(config.keysOfExisting)+ );++ const seenKeys = new Set<string>();+ const accepted: Rec[] = [];++ for (const [rowIndex, record] of mappedRecords.entries()) {+ const reason = config.validate(record);+ if (reason) {+ summary.errors.push({ row: rowIndex, reason });+ continue;+ }++ const keys = config.keysOf(record);+ if (keys.some((k) => existingKeys.has(k))) {+ summary.skipped.push({+ row: rowIndex,+ reason: "Already exists — skipped"+ });+ continue;+ }+ if (keys.some((k) => seenKeys.has(k))) {+ summary.skipped.push({+ row: rowIndex,+ reason: "Duplicate row in file — skipped"+ });+ continue;+ }++ for (const key of keys) seenKeys.add(key);+ accepted.push(record);++ if (config.parentField && record.parentName?.trim()) {+ pendingParents.push({+ row: rowIndex,+ name: record.name!.trim(),+ parentName: record.parentName.trim()+ });+ }+ }++ importCsvTableLogger.info("import-config-lookups", {+ table,+ totalRecords: mappedRecords.length,+ accepted: accepted.length,+ skipped: summary.skipped.length,+ errors: summary.errors.length+ });++ if (accepted.length > 0) {+ const now = datetime.timestamp();+ const inserted = await inChunks(+ accepted.map(+ (r) =>+ ({+ ...config.values(r),+ companyId,+ createdBy: userId,+ createdAt: now+ }) as never+ ),+ (rows) =>+ trx+ .insertInto(table)+ .values(rows)+ .onConflict((oc) => oc.doNothing())+ .returning(["id"])+ .execute()+ );+ summary.inserted += inserted.length;+ }+ });++ if (config.parentField) {+ await applyParents(+ db,+ table,+ config.parentField,+ pendingParents,+ companyId,+ summary+ );+ }+ }+ export type MaterialPropertyTable =+ | "materialSubstance"+ | "materialForm"+ | "materialFinish"+ | "materialGrade"+ | "materialType"+ | "materialDimension";++ const isMetricValue = (s: string | undefined) => {+ const v = norm(s);+ return (+ v === "true" || v === "1" || v === "yes" || v === "y" || v === "metric"+ );+ };++ const SUBSTANCE_UNMATCHED =+ "Substance could not be matched — make sure the substance exists and is mapped in the wizard";++ const SHAPE_UNMATCHED =+ "Shape could not be matched — make sure the shape exists and is mapped in the wizard";++ type ParentSpec = {+ field: "materialSubstanceId" | "materialFormId";+ table: "materialSubstance" | "materialForm";+ reason: string;+ };++ type materialPropertyImportTableConfig = {+ validate: (r: Rec) => string | null;+ keysOf: (r: Rec) => string[];+ loadExistingKeys: (+ trx: Transaction<KyselyDatabase>,+ companyId: string+ ) => Promise<Set<string>>;+ insert: (+ trx: Transaction<KyselyDatabase>,+ rows: Rec[],+ companyId: string,+ userId: string+ ) => Promise<number>;+ parents?: ParentSpec[];+ };++ const loadParentIds = async (+ trx: Transaction<KyselyDatabase>,+ table: "materialSubstance" | "materialForm",+ companyId: string+ ): Promise<Set<string>> => {+ const rows =+ table === "materialSubstance"+ ? await trx+ .selectFrom("materialSubstance")+ .select(["id"])+ .where((eb) =>+ eb.or([+ eb("companyId", "=", companyId),+ eb("companyId", "is", null)+ ])+ )+ .execute()+ : await trx+ .selectFrom("materialForm")+ .select(["id"])+ .where((eb) =>+ eb.or([+ eb("companyId", "=", companyId),+ eb("companyId", "is", null)+ ])+ )+ .execute();+ return new Set(rows.map((x) => x.id));+ };++ const materialPropertyImportCONFIGS: Record<+ MaterialPropertyTable,+ materialPropertyImportTableConfig+ > = {+ materialSubstance: {+ validate: (r) =>+ !r.name?.trim()+ ? "Name is required"+ : !r.code?.trim()+ ? "Code is required"+ : null,+ keysOf: (r) => [`c:${norm(r.code)}`],+ loadExistingKeys: async (trx, companyId) => {+ const rows = await trx+ .selectFrom("materialSubstance")+ .select(["code"])+ .where((eb) =>+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])+ )+ .execute();+ return new Set(rows.map((x) => `c:${norm(x.code ?? "")}`));+ },+ insert: async (trx, rows, companyId, userId) => {+ const now = datetime.timestamp();+ const inserted = await inChunks(+ rows.map(+ (r) =>+ ({+ name: r.name!.trim(),+ code: r.code!.trim(),+ companyId,+ createdBy: userId,+ createdAt: now+ }) as never+ ),+ (rows) =>+ trx+ .insertInto("materialSubstance")+ .values(rows)+ .onConflict((oc) => oc.doNothing())+ .returning(["id"])+ .execute()+ );+ return inserted.length;+ }+ },+ materialForm: {+ validate: (r) =>+ !r.name?.trim()+ ? "Name is required"+ : !r.code?.trim()+ ? "Code is required"+ : null,+ keysOf: (r) => [`c:${norm(r.code)}`],+ loadExistingKeys: async (trx, companyId) => {+ const rows = await trx+ .selectFrom("materialForm")+ .select(["code"])+ .where((eb) =>+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])+ )+ .execute();+ return new Set(rows.map((x) => `c:${norm(x.code ?? "")}`));+ },+ insert: async (trx, rows, companyId, userId) => {+ const now = datetime.timestamp();+ const inserted = await inChunks(+ rows.map(+ (r) =>+ ({+ name: r.name!.trim(),+ code: r.code!.trim(),+ companyId,+ createdBy: userId,+ createdAt: now+ }) as never+ ),+ (rows) =>+ trx+ .insertInto("materialForm")+ .values(rows)+ .onConflict((oc) => oc.doNothing())+ .returning(["id"])+ .execute()+ );+ return inserted.length;+ }+ },+ materialFinish: {+ parents: [+ {+ field: "materialSubstanceId",+ table: "materialSubstance",+ reason: SUBSTANCE_UNMATCHED+ }+ ],+ validate: (r) =>+ !r.name?.trim()+ ? "Name is required"+ : !r.materialSubstanceId?.trim()+ ? SUBSTANCE_UNMATCHED+ : null,+ keysOf: (r) => [`${r.materialSubstanceId!.trim()}:${norm(r.name)}`],+ loadExistingKeys: async (trx, companyId) => {+ const rows = await trx+ .selectFrom("materialFinish")+ .select(["materialSubstanceId", "name"])+ .where((eb) =>+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])+ )+ .execute();+ return new Set(+ rows.map((x) => `${x.materialSubstanceId}:${norm(x.name)}`)+ );+ },+ insert: async (trx, rows, companyId) => {+ const inserted = await inChunks(+ rows.map(+ (r) =>+ ({+ name: r.name!.trim(),+ materialSubstanceId: r.materialSubstanceId!.trim(),+ companyId+ }) as never+ ),+ (rows) =>+ trx+ .insertInto("materialFinish")+ .values(rows)+ .onConflict((oc) => oc.doNothing())+ .returning(["id"])+ .execute()+ );+ return inserted.length;+ }+ },+ materialGrade: {+ parents: [+ {+ field: "materialSubstanceId",+ table: "materialSubstance",+ reason: SUBSTANCE_UNMATCHED+ }+ ],+ validate: (r) =>+ !r.name?.trim()+ ? "Name is required"+ : !r.materialSubstanceId?.trim()+ ? SUBSTANCE_UNMATCHED+ : null,+ keysOf: (r) => [`${r.materialSubstanceId!.trim()}:${norm(r.name)}`],+ loadExistingKeys: async (trx, companyId) => {+ const rows = await trx+ .selectFrom("materialGrade")+ .select(["materialSubstanceId", "name"])+ .where((eb) =>+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])+ )+ .execute();+ return new Set(+ rows.map((x) => `${x.materialSubstanceId}:${norm(x.name)}`)+ );+ },+ insert: async (trx, rows, companyId) => {+ const inserted = await inChunks(+ rows.map(+ (r) =>+ ({+ name: r.name!.trim(),+ materialSubstanceId: r.materialSubstanceId!.trim(),+ companyId+ }) as never+ ),+ (rows) =>+ trx+ .insertInto("materialGrade")+ .values(rows)+ .onConflict((oc) => oc.doNothing())+ .returning(["id"])+ .execute()+ );+ return inserted.length;+ }+ },+ materialType: {+ parents: [+ {+ field: "materialSubstanceId",+ table: "materialSubstance",+ reason: SUBSTANCE_UNMATCHED+ },+ {+ field: "materialFormId",+ table: "materialForm",+ reason: SHAPE_UNMATCHED+ }+ ],+ validate: (r) =>+ !r.name?.trim()+ ? "Name is required"+ : !r.code?.trim()+ ? "Code is required"+ : !r.materialSubstanceId?.trim()+ ? SUBSTANCE_UNMATCHED+ : !r.materialFormId?.trim()+ ? SHAPE_UNMATCHED+ : null,+ keysOf: (r) => {+ const sub = r.materialSubstanceId!.trim();+ const form = r.materialFormId!.trim();+ return [+ `${sub}:${form}:c:${norm(r.code)}`,+ `${sub}:${form}:n:${norm(r.name)}`+ ];+ },+ loadExistingKeys: async (trx, companyId) => {+ const rows = await trx+ .selectFrom("materialType")+ .select(["materialSubstanceId", "materialFormId", "code", "name"])+ .where((eb) =>+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])+ )+ .execute();+ const set = new Set<string>();+ for (const x of rows) {+ set.add(+ `${x.materialSubstanceId}:${x.materialFormId}:c:${norm(x.code ?? "")}`+ );+ set.add(+ `${x.materialSubstanceId}:${x.materialFormId}:n:${norm(x.name)}`+ );+ }+ return set;+ },+ insert: async (trx, rows, companyId) => {+ const inserted = await inChunks(+ rows.map(+ (r) =>+ ({+ name: r.name!.trim(),+ code: r.code!.trim(),+ materialSubstanceId: r.materialSubstanceId!.trim(),+ materialFormId: r.materialFormId!.trim(),+ companyId+ }) as never+ ),+ (rows) =>+ trx+ .insertInto("materialType")+ .values(rows)+ .onConflict((oc) => oc.doNothing())+ .returning(["id"])+ .execute()+ );+ return inserted.length;+ }+ },+ materialDimension: {+ parents: [+ {+ field: "materialFormId",+ table: "materialForm",+ reason: SHAPE_UNMATCHED+ }+ ],+ validate: (r) =>+ !r.name?.trim()+ ? "Name is required"+ : !r.materialFormId?.trim()+ ? SHAPE_UNMATCHED+ : null,+ keysOf: (r) => [`${r.materialFormId!.trim()}:${norm(r.name)}`],+ loadExistingKeys: async (trx, companyId) => {+ const rows = await trx+ .selectFrom("materialDimension")+ .select(["materialFormId", "name"])+ .where((eb) =>+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])+ )+ .execute();+ return new Set(rows.map((x) => `${x.materialFormId}:${norm(x.name)}`));+ },+ insert: async (trx, rows, companyId) => {+ const inserted = await inChunks(+ rows.map(+ (r) =>+ ({+ name: r.name!.trim(),+ materialFormId: r.materialFormId!.trim(),+ isMetric: isMetricValue(r.isMetric),+ companyId+ }) as never+ ),+ (rows) =>+ trx+ .insertInto("materialDimension")+ .values(rows)+ .onConflict((oc) => oc.doNothing())+ .returning(["id"])+ .execute()+ );+ return inserted.length;+ }+ }+ };++ export async function importMaterialProperties(+ db: Kysely<KyselyDatabase>,+ {+ table,+ mappedRecords,+ companyId,+ userId,+ summary+ }: {+ table: MaterialPropertyTable;+ mappedRecords: Rec[];+ companyId: string;+ userId: string;+ summary: Summary;+ }+ ) {+ const config = materialPropertyImportCONFIGS[table];++ await db.transaction().execute(async (trx) => {+ const existingKeys = await config.loadExistingKeys(trx, companyId);++ const parentSpecs = config.parents ?? [];+ const parentIds = new Map<string, Set<string>>();+ for (const parentTable of new Set(parentSpecs.map((p) => p.table))) {+ parentIds.set(+ parentTable,+ await loadParentIds(trx, parentTable, companyId)+ );+ }++ const seenKeys = new Set<string>();+ const accepted: Rec[] = [];++ for (const [rowIndex, record] of mappedRecords.entries()) {+ const reason = config.validate(record);+ if (reason) {+ summary.errors.push({ row: rowIndex, reason });+ continue;+ }++ const foreignParent = parentSpecs.find(+ (p) => !parentIds.get(p.table)?.has((record[p.field] ?? "").trim())+ );+ if (foreignParent) {+ summary.errors.push({ row: rowIndex, reason: foreignParent.reason });+ continue;+ }++ const keys = config.keysOf(record);+ if (keys.some((k) => existingKeys.has(k))) {+ summary.skipped.push({+ row: rowIndex,+ reason: "Already exists — skipped"+ });+ continue;+ }+ if (keys.some((k) => seenKeys.has(k))) {+ summary.skipped.push({+ row: rowIndex,+ reason: "Duplicate row in file — skipped"+ });+ continue;+ }++ keys.forEach((k) => seenKeys.add(k));+ accepted.push(record);+ }++ importCsvTableLogger.info("import-material-properties", {+ table,+ totalRecords: mappedRecords.length,+ accepted: accepted.length,+ skipped: summary.skipped.length,+ errors: summary.errors.length+ });++ if (accepted.length > 0) {+ summary.inserted += await config.insert(trx, accepted, companyId, userId);+ }+ });+ }+ const ROW_TYPES = ["PART", "BOM", "BOP", "STEP", "TOOL", "PARAM"] as const;++ type RowType = (typeof ROW_TYPES)[number];++ const STEP_TYPES = [+ "Task",+ "Value",+ "Measurement",+ "Checkbox",+ "Timestamp",+ "Person",+ "List",+ "File",+ "Inspection"+ ] as const;++ type Entry = { record: Rec; index: number };++ type VersionBucket = {+ bom: Entry[];+ bop: Entry[];+ step: Entry[];+ tool: Entry[];+ param: Entry[];+ };++ type Group = {+ readableId: string;+ revision: string;+ firstIndex: number;+ partRow?: Entry;+ versions: Map<string, VersionBucket>;+ };++ type ItemInfo = {+ id: string;+ type: string;+ defaultMethodType: string | null;+ sourcingType: string | null;+ };++ // ---------------------------------------------------------------------------+ // small helpers+ // ---------------------------------------------------------------------------++ const key = (readableId: string, revision: string) =>+ `${readableId} ${revision || "0"}`;++ const num = (s: string | undefined): number | undefined => {+ if (s === undefined || s.trim() === "") return undefined;+ const n = Number(s);+ return Number.isFinite(n) ? n : undefined;+ };++ const bool = (s: string | undefined): boolean =>+ typeof s === "string" && s.trim().toLowerCase() === "true";++ // Legacy CSV templates may still use the old "Inside"/"Outside" operation types.+ const normalizeOperationType = (value: string): string =>+ value === "Inside"+ ? "Process"+ : value === "Outside"+ ? "Outside Processing"+ : value;++ // The `row` reported on each error: the 0-based index of the data row. This must+ // match how the results modal keys errors to rows (by array index into the parsed+ // rows) and the standard importer in index.ts — NOT a human CSV line number.+ const rowOf = (index: number) => index;++ // Plain text → minimal tiptap doc for a step's rich-text description.+ function plainTextToTiptap(value: string): Record<string, unknown> {+ const t = (value ?? "").trim();+ if (!t) return {};+ return {+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: t }] }]+ };+ }++ function normalizeRowType(+ raw: string | undefined,+ table: string+ ): RowType | null {+ const v = (raw ?? "").trim().toUpperCase();+ // The BOM file is homogeneous — every row is a BOM line — so a blank Row Type+ // defaults to BOM. The operations and combined files are multi-type (BOP/STEP/+ // TOOL/PARAM, +PART), so Row Type is a required discriminator there.+ if (!v) return table === "bom" ? "BOM" : null;+ return (ROW_TYPES as readonly string[]).includes(v) ? (v as RowType) : null;+ }++ // ---------------------------------------------------------------------------+ // entry point+ // ---------------------------------------------------------------------------++ export async function importMethods(+ db: Kysely<KyselyDatabase>,+ args: {+ table: "bom" | "operations" | "partWithMethod";+ mappedRecords: Rec[];+ companyId: string;+ userId: string;+ summary: Summary;+ }+ ): Promise<void> {+ const { table, mappedRecords, companyId, userId, summary } = args;++ // 1. classify + group by parent part ------------------------------------+ const groups = new Map<string, Group>();+ const getGroup = (readableId: string, revision: string, index: number) => {+ const k = key(readableId, revision);+ let g = groups.get(k);+ if (!g) {+ g = {+ readableId,+ revision: revision || "0",+ firstIndex: index,+ versions: new Map()+ };+ groups.set(k, g);+ }+ return g;+ };+ const getBucket = (g: Group, version: string): VersionBucket => {+ let b = g.versions.get(version);+ if (!b) {+ b = { bom: [], bop: [], step: [], tool: [], param: [] };+ g.versions.set(version, b);+ }+ return b;+ };++ mappedRecords.forEach((record, index) => {+ const rowType = normalizeRowType(record.rowType, table);+ if (!rowType) {+ summary.errors.push({+ row: rowOf(index),+ reason: `Unknown or missing Row Type "${text(record.rowType)}"`+ });+ return;+ }++ if (rowType === "PART") {+ const readableId = text(record.readableId);+ if (!readableId) {+ summary.errors.push({+ row: rowOf(index),+ reason: "PART row is missing Part Number"+ });+ return;+ }+ const g = getGroup(readableId, text(record.revision), index);+ g.partRow = { record, index };+ return;+ }++ // BOM / BOP / STEP / TOOL / PARAM — keyed to a parent part.+ const parentId = text(record.parentId);+ if (!parentId) {+ summary.errors.push({+ row: rowOf(index),+ reason: `${rowType} row is missing Parent ID`+ });+ return;+ }+ const g = getGroup(parentId, text(record.parentRevision), index);+ const bucket = getBucket(g, text(record.makeMethodVersion));+ const entry = { record, index };+ if (rowType === "BOM") bucket.bom.push(entry);+ else if (rowType === "BOP") bucket.bop.push(entry);+ else if (rowType === "STEP") bucket.step.push(entry);+ else if (rowType === "TOOL") bucket.tool.push(entry);+ else if (rowType === "PARAM") bucket.param.push(entry);+ });++ if (groups.size === 0) return;++ // 2. collect reference lookups ------------------------------------------+ const readableIds = new Set<string>();+ const processNames = new Set<string>();+ const workCenterNames = new Set<string>();+ const uomCodes = new Set<string>();+ const supplierNames = new Set<string>();++ for (const g of groups.values()) {+ readableIds.add(g.readableId);+ for (const bucket of g.versions.values()) {+ for (const e of bucket.bom) {+ if (text(e.record.componentId))+ readableIds.add(text(e.record.componentId));+ if (text(e.record.unitOfMeasureCode))+ uomCodes.add(text(e.record.unitOfMeasureCode));+ }+ for (const e of bucket.bop) {+ if (text(e.record.process))+ processNames.add(text(e.record.process).toLowerCase());+ if (text(e.record.workCenter))+ workCenterNames.add(text(e.record.workCenter).toLowerCase());+ if (text(e.record.supplier))+ supplierNames.add(text(e.record.supplier).toLowerCase());+ }+ for (const e of bucket.tool) {+ if (text(e.record.toolId)) readableIds.add(text(e.record.toolId));+ }+ for (const e of bucket.step) {+ if (text(e.record.stepUnitOfMeasureCode))+ uomCodes.add(text(e.record.stepUnitOfMeasureCode));+ }+ }+ }++ const itemMap = new Map<string, ItemInfo>();+ if (readableIds.size > 0) {+ const rows = await db+ .selectFrom("item")+ .select([+ "id",+ "readableId",+ "revision",+ "type",+ "defaultMethodType",+ "sourcingType"+ ])+ .where("companyId", "=", companyId)+ .where("readableId", "in", Array.from(readableIds))+ .execute();+ for (const r of rows) {+ const k = key(r.readableId, r.revision ?? "0");+ if (!itemMap.has(k)) {+ itemMap.set(k, {+ id: r.id,+ type: r.type,+ defaultMethodType: r.defaultMethodType ?? null,+ sourcingType: r.sourcingType ?? null+ });+ }+ }+ }++ const { map: processMap, ambiguous: processAmbiguous } = await nameMap(+ db,+ "process",+ companyId,+ processNames+ );+ const { map: workCenterMap, ambiguous: workCenterAmbiguous } = await nameMap(+ db,+ "workCenter",+ companyId,+ workCenterNames+ );++ const uomSet = new Set<string>();+ if (uomCodes.size > 0) {+ const rows = await db+ .selectFrom("unitOfMeasure")+ .select(["code"])+ .where("companyId", "=", companyId)+ .execute();+ for (const r of rows) uomSet.add(r.code);+ }++ const supplierMap = new Map<string, string>();+ if (supplierNames.size > 0) {+ const rows = await db+ .selectFrom("supplier")+ .select(["id", "name", "readableId"])+ .where("companyId", "=", companyId)+ .execute();+ for (const r of rows) {+ supplierMap.set(r.name.toLowerCase(), r.id);+ if (r.readableId) supplierMap.set(r.readableId.toLowerCase(), r.id);+ }+ }++ // Set of parts that this file will create (so a same-file sub-assembly counts+ // as resolvable during validation even though it doesn't exist yet).+ const fileCreatedParts = new Set<string>();+ for (const g of groups.values()) {+ if (g.partRow) fileCreatedParts.add(key(g.readableId, g.revision));+ }++ // 3 + 4. validate and write each part group ------------------------------+ for (const g of groups.values()) {+ const partLabel = `${g.readableId} rev ${g.revision}`;+ const errors = validateGroup(g, {+ itemMap,+ fileCreatedParts,+ processMap,+ processAmbiguous,+ workCenterMap,+ workCenterAmbiguous,+ uomSet+ });++ if (errors.length > 0) {+ for (const e of errors) summary.errors.push(e);+ continue;+ }++ try {+ const result = await writeGroup(db, g, {+ companyId,+ userId,+ itemMap,+ processMap,+ workCenterMap,+ supplierMap+ });+ if (result.filledAny) {+ // A new part counts as imported; an existing part as updated.+ if (g.partRow) summary.inserted++;+ else summary.updated++;+ } else if (result.skippedExisting) {+ // The targeted version already had content — create-only, never clobber.+ // Benign: not something the user needs to fix, so it's a skip, not an error.+ summary.skipped.push({+ row: rowOf(g.firstIndex),+ reason: `Part ${partLabel} already has a method; skipped`+ });+ } else if (g.partRow) {+ // A PART row with no BOM/BOP rows — only the part itself was created.+ summary.inserted++;+ }+ } catch (err) {+ summary.errors.push({+ row: rowOf(g.firstIndex),+ reason: `Part ${partLabel} failed to import: ${+ err instanceof Error ? err.message : String(err)+ }`+ });+ }+ }+ }++ // ---------------------------------------------------------------------------+ // reference helpers+ // ---------------------------------------------------------------------------++ async function nameMap(+ db: Kysely<KyselyDatabase>,+ table: "process" | "workCenter",+ companyId: string,+ names: Set<string>+ ): Promise<{ map: Map<string, string>; ambiguous: Set<string> }> {+ const map = new Map<string, string>();+ const ambiguous = new Set<string>();+ if (names.size === 0) return { map, ambiguous };++ const rows = await db+ .selectFrom(table)+ .select(["id", "name"])+ .where("companyId", "=", companyId)+ .execute();+ for (const r of rows) {+ const lower = r.name.toLowerCase();+ if (map.has(lower)) ambiguous.add(lower);+ else map.set(lower, r.id);+ }+ return { map, ambiguous };+ }++ // ---------------------------------------------------------------------------+ // validation (pure, given the resolved lookups)+ // ---------------------------------------------------------------------------++ type Lookups = {+ itemMap: Map<string, ItemInfo>;+ fileCreatedParts: Set<string>;+ processMap: Map<string, string>;+ processAmbiguous: Set<string>;+ workCenterMap: Map<string, string>;+ workCenterAmbiguous: Set<string>;+ uomSet: Set<string>;+ };++ function validateGroup(+ g: Group,+ lk: Lookups+ ): Array<{ row: number; reason: string }> {+ const errors: Array<{ row: number; reason: string }> = [];+ const parentKey = key(g.readableId, g.revision);+ const partLabel = `${g.readableId} rev ${g.revision}`;++ // Parent must be makeable (Part or Tool). A part created by this file is makeable.+ if (!g.partRow) {+ const parent = lk.itemMap.get(parentKey);+ if (!parent) {+ errors.push({+ row: rowOf(g.firstIndex),+ reason: `Parent part ${partLabel} not found`+ });+ } else if (parent.type !== "Part" && parent.type !== "Tool") {+ errors.push({+ row: rowOf(g.firstIndex),+ reason: `Parent ${partLabel} is a ${parent.type}; only a Part or Tool can own a method`+ });+ }+ }++ for (const bucket of g.versions.values()) {+ // Op No uniqueness within the parent + a set to validate child references.+ const opNos = new Set<string>();+ for (const e of bucket.bop) {+ const opNo = text(e.record.opNo);+ if (!opNo) {+ errors.push({+ row: rowOf(e.index),+ reason: "BOP row is missing Op No"+ });+ continue;+ }+ if (opNos.has(opNo)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Duplicate Op No "${opNo}" for ${partLabel}`+ });+ }+ opNos.add(opNo);++ // process required + resolvable+ const proc = text(e.record.process).toLowerCase();+ if (!proc) {+ errors.push({+ row: rowOf(e.index),+ reason: `Op ${opNo}: Process is required`+ });+ } else if (lk.processAmbiguous.has(proc)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Op ${opNo}: Process name is ambiguous`+ });+ } else if (!lk.processMap.has(proc)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Op ${opNo}: Process "${text(e.record.process)}" not found`+ });+ }++ const wc = text(e.record.workCenter).toLowerCase();+ if (wc) {+ if (lk.workCenterAmbiguous.has(wc)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Op ${opNo}: Work Center name is ambiguous`+ });+ } else if (!lk.workCenterMap.has(wc)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Op ${opNo}: Work Center "${text(e.record.workCenter)}" not found`+ });+ }+ }++ // In-house operations need time units.+ const opType =+ normalizeOperationType(text(e.record.operationType)) || "Process";+ if (opType !== "Outside Processing") {+ if (+ !text(e.record.setupUnit) ||+ !text(e.record.laborUnit) ||+ !text(e.record.machineUnit)+ ) {+ errors.push({+ row: rowOf(e.index),+ reason: `Op ${opNo}: In-house operations require Setup, Labor, and Machine units`+ });+ }+ }+ }++ // BOM lines+ for (const e of bucket.bom) {+ const componentId = text(e.record.componentId);+ if (!componentId) {+ errors.push({+ row: rowOf(e.index),+ reason: "BOM row is missing Material ID"+ });+ continue;+ }+ const compKey = key(componentId, text(e.record.componentRevision));+ if (!lk.itemMap.has(compKey) && !lk.fileCreatedParts.has(compKey)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Material ${componentId} rev ${text(e.record.componentRevision) || "0"} not found`+ });+ }+ if (num(e.record.quantity) === undefined) {+ errors.push({+ row: rowOf(e.index),+ reason: "BOM row has an invalid Quantity"+ });+ }+ const uom = text(e.record.unitOfMeasureCode);+ if (uom && !lk.uomSet.has(uom)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Unit of Measure "${uom}" not found`+ });+ }+ }++ // STEP / TOOL / PARAM must reference a known Op No within this version.+ for (const e of bucket.step) {+ const opNo = text(e.record.opNo);+ if (!opNos.has(opNo)) {+ errors.push({+ row: rowOf(e.index),+ reason: `STEP references unknown Op No "${opNo}"`+ });+ }+ if (!text(e.record.stepName)) {+ errors.push({+ row: rowOf(e.index),+ reason: "STEP row is missing Name"+ });+ }+ const stepType = text(e.record.stepType) || "Task";+ if (!(STEP_TYPES as readonly string[]).includes(stepType)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Invalid Step Type "${stepType}"`+ });+ }+ if (stepType === "Measurement" && !text(e.record.stepUnitOfMeasureCode)) {+ errors.push({+ row: rowOf(e.index),+ reason: "Measurement step requires a Step Unit of Measure"+ });+ }+ if (stepType === "List" && !text(e.record.stepListValues)) {+ errors.push({+ row: rowOf(e.index),+ reason: "List step requires Step List Values"+ });+ }+ }+ for (const e of bucket.tool) {+ const opNo = text(e.record.opNo);+ if (!opNos.has(opNo)) {+ errors.push({+ row: rowOf(e.index),+ reason: `TOOL references unknown Op No "${opNo}"`+ });+ }+ const toolId = text(e.record.toolId);+ if (!toolId) {+ errors.push({+ row: rowOf(e.index),+ reason: "TOOL row is missing Tool ID"+ });+ } else {+ const toolKey = key(toolId, text(e.record.toolRevision));+ if (!lk.itemMap.has(toolKey) && !lk.fileCreatedParts.has(toolKey)) {+ errors.push({+ row: rowOf(e.index),+ reason: `Tool ${toolId} rev ${text(e.record.toolRevision) || "0"} not found`+ });+ }+ }+ if (num(e.record.toolQuantity) === undefined) {+ errors.push({+ row: rowOf(e.index),+ reason: "TOOL row has an invalid Quantity"+ });+ }+ }+ for (const e of bucket.param) {+ const opNo = text(e.record.opNo);+ if (!opNos.has(opNo)) {+ errors.push({+ row: rowOf(e.index),+ reason: `PARAM references unknown Op No "${opNo}"`+ });+ }+ if (!text(e.record.paramKey)) {+ errors.push({+ row: rowOf(e.index),+ reason: "PARAM row is missing Key"+ });+ }+ if (!text(e.record.paramValue)) {+ errors.push({+ row: rowOf(e.index),+ reason: "PARAM row is missing Value"+ });+ }+ }+ }++ return errors;+ }++ // ---------------------------------------------------------------------------+ // write (one transaction per part group → atomic per part, ADR-0001)+ // ---------------------------------------------------------------------------++ async function writeGroup(+ db: Kysely<KyselyDatabase>,+ g: Group,+ ctx: {+ companyId: string;+ userId: string;+ itemMap: Map<string, ItemInfo>;+ processMap: Map<string, string>;+ workCenterMap: Map<string, string>;+ supplierMap: Map<string, string>;+ }+ ): Promise<{ filledAny: boolean; skippedExisting: boolean }> {+ const { companyId, userId } = ctx;+ const now = () => datetime.timestamp();++ return await db.transaction().execute(async (trx) => {+ let filledAny = false;+ let skippedExisting = false;++ // Resolve (or create) the parent item.+ let parentItemId: string;+ if (g.partRow) {+ const r = g.partRow.record;+ const inserted = await trx+ .insertInto("item")+ .values([+ {+ readableId: g.readableId,+ revision: g.revision || "0",+ name: text(r.name) || g.readableId,+ mpn: text(r.mpn) || undefined,+ type: "Part",+ companyId,+ active: text(r.active).toLowerCase() !== "false",+ replenishmentSystem: text(r.replenishmentSystem) || "Buy and Make",+ defaultMethodType: text(r.defaultMethodType) || undefined,+ itemTrackingType: text(r.itemTrackingType) || "Inventory",+ unitOfMeasureCode: text(r.unitOfMeasureCode) || "EA",+ createdAt: now(),+ createdBy: userId+ } as never+ ])+ // Re-running the same file upserts the item rather than duplicating it.+ .onConflict((oc) =>+ oc.constraint("item_unique").doUpdateSet({+ updatedAt: now(),+ updatedBy: userId+ } as never)+ )+ .returning(["id"])+ .execute();+ parentItemId = inserted[0]!.id;++ // The makeMethod Draft v1 is created by the AFTER INSERT trigger on item.+ // The part row links to the item by readableId (part.id = item.readableId).+ await trx+ .insertInto("part")+ .values([+ {+ id: g.readableId,+ companyId,+ approved: true,+ createdAt: now(),+ createdBy: userId+ } as never+ ])+ .onConflict((oc) => oc.columns(["id", "companyId"]).doNothing())+ .execute();+ } else {+ const parent = ctx.itemMap.get(key(g.readableId, g.revision));+ parentItemId = parent!.id;+ }++ for (const [version, bucket] of g.versions) {+ const makeMethodId = await ensureMakeMethod(+ trx,+ parentItemId,+ version,+ companyId,+ userId+ );++ // Create-only: fill a version only if it has no method content yet.+ const hasMaterial = await trx+ .selectFrom("methodMaterial")+ .select("id")+ .where("makeMethodId", "=", makeMethodId)+ .limit(1)+ .executeTakeFirst();+ const hasOperation = await trx+ .selectFrom("methodOperation")+ .select("id")+ .where("makeMethodId", "=", makeMethodId)+ .limit(1)+ .executeTakeFirst();+ if (hasMaterial || hasOperation) {+ skippedExisting = true;+ continue;+ }++ // --- materials (BOM), in file row order ---+ let order = 1;+ for (const e of bucket.bom) {+ const r = e.record;+ const component = await resolveItem(+ trx,+ companyId,+ text(r.componentId),+ text(r.componentRevision),+ ctx.itemMap+ );+ const methodType = component.defaultMethodType ?? "Pull from Inventory";+ const sourcingType = component.sourcingType ?? "Specified";++ let materialMakeMethodId: string | null = null;+ if (methodType === "Make to Order") {+ materialMakeMethodId = await currentMakeMethodId(+ trx,+ component.id,+ companyId+ );+ }++ const storageUnitIds = await seedStorageUnitIds(trx, component.id);++ await trx+ .insertInto("methodMaterial")+ .values([+ {+ makeMethodId,+ itemId: component.id,+ itemType: component.type,+ methodType,+ sourcingType,+ materialMakeMethodId,+ quantity: num(r.quantity) ?? 1,+ unitOfMeasureCode: text(r.unitOfMeasureCode) || "EA",+ order,+ kit: bool(r.kit),+ storageUnitIds,+ companyId,+ createdBy: userId,+ createdAt: now()+ } as never+ ])+ .execute();+ order++;+ filledAny = true;+ }++ // --- operations (BOP), keyed by Op No ---+ const opIdByNo = new Map<string, string>();+ let opIndex = 1;+ for (const e of bucket.bop) {+ const r = e.record;+ const opNo = text(r.opNo);+ const opType =+ normalizeOperationType(text(r.operationType)) || "Process";+ const processId = ctx.processMap.get(text(r.process).toLowerCase())!;+ const workCenterId = text(r.workCenter)+ ? ctx.workCenterMap.get(text(r.workCenter).toLowerCase())+ : undefined;++ let operationSupplierProcessId: string | undefined;+ if (opType === "Outside Processing" && text(r.supplier)) {+ operationSupplierProcessId = await resolveSupplierProcess(+ trx,+ companyId,+ ctx.supplierMap.get(text(r.supplier).toLowerCase()),+ processId+ );+ }++ const inserted = await trx+ .insertInto("methodOperation")+ .values([+ {+ makeMethodId,+ order: num(opNo) ?? opIndex,+ operationOrder: text(r.operationOrder) || "After Previous",+ operationType: opType,+ processId,+ workCenterId,+ description: text(r.operationDescription),+ setupUnit: text(r.setupUnit) || undefined,+ setupTime: num(r.setupTime) ?? 0,+ laborUnit: text(r.laborUnit) || undefined,+ laborTime: num(r.laborTime) ?? 0,+ machineUnit: text(r.machineUnit) || undefined,+ machineTime: num(r.machineTime) ?? 0,+ operationSupplierProcessId,+ operationMinimumCost: num(r.operationMinimumCost),+ operationUnitCost: num(r.operationUnitCost),+ operationLeadTime: num(r.operationLeadTime),+ workInstruction: {},+ companyId,+ createdBy: userId,+ createdAt: now()+ } as never+ ])+ .returning(["id"])+ .execute();+ opIdByNo.set(opNo, inserted[0]!.id);+ opIndex++;+ filledAny = true;+ }++ // --- steps / tools / parameters per operation ---+ const sortByOp = new Map<string, number>();+ for (const e of bucket.step) {+ const r = e.record;+ const operationId = opIdByNo.get(text(r.opNo))!;+ const sortOrder = (sortByOp.get(operationId) ?? 0) + 1;+ sortByOp.set(operationId, sortOrder);+ const stepType = text(r.stepType) || "Task";+ await trx+ .insertInto("methodOperationStep")+ .values([+ {+ operationId,+ name: text(r.stepName),+ description: plainTextToTiptap(text(r.stepDescription)),+ type: stepType,+ required: bool(r.stepRequired),+ sortOrder,+ unitOfMeasureCode:+ stepType === "Measurement"+ ? text(r.stepUnitOfMeasureCode) || undefined+ : undefined,+ minValue: num(r.stepMinValue),+ maxValue: num(r.stepMaxValue),+ listValues:+ stepType === "List" && text(r.stepListValues)+ ? text(r.stepListValues)+ .split("|")+ .map((v) => v.trim())+ .filter(Boolean)+ : undefined,+ companyId,+ createdBy: userId,+ createdAt: now()+ } as never+ ])+ .execute();+ }++ for (const e of bucket.tool) {+ const r = e.record;+ const operationId = opIdByNo.get(text(r.opNo))!;+ const tool = await resolveItem(+ trx,+ companyId,+ text(r.toolId),+ text(r.toolRevision),+ ctx.itemMap+ );+ await trx+ .insertInto("methodOperationTool")+ .values([+ {+ operationId,+ toolId: tool.id,+ quantity: num(r.toolQuantity) ?? 1,+ companyId,+ createdBy: userId,+ createdAt: now()+ } as never+ ])+ .execute();+ }++ for (const e of bucket.param) {+ const r = e.record;+ const operationId = opIdByNo.get(text(r.opNo))!;+ await trx+ .insertInto("methodOperationParameter")+ .values([+ {+ operationId,+ key: text(r.paramKey),+ value: text(r.paramValue),+ companyId,+ createdBy: userId,+ createdAt: now()+ } as never+ ])+ .execute();+ }+ }++ return { filledAny, skippedExisting };+ });+ }++ // ---------------------------------------------------------------------------+ // transaction-scoped resolution helpers+ // ---------------------------------------------------------------------------++ // Resolve an item id by readableId + revision. Falls back to a DB lookup for a+ // part created earlier in this same file (not present in the prefetched map).+ async function resolveItem(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ readableId: string,+ revision: string,+ itemMap: Map<string, ItemInfo>+ ): Promise<ItemInfo> {+ const k = key(readableId, revision);+ const cached = itemMap.get(k);+ if (cached) return cached;++ const row = await trx+ .selectFrom("item")+ .select(["id", "type", "defaultMethodType", "sourcingType"])+ .where("companyId", "=", companyId)+ .where("readableId", "=", readableId)+ .where("revision", "=", revision || "0")+ .limit(1)+ .executeTakeFirst();+ if (!row) {+ throw new Error(`Item ${readableId} rev ${revision || "0"} not found`);+ }+ const info: ItemInfo = {+ id: row.id,+ type: row.type,+ defaultMethodType: row.defaultMethodType ?? null,+ sourcingType: row.sourcingType ?? null+ };+ itemMap.set(k, info);+ return info;+ }++ // The part's current (active, else highest non-archived) make method id —+ // mirrors the activeMakeMethods view ranking.+ async function currentMakeMethodId(+ trx: Transaction<KyselyDatabase>,+ itemId: string,+ companyId: string+ ): Promise<string | null> {+ const rows = await trx+ .selectFrom("makeMethod")+ .select(["id", "version", "status"])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .where("status", "!=", "Archived")+ .execute();+ if (rows.length === 0) return null;+ rows.sort((a, b) => {+ const aActive = a.status === "Active" ? 0 : 1;+ const bActive = b.status === "Active" ? 0 : 1;+ if (aActive !== bActive) return aActive - bActive;+ return Number(b.version) - Number(a.version);+ });+ return rows[0]!.id;+ }++ // Resolve the target make method for a version. Blank → the part's current+ // method (the trigger-created Draft v1 for a new part). Explicit → find-or-create+ // that version as a Draft; never auto-activate.+ async function ensureMakeMethod(+ trx: Transaction<KyselyDatabase>,+ itemId: string,+ version: string,+ companyId: string,+ userId: string+ ): Promise<string> {+ if (!version.trim()) {+ const current = await currentMakeMethodId(trx, itemId, companyId);+ if (current) return current;+ // No make method yet (e.g. a non-trigger item type) — create Draft v1.+ const inserted = await trx+ .insertInto("makeMethod")+ .values([+ {+ itemId,+ companyId,+ version: 1,+ status: "Draft",+ createdBy: userId,+ createdAt: datetime.timestamp()+ } as never+ ])+ .returning(["id"])+ .execute();+ return inserted[0]!.id;+ }++ const versionNumber = num(version) ?? 1;+ const existing = await trx+ .selectFrom("makeMethod")+ .select(["id"])+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .where("version", "=", versionNumber)+ .limit(1)+ .executeTakeFirst();+ if (existing) return existing.id;++ const inserted = await trx+ .insertInto("makeMethod")+ .values([+ {+ itemId,+ companyId,+ version: versionNumber,+ status: "Draft",+ createdBy: userId,+ createdAt: datetime.timestamp()+ } as never+ ])+ .returning(["id"])+ .execute();+ return inserted[0]!.id;+ }++ // Seed storageUnitIds from the component's pickMethod default bins (mirrors+ // resolveMethodMaterialStorageUnitIds in items.service.ts).+ async function seedStorageUnitIds(+ trx: Transaction<KyselyDatabase>,+ itemId: string+ ): Promise<Record<string, string>> {+ const current: Record<string, string> = {};+ const rows = await trx+ .selectFrom("pickMethod")+ .select(["locationId", "defaultStorageUnitId"])+ .where("itemId", "=", itemId)+ .execute();+ for (const row of rows) {+ if (+ row.locationId &&+ row.defaultStorageUnitId &&+ !current[row.locationId]+ ) {+ current[row.locationId] = row.defaultStorageUnitId;+ }+ }+ return current;+ }++ // Optional supplier-process link for an Outside Processing operation (by supplier + process).+ async function resolveSupplierProcess(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ supplierId: string | undefined,+ processId: string+ ): Promise<string | undefined> {+ if (!supplierId) return undefined;+ const row = await trx+ .selectFrom("supplierProcess")+ .select(["id"])+ .where("companyId", "=", companyId)+ .where("supplierId", "=", supplierId)+ .where("processId", "=", processId)+ .limit(1)+ .executeTakeFirst();+ return row?.id;+ }+ export async function importStockQuantities(+ db: Kysely<KyselyDatabase>,+ client: SupabaseClient<Database>,+ args: {+ table: StockImportTable;+ mappedRecords: Rec[];+ companyId: string;+ userId: string;+ summary: Summary;+ }+ ): Promise<void> {+ const { table, mappedRecords, companyId, userId, summary } = args;+ const isTracked = table !== "inventoryQuantity";++ // 1. preload lookups ------------------------------------------------------+ const readableIds = [+ ...new Set(mappedRecords.map((r) => text(r.readableId)).filter(Boolean))+ ];+ const items =+ readableIds.length > 0+ ? await db+ .selectFrom("item")+ .select([+ "id",+ "readableId",+ "revision",+ "readableIdWithRevision",+ "itemTrackingType",+ "replenishmentSystem",+ "type"+ ])+ .where("companyId", "=", companyId)+ .where("readableId", "in", readableIds)+ .orderBy("type")+ .orderBy("id")+ .execute()+ : [];++ const itemIds = items.map((i) => i.id);+ const [itemCosts, shelfLives] =+ itemIds.length > 0+ ? await Promise.all([+ db+ .selectFrom("itemCost")+ .select([+ "itemId",+ "costingMethod",+ "unitCost",+ "standardCost",+ "itemPostingGroupId"+ ])+ .where("companyId", "=", companyId)+ .where("itemId", "in", itemIds)+ .execute(),+ isTracked+ ? db+ .selectFrom("itemShelfLife")+ .select(["itemId", "mode", "days"])+ .where("companyId", "=", companyId)+ .where("itemId", "in", itemIds)+ .execute()+ : Promise.resolve([])+ ])+ : [[], []];+ const itemCostByItem = new Map(itemCosts.map((c) => [c.itemId, c]));+ const shelfLifeByItem = new Map(shelfLives.map((s) => [s.itemId, s]));++ // readableId + revision → item; ties broken in `buildStockItemMap`. The+ // query order (type, id) makes the fallback pick deterministic.+ const itemMap = buildStockItemMap(+ table,+ items.map((i) => ({+ id: i.id,+ readableId: i.readableId,+ revision: i.revision,+ itemTrackingType: i.itemTrackingType,+ hasItemCost: itemCostByItem.has(i.id)+ }))+ );+ const itemById = new Map(items.map((i) => [i.id, i]));++ const locations = await db+ .selectFrom("location")+ .select(["id"])+ .where("companyId", "=", companyId)+ .execute();+ const locationIds = new Set(locations.map((l) => l.id));++ const referencedLocationIds = [+ ...new Set(+ mappedRecords+ .map((r) => text(r.locationId))+ .filter((l) => l !== "" && locationIds.has(l))+ )+ ];+ const storageUnits =+ referencedLocationIds.length > 0+ ? await db+ .selectFrom("storageUnit")+ .select(["id", "name", "locationId"])+ .where("companyId", "=", companyId)+ .where("locationId", "in", referencedLocationIds)+ // Only active units, as the single-record adjustment offers+ // (getStorageUnitsListForLocation); an inactive name falls through+ // to the "not found in this location" row error.+ .where("active", "=", true)+ .execute()+ : [];+ const storageUnitMap = new Map<string, string>();+ for (const u of storageUnits) {+ storageUnitMap.set(storageUnitKey(u.locationId, u.name), u.id);+ }++ // Existing batch / serial numbers on the referenced items, any status.+ const existingTrackedKeys = new Set<string>();+ if (isTracked && itemIds.length > 0) {+ const numberField =+ table === "serialQuantity" ? "serialNumber" : "batchNumber";+ const numbers = [+ ...new Set(mappedRecords.map((r) => text(r[numberField])).filter(Boolean))+ ];+ if (numbers.length > 0) {+ const existing = await db+ .selectFrom("trackedEntity")+ .select(["itemId", "readableId"])+ .where("companyId", "=", companyId)+ .where("itemId", "in", itemIds)+ .where("readableId", "in", numbers)+ .execute();+ for (const e of existing) {+ if (e.itemId && e.readableId) {+ existingTrackedKeys.add(trackedKey(e.itemId, e.readableId));+ }+ }+ }+ }++ // 2. classify -------------------------------------------------------------+ const seenTrackedKeys = new Set<string>();+ const planned: StockRowResolved[] = [];+ for (const [rowIndex, record] of mappedRecords.entries()) {+ const decision = classifyStockRow({+ table,+ record,+ itemMap,+ locationIds,+ storageUnitMap,+ existingTrackedKeys,+ seenTrackedKeys+ });+ if (decision.action === "skip") {+ (decision.category === "error" ? summary.errors : summary.skipped).push({+ row: rowIndex,+ reason: decision.reason+ });+ continue;+ }+ // Claim the dedup slot only once the row is valid, so a rejected row never+ // blocks a later legitimate row with the same number.+ if (decision.row.trackedKey) seenTrackedKeys.add(decision.row.trackedKey);+ planned.push(decision.row);+ }++ importCsvTableLogger.info({+ function: "import-stock-quantities",+ table,+ trackingType: STOCK_IMPORT_TRACKING_TYPE[table],+ totalRecords: mappedRecords.length,+ planned: planned.length,+ skipped: summary.skipped.length,+ errors: summary.errors.length+ });++ if (planned.length === 0) return;++ // 3. accounting context — resolved BEFORE the transaction, as+ // post-inventory-adjustment / post-inventory-count do (REST hops+ // mid-transaction park the size-1 pool in idle-in-transaction).+ const today = datetime+ .today(await resolveCompanyTimeZone(db, companyId))+ .toString();+ const nowIso = datetime.timestamp();++ // The journal is Provisional before the company's accounting cutover and+ // Posted after it. Read here to decide whether to resolve a period, and+ // again inside the transaction. A Provisional journal has no period.+ const postingStatus = await journalPostingStatus(db, companyId);+ const accountDefaults = await getDefaultPostingGroup(db, companyId);+ if (accountDefaults.error || !accountDefaults.data) {+ throw new Error("Error getting account defaults");+ }+ const accountingPeriodId =+ postingStatus === "Posted"+ ? await getCurrentAccountingPeriod(companyId, db, today)+ : null;++ // Active dimensions for the company group — journal lines get Item /+ // ItemPostingGroup / Location tags.+ const dimensionMap: Record<string, string> = {};+ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["companyGroupId"] }+ );+ if (companyRecord.error) throw new Error("Failed to fetch company");+ const dimensions = await many(+ db,+ "dimension",+ {+ companyGroupId: companyRecord.data.companyGroupId!,+ active: true,+ entityType: ["Item", "ItemPostingGroup", "Location"]+ },+ { columns: ["id", "entityType"] }+ );+ // Fail closed: journal lines must not silently lose dimension tags.+ if (dimensions.error) throw new Error("Failed to fetch dimensions");+ for (const dim of dimensions.data ?? []) {+ if (dim.entityType) dimensionMap[dim.entityType] = dim.id;+ }++ const accounting = {+ accountingPeriodId,+ accountDefaults: {+ rawMaterialsAccount: accountDefaults.data.rawMaterialsAccount,+ finishedGoodsAccount: accountDefaults.data.finishedGoodsAccount,+ inventoryAdjustmentVarianceAccount:+ accountDefaults.data.inventoryAdjustmentVarianceAccount+ },+ description: "Inventory Adjustment — CSV import",+ userId,+ dimensions: dimensionMap+ };++ // Fixed Duration shelf-life fallback for a new tracked entity with no typed+ // expiry — same rule as post-inventory-adjustment's+ // resolveExpirationForNewEntity. Other modes stay NULL.+ const resolveExpiration = (row: StockRowResolved): string | null => {+ if (row.expirationDate) return row.expirationDate;+ const shelfLife = shelfLifeByItem.get(row.itemId);+ if (shelfLife?.mode === "Fixed Duration" && shelfLife.days) {+ return parseDate(today)+ .add({ days: Number(shelfLife.days) })+ .toString();+ }+ return null;+ };++ // 4. write — whole file in one transaction --------------------------------+ // Everything is planned in memory first, then written table by table in bulk.+ // The rows are byte-for-byte what `bookAdjustment` writes per movement+ // because every one of them — item ledger, cost layer, journal line,+ // journal line dimension — comes out of the builders in+ // `../lib/plan-adjustment.ts` that `bookAdjustment` itself calls, and the+ // cost layers are valued by replaying the per-row read (see+ // `planIncreaseUnitCosts`). Nothing here re-derives a field.+ await db.transaction().execute(async (trx) => {+ await assertPostingStatusUnchanged(trx, companyId, postingStatus);++ // A tracked entity's id is ours to choose, so the ledger rows can name it+ // before anything is inserted.+ const trackedEntityIds = planned.map(() => (isTracked ? nanoid() : null));++ // Value every row up front. `planStockRows` (pure, tested) does the whole+ // per-file plan: which rows carry value at all (bookAdjustment's early+ // return — classifyStockRow already rejects both cases, so it guards a+ // future column rather than a live branch), each row's layer cost from the+ // per-item replay, and which rows post to the GL.+ const planInputs = planned.map((row) => ({+ itemId: row.itemId,+ quantity: row.quantity,+ itemTrackingType: itemById.get(row.itemId)!.itemTrackingType+ }));+ const openLayersByItem = await loadOpenCostLayers(trx, {+ itemIds: [+ ...new Set(+ planInputs+ .filter((row) =>+ carriesAdjustmentValue(row.quantity, row.itemTrackingType)+ )+ .map((row) => row.itemId)+ )+ ],+ companyId+ });+ const rowPlans = planStockRows({+ rows: planInputs,+ itemCosts: itemCostByItem,+ openLayersByItem+ });++ // Tracked entities first: the ledger rows reference them.+ if (isTracked) {+ const trackedEntityRows = planned.map((row, rowIndex) => {+ const item = itemById.get(row.itemId)!;+ const expirationDate = resolveExpiration(row);+ // Stamp the trace blob so the popover Source / Override steps show+ // where the entity originated (post-inventory-adjustment shape).+ const adjustmentStamp = {+ userId,+ at: nowIso,+ reason: "Created via CSV import"+ };+ const attributes: Record<string, unknown> = {+ "Inventory Adjustment": adjustmentStamp,+ ...(expirationDate+ ? {+ expiryOverrides: [+ {+ previous: null,+ next: expirationDate,+ reason: adjustmentStamp.reason,+ source: "Inventory Adjustment",+ userId: adjustmentStamp.userId,+ at: adjustmentStamp.at+ }+ ]+ }+ : {})+ };+ return {+ id: trackedEntityIds[rowIndex]!,+ sourceDocument: "Item",+ sourceDocumentId: row.itemId,+ sourceDocumentReadableId: item.readableIdWithRevision ?? undefined,+ itemId: row.itemId,+ readableId: row.readableId,+ quantity: row.quantity,+ status: "Available" as const,+ expirationDate,+ attributes: attributes as unknown as Json,+ companyId,+ createdBy: userId+ };+ });+ for (const rows of chunked(trackedEntityRows)) {+ await trx.insertInto("trackedEntity").values(rows).execute();+ }+ }++ // Item ledger. The generated id is each movement's documentId on its cost+ // ledger and journal lines, so the ids have to come back mapped to their+ // source row. `entryNumber` is a SERIAL assigned as the VALUES rows are+ // formed, so sorting each chunk by it recovers the source order without+ // depending on RETURNING's output order.+ const itemLedgerIds: string[] = [];+ for (const rows of chunked(+ planned.map((row, rowIndex) =>+ buildItemLedgerRow({+ postingDate: today,+ entryType: "Positive Adjmt.",+ documentType: null,+ documentId: null,+ correctionOfItemLedgerId: null,+ itemId: row.itemId,+ locationId: row.locationId,+ storageUnitId: row.storageUnitId,+ trackedEntityId: trackedEntityIds[rowIndex] ?? null,+ quantity: row.quantity,+ comment: row.comment,+ scrapReasonId: null,+ companyId,+ createdBy: userId+ })+ )+ )) {+ const inserted = await trx+ .insertInto("itemLedger")+ .values(rows)+ .returning(["id", "entryNumber"])+ .execute();+ inserted.sort((a, b) => Number(a.entryNumber) - Number(b.entryNumber));+ for (const row of inserted) itemLedgerIds.push(row.id);+ }+ if (itemLedgerIds.length !== planned.length) {+ throw new Error("Item ledger insert did not return a row per movement");+ }++ // Cost layers.+ const costLedgerRows = planned.flatMap((row, rowIndex) =>+ rowPlans[rowIndex]!.carriesValue+ ? [+ buildCostLedgerRow({+ entryType: "Positive Adjmt.",+ documentType: null,+ documentId: itemLedgerIds[rowIndex]!,+ itemId: row.itemId,+ quantity: row.quantity,+ cost: rowPlans[rowIndex]!.cost,+ postingDate: today,+ companyId+ })+ ]+ : []+ );+ for (const rows of chunked(costLedgerRows)) {+ await trx.insertInto("costLedger").values(rows).execute();+ }++ // Journal. A zero-value movement posts no lines, so an all-zero-cost file+ // creates no journal at all — the lazy `getJournalId` behaviour, decided+ // once here instead of per row.+ const postingRowIndexes = planned+ .map((_, rowIndex) => rowIndex)+ .filter((rowIndex) => rowPlans[rowIndex]!.postsJournal);+ if (postingRowIndexes.length > 0) {+ const journalId = await createAdjustmentJournal(trx, {+ companyId,+ accountingPeriodId: accounting.accountingPeriodId,+ status: postingStatus,+ description: accounting.description,+ postingDate: today,+ userId+ });++ // `journalLineReference` already identifies a movement's line pair (it+ // is what ties the two sides together on the per-row path), so it is+ // also how the inserted ids find their way back to their movement — no+ // positional assumption about RETURNING.+ const referenceByRowIndex = new Map<number, string>(+ postingRowIndexes.map((rowIndex) => [rowIndex, nanoid()])+ );+ const journalLineRows = postingRowIndexes.flatMap((rowIndex) => {+ const row = planned[rowIndex];+ const item = itemById.get(row!.itemId)!;+ return buildAdjustmentJournalLines({+ journalId,+ documentId: itemLedgerIds[rowIndex]!,+ documentType: null,+ journalLineReference: referenceByRowIndex.get(rowIndex)!,+ isGain: true,+ cost: rowPlans[rowIndex]!.cost,+ quantity: row!.quantity,+ replenishmentSystem: item.replenishmentSystem,+ accountDefaults: accounting.accountDefaults,+ companyId+ });+ });+ const journalLineIdsByReference = new Map<string, string[]>();+ for (const rows of chunked(journalLineRows)) {+ const inserted = await trx+ .insertInto("journalLine")+ .values(rows)+ .returning(["id", "journalLineReference"])+ .execute();+ for (const line of inserted) {+ const reference = line.journalLineReference;+ const ids = journalLineIdsByReference.get(reference) ?? [];+ ids.push(line.id);+ journalLineIdsByReference.set(reference, ids);+ }+ }++ const dimensionRows = postingRowIndexes.flatMap((rowIndex) => {+ const row = planned[rowIndex];+ const reference = referenceByRowIndex.get(rowIndex)!;+ const journalLineIds = journalLineIdsByReference.get(reference) ?? [];+ if (journalLineIds.length !== 2) {+ throw new Error(+ "Journal line insert did not return a pair per movement"+ );+ }+ return buildJournalLineDimensions({+ journalLineIds,+ dimensions: accounting.dimensions,+ itemId: row!.itemId,+ itemPostingGroupId: itemCostByItem.get(row!.itemId)!+ .itemPostingGroupId,+ locationId: row!.locationId,+ companyId+ });+ });+ for (const rows of chunked(dimensionRows)) {+ await trx.insertInto("journalLineDimension").values(rows).execute();+ }+ }++ summary.inserted += planned.length;+ });+ }+ export const importCsvInput = z.object({+ table: z.enum([+ "consumable",+ "customer",+ "customerContact",+ "fixture",+ "material",+ "bom",+ "operations",+ "partWithMethod",+ "part",+ "service",+ "supplier",+ "supplierContact",+ "tool",+ "workCenter",+ "process",+ "storageUnit",+ "unitOfMeasure",+ "itemPostingGroup",+ "storageType",+ "scrapReason",+ "department",+ "materialSubstance",+ "materialForm",+ "materialFinish",+ "materialGrade",+ "materialType",+ "materialDimension",+ "inventoryQuantity",+ "batchQuantity",+ "serialQuantity"+ ]),+ filePath: z.string(),+ columnMappings: z.record(z.string(), z.string()),+ enumMappings: z+ .record(z.string(), z.record(z.string(), z.string()))+ .optional()+ });++ const EXTERNAL_ID_KEY = "csv";++ type ImportTable = z.infer<typeof importCsvInput>["table"];++ // The columns each importer may write from a CSV row. Kysely here runs as the+ // service role, so spreading a row into an INSERT/UPDATE would let a crafted+ // mapping write `id`, `createdBy`, `intercompanyCompanyId`, or any other+ // column. These mirror `fieldMappings` / `importSchemas` in the ERP's+ // `imports.models.ts`; columns the importer derives itself (rates, flags,+ // side-table fields) are handled explicitly at the call site.+ type CsvTables = Database["public"]["Tables"];++ type InsertColumns<T extends keyof CsvTables> =+ readonly (keyof CsvTables[T]["Insert"] & string)[];++ const CUSTOMER_COLUMNS = [+ "name",+ "accountManagerId",+ "customerStatusId",+ "customerTypeId",+ "phone",+ "fax",+ "currencyCode",+ "website"+ ] as const satisfies InsertColumns<"customer">;++ const SUPPLIER_COLUMNS = [+ "name",+ "accountManagerId",+ "supplierStatus",+ "supplierTypeId",+ "phone",+ "fax",+ "currencyCode",+ "website"+ ] as const satisfies InsertColumns<"supplier">;++ const CONTACT_COLUMNS = [+ "firstName",+ "lastName",+ "email",+ "title",+ "mobilePhone",+ "workPhone",+ "homePhone",+ "fax",+ "notes"+ ] as const satisfies InsertColumns<"contact">;++ const WORK_CENTER_COLUMNS = [+ "name",+ "description",+ "defaultStandardFactor",+ "locationId"+ ] as const satisfies InsertColumns<"workCenter">;++ const PROCESS_COLUMNS = [+ "name",+ "defaultStandardFactor"+ ] as const satisfies InsertColumns<"process">;++ /**+ * The allow-listed columns of a CSV row, typed as `table`'s own columns. CSV+ * cells are strings; the enum and numeric columns among them are checked by+ * Postgres on write, as they were before the allow-list.+ */+ function pickColumns<+ T extends keyof CsvTables,+ K extends keyof CsvTables[T]["Insert"] & string+ >(+ _table: T,+ record: Partial<Record<string, string>>,+ columns: readonly K[]+ ): Partial<Pick<CsvTables[T]["Insert"], K>> {+ const out: Partial<Record<K, string>> = {};+ for (const column of columns) {+ if (column in record) out[column] = record[column];+ }+ return out as unknown as Partial<Pick<CsvTables[T]["Insert"], K>>;+ }++ // Tables a CSV row may reference by id. The material taxonomy has global+ // system rows (companyId IS NULL) that every company may use.+ type ReferencedTable =+ | "employee"+ | "customerStatus"+ | "customerType"+ | "supplierType"+ | "paymentTerm"+ | "shippingMethod"+ | "supplier"+ | "location"+ | "materialSubstance"+ | "materialForm"+ | "materialFinish"+ | "materialGrade"+ | "materialDimension";++ const GLOBAL_REFERENCED_TABLES = new Set<ReferencedTable>([+ "materialSubstance",+ "materialForm",+ "materialFinish",+ "materialGrade",+ "materialDimension"+ ]);++ type ReferenceSpec = { column: string; table: ReferencedTable; label: string };++ const itemReferences: ReferenceSpec[] = [+ { column: "supplierId", table: "supplier", label: "Supplier" }+ ];++ // Id-valued columns per import. The wizard resolves these through+ // company-scoped fetchers, but the ids arrive in the request body, so each is+ // re-checked against the caller's company before anything is written.+ const REFERENCES: Partial<Record<ImportTable, ReferenceSpec[]>> = {+ customer: [+ { column: "accountManagerId", table: "employee", label: "Account Manager" },+ { column: "customerStatusId", table: "customerStatus", label: "Status" },+ { column: "customerTypeId", table: "customerType", label: "Type" },+ { column: "paymentTermId", table: "paymentTerm", label: "Payment Term" }+ ],+ supplier: [+ { column: "accountManagerId", table: "employee", label: "Account Manager" },+ { column: "supplierTypeId", table: "supplierType", label: "Type" },+ { column: "paymentTermId", table: "paymentTerm", label: "Payment Term" },+ {+ column: "shippingMethodId",+ table: "shippingMethod",+ label: "Shipping Method"+ }+ ],+ part: itemReferences,+ tool: itemReferences,+ fixture: itemReferences,+ consumable: itemReferences,+ service: itemReferences,+ material: [+ ...itemReferences,+ {+ column: "materialSubstanceId",+ table: "materialSubstance",+ label: "Substance"+ },+ { column: "materialFormId", table: "materialForm", label: "Form" },+ { column: "finishId", table: "materialFinish", label: "Finish" },+ { column: "gradeId", table: "materialGrade", label: "Grade" },+ { column: "dimensionId", table: "materialDimension", label: "Dimensions" }+ ],+ workCenter: [{ column: "locationId", table: "location", label: "Location" }],+ storageUnit: [{ column: "locationId", table: "location", label: "Location" }]+ };++ type CsvRecord = Record<string, string>;++ /**+ * Report every row that references a record outside the caller's company, and+ * return the other rows as `[rowIndex, record]` pairs (the index is the CSV row+ * the summary reports). One query per referenced column, run together.+ */+ async function rejectForeignReferences(+ db: Kysely<KyselyDatabase>,+ table: ImportTable,+ records: CsvRecord[],+ cId: string,+ errors: Array<{ row: number; reason: string }>+ ): Promise<Array<[number, CsvRecord]>> {+ const ownedBySpec = await Promise.all(+ (REFERENCES[table] ?? []).map(async (spec) => {+ const ids = [+ ...new Set(+ records.map((r) => r[spec.column]).filter((v): v is string => !!v)+ )+ ];+ if (ids.length === 0) return { spec, owned: new Set<string>() };+ const scope = GLOBAL_REFERENCED_TABLES.has(spec.table)+ ? sql<boolean>`("companyId" = ${cId} OR "companyId" IS NULL)`+ : sql<boolean>`"companyId" = ${cId}`;+ // Every referenced table has an `id` and a `companyId`; the cast only+ // narrows the union for Kysely's types.+ const rows = await db+ .selectFrom(spec.table as "location")+ .select(["id"])+ .where("id", "in", ids)+ .where(scope)+ .execute();+ return { spec, owned: new Set(rows.map((r) => r.id)) };+ })+ );++ const accepted: Array<[number, CsvRecord]> = [];+ for (const [rowIndex, record] of records.entries()) {+ const foreign = ownedBySpec.find(+ ({ spec, owned }) =>+ !!record[spec.column] && !owned.has(record[spec.column]!)+ );+ if (foreign) {+ errors.push({+ row: rowIndex,+ reason: `${foreign.spec.label} "${record[foreign.spec.column]}" was not found in this company`+ });+ } else {+ accepted.push([rowIndex, record]);+ }+ }+ return accepted;+ }++ /**+ * Fallback CSV parser used when std/csv rejects a row-length mismatch.+ * Handles RFC-4180 quoting but tolerates uneven row widths (extra cells+ * dropped, missing cells become "").+ */+ function parsePermissiveCsv(text: string): Record<string, string>[] {+ const rows: string[][] = [];+ let row: string[] = [];+ let field = "";+ let inQuotes = false;+ for (let i = 0; i < text.length; i++) {+ const c = text[i];+ if (inQuotes) {+ if (c === '"') {+ if (text[i + 1] === '"') {+ field += '"';+ i++;+ } else {+ inQuotes = false;+ }+ } else {+ field += c;+ }+ } else if (c === '"') {+ inQuotes = true;+ } else if (c === ",") {+ row.push(field);+ field = "";+ } else if (c === "\n" || c === "\r") {+ // \r\n: consume the \n that follows+ if (c === "\r" && text[i + 1] === "\n") i++;+ row.push(field);+ field = "";+ // Skip blank rows that arise from trailing newlines+ if (row.length > 1 || (row.length === 1 && row[0] !== "")) {+ rows.push(row);+ }+ row = [];+ } else {+ field += c;+ }+ }+ if (field !== "" || row.length > 0) {+ row.push(field);+ if (row.length > 1 || (row.length === 1 && row[0] !== "")) {+ rows.push(row);+ }+ }++ if (rows.length === 0) return [];+ const headers = rows[0];+ return rows.slice(1).map((r) => {+ const obj: Record<string, string> = {};+ for (let i = 0; i < headers!.length; i++) {+ obj[headers![i]!] = r[i] ?? "";+ }+ return obj;+ });+ }++ type CsvEntityType =+ | "customer"+ | "supplier"+ | "item"+ | "contact"+ | "workCenter"+ | "process"+ | "storageUnit";++ /**+ * Look up the ids that still exist in the entity table. Done as a typed+ * switch so each Kysely query is fully type-checked — avoids `as any` casts+ * that bypass the generated DB types.+ */+ async function fetchLiveEntityIds(+ db: Kysely<KyselyDatabase>,+ entityType: CsvEntityType,+ ids: string[]+ ): Promise<Set<string>> {+ if (ids.length === 0) return new Set();+ let rows: { id: string }[];+ switch (entityType) {+ case "customer":+ rows = await db+ .selectFrom("customer")+ .select(["id"])+ .where("id", "in", ids)+ .execute();+ break;+ case "supplier":+ rows = await db+ .selectFrom("supplier")+ .select(["id"])+ .where("id", "in", ids)+ .execute();+ break;+ case "item":+ rows = await db+ .selectFrom("item")+ .select(["id"])+ .where("id", "in", ids)+ .execute();+ break;+ case "contact":+ rows = await db+ .selectFrom("contact")+ .select(["id"])+ .where("id", "in", ids)+ .execute();+ break;+ case "workCenter":+ rows = await db+ .selectFrom("workCenter")+ .select(["id"])+ .where("id", "in", ids)+ .execute();+ break;+ case "process":+ rows = await db+ .selectFrom("process")+ .select(["id"])+ .where("id", "in", ids)+ .execute();+ break;+ case "storageUnit":+ rows = await db+ .selectFrom("storageUnit")+ .select(["id"])+ .where("id", "in", ids)+ .execute();+ break;+ }+ return new Set(rows.map((r) => r.id));+ }++ /**+ * Build a name → id map for an entity table, scoped to a company and to the+ * specific names the caller cares about. Used as a fallback dedup key when+ * the CSV's Unique ID has no externalIntegrationMapping row yet (e.g., the+ * entity was created in-app, then a CSV with the same name is imported).+ * Scoping the query to `namesToCheck` avoids a full-table scan on+ * supplier/customer for companies with large rosters.+ */+ async function getNameMap(+ db: Kysely<KyselyDatabase>,+ entityType: "supplier" | "customer",+ cId: string,+ namesToCheck: string[]+ ): Promise<Map<string, string>> {+ if (namesToCheck.length === 0) return new Map();+ const rows =+ entityType === "supplier"+ ? await db+ .selectFrom("supplier")+ .select(["id", "name"])+ .where("companyId", "=", cId)+ .where("name", "in", namesToCheck)+ .execute()+ : await db+ .selectFrom("customer")+ .select(["id", "name"])+ .where("companyId", "=", cId)+ .where("name", "in", namesToCheck)+ .execute();+ return new Map(rows.map((r) => [r.name, r.id]));+ }++ /**+ * Build a map of CSV external IDs → entity IDs from externalIntegrationMapping.+ * Filters orphan mappings (rows whose entityId points at a deleted entity)+ * so re-imports cleanly take the INSERT path instead of failing the+ * subsequent supplierTax/customerTax upsert with a 23503 FK error.+ */+ async function getCsvExternalIdMap(+ db: Kysely<KyselyDatabase>,+ entityType: CsvEntityType,+ cId: string+ ): Promise<Map<string, string>> {+ const result = await db+ .selectFrom("externalIntegrationMapping")+ .select(["externalId", "entityId"])+ .where("entityType", "=", entityType)+ .where("integration", "=", EXTERNAL_ID_KEY)+ .where("companyId", "=", cId)+ .execute();++ const candidates = result.filter(+ (r): r is typeof r & { externalId: string; entityId: string } =>+ r.externalId !== null && r.entityId !== null+ );++ if (candidates.length === 0) return new Map();++ const liveIds = await fetchLiveEntityIds(+ db,+ entityType,+ candidates.map((r) => r.entityId)+ );++ return new Map(+ candidates+ .filter((r) => liveIds.has(r.entityId))+ .map((r) => [r.externalId, r.entityId])+ );+ }++ /**+ * Convert empty-string values to undefined. Kysely drops undefined keys from+ * the INSERT, so the column gets its DB default (NULL). Empty CSV cells would+ * otherwise become literal "" and fail FK or enum constraints.+ */+ function nullifyEmptyStrings<T extends Record<string, unknown>>(+ obj: T+ ): Partial<T> {+ const out: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(obj)) {+ out[k] = v === "" ? undefined : v;+ }+ return out as Partial<T>;+ }++ /**+ * Upsert CSV external ID mappings into the externalIntegrationMapping table.+ * Uses ON CONFLICT to handle re-imports idempotently.+ */+ async function upsertCsvMappings(+ trx: Kysely<KyselyDatabase>,+ entityType: CsvEntityType,+ mappings: Array<{ entityId: string; externalId: string }>,+ cId: string,+ userId: string+ ): Promise<void> {+ // Skip blank external ids: they carry no match value, and multiple "" rows+ // would collide on the ON CONFLICT key and abort the entire batch insert.+ const valid = mappings.filter((m) => m.externalId);+ if (valid.length === 0) return;++ const now = datetime.timestamp();++ await inChunks(+ valid.map((m) => ({+ entityType,+ entityId: m.entityId,+ integration: EXTERNAL_ID_KEY,+ externalId: m.externalId,+ companyId: cId,+ allowDuplicateExternalId: false,+ createdBy: userId,+ createdAt: now,+ updatedAt: now+ })),+ (rows) =>+ trx+ .insertInto("externalIntegrationMapping")+ .values(rows)+ // On conflict (orphan mapping with same csv id but stale entityId),+ // repoint entityId to the freshly-inserted entity. The .where() matches+ // the partial unique index's predicate, required by Postgres for+ // arbitration on partial indexes (42P10 otherwise).+ .onConflict((oc) =>+ oc+ .columns(["integration", "externalId", "entityType", "companyId"])+ .where("allowDuplicateExternalId", "=", false)+ .doUpdateSet((eb) => ({+ entityId: eb.ref("excluded.entityId"),+ updatedAt: eb.ref("excluded.updatedAt")+ }))+ )+ .execute()+ );+ }++ /**+ * Key for a scoped material-taxonomy lookup: the parent scope id (substance+ * for finish/grade, form for dimensions) plus the case-insensitively+ * normalized name.+ */+ function materialTaxonomyKey(scopeId: string, name: string): string {+ return `${scopeId.trim()}:${name.trim().toLowerCase()}`;+ }++ /**+ * Resolve raw Finish / Grade / Dimensions CSV text to material-taxonomy ids.+ * The taxonomy tables are scoped — materialFinish/materialGrade by substance,+ * materialDimension by form — so names are matched within the row's scope+ * against both global (companyId IS NULL) and company rows; a company row wins+ * a name clash. Unmatched names create a company-scoped row, mirroring the+ * creatable comboboxes on the material form. Returns ids keyed by+ * materialTaxonomyKey.+ */+ async function resolveMaterialTaxonomyIds(+ trx: Kysely<KyselyDatabase>,+ taxonomyTable: "materialFinish" | "materialGrade" | "materialDimension",+ scopeColumn: "materialSubstanceId" | "materialFormId",+ pairs: Array<{ scopeId: string; name: string }>,+ cId: string+ ): Promise<Map<string, string>> {+ const needed = new Map<string, { scopeId: string; name: string }>();+ for (const pair of pairs) {+ const scopeId = pair.scopeId?.trim();+ const name = pair.name?.trim();+ if (!scopeId || !name) continue;+ const key = materialTaxonomyKey(scopeId, name);+ if (!needed.has(key)) {+ needed.set(key, { scopeId, name });+ }+ }++ const idByKey = new Map<string, string>();+ if (needed.size === 0) return idByKey;++ const scopeIds = [...new Set([...needed.values()].map((p) => p.scopeId))];++ const selectMatches = async () => {+ const rows = await trx+ .selectFrom(taxonomyTable)+ .select(["id", "name", "companyId", scopeColumn] as never)+ .where(trx.dynamic.ref<string>(scopeColumn), "in", scopeIds)+ .where(sql<boolean>`("companyId" = ${cId} OR "companyId" IS NULL)`)+ .$castTo<Record<string, string | null>>()+ .execute();+ return rows.map((row) => ({+ id: row.id as string,+ name: row.name as string,+ companyId: row.companyId ?? null,+ scopeId: row[scopeColumn] as string+ }));+ };++ const collect = (rows: Awaited<ReturnType<typeof selectMatches>>) => {+ for (const row of rows) {+ const key = materialTaxonomyKey(row.scopeId, row.name);+ // Company-scoped rows win over global (NULL companyId) rows.+ if (!idByKey.has(key) || row.companyId === cId) {+ idByKey.set(key, row.id);+ }+ }+ };++ collect(await selectMatches());++ const missing = [...needed.values()].filter(+ (pair) => !idByKey.has(materialTaxonomyKey(pair.scopeId, pair.name))+ );++ if (missing.length > 0) {+ await inChunks(+ missing.map((pair) => ({+ name: pair.name,+ companyId: cId,+ [scopeColumn]: pair.scopeId+ })),+ (rows) =>+ trx+ .insertInto(taxonomyTable)+ .values(rows as never)+ // A concurrent import may have created the same name first; the+ // re-select below picks up whichever row won. The unique constraint is+ // exact-match, so two concurrent imports inserting different CASINGS of+ // the same new name can both land, leaving a case-variant duplicate —+ // the same duplicate the app's creatable comboboxes permit. Closing+ // that window needs a case-insensitive unique index on+ // (scope, lower(name), companyId), which requires a migration plus a+ // dedupe of existing case-variant rows.+ .onConflict((oc) =>+ oc.columns([scopeColumn, "name", "companyId"] as never).doNothing()+ )+ .execute()+ );++ collect(await selectMatches());+ }++ return idByKey;+ }++ /**+ * Address/payment/shipping fields that can ride along on a supplier or+ * customer CSV row. Written to side-tables (address + supplierLocation /+ * supplierPayment / supplierShipping, mirror for customer) after the parent+ * upsert lands.+ */+ type PartnerExtensionData = {+ locationName?: string;+ addressLine1?: string;+ addressLine2?: string;+ city?: string;+ state?: string;+ postalCode?: string;+ countryCode?: string;+ paymentTermId?: string;+ shippingMethodId?: string;+ incoterm?: string;+ incotermLocation?: string;+ };++ function extractPartnerExtensions(+ record: Record<string, string>+ ): PartnerExtensionData {+ return {+ locationName: record.locationName,+ addressLine1: record.addressLine1,+ addressLine2: record.addressLine2,+ city: record.city,+ state: record.state,+ postalCode: record.postalCode,+ countryCode: record.countryCode,+ paymentTermId: record.paymentTermId,+ shippingMethodId: record.shippingMethodId,+ incoterm: record.incoterm,+ incotermLocation: record.incotermLocation+ };+ }++ function hasAnyAddressField(ext: PartnerExtensionData): boolean {+ // Require addressLine1 to recognize a row as having an address. It's the+ // most distinguishing line of a postal address and also doubles as the+ // location-name fallback when `Location Name` is blank — without it,+ // creating a supplierLocation/customerLocation would have no usable label.+ return !!ext.addressLine1;+ }++ function buildAddressFields(ext: PartnerExtensionData): {+ addressLine1: string | null;+ addressLine2: string | null;+ city: string | null;+ stateProvince: string | null;+ postalCode: string | null;+ countryCode: string | null;+ } {+ return {+ addressLine1: ext.addressLine1 || null,+ addressLine2: ext.addressLine2 || null,+ city: ext.city || null,+ // The CSV field is `state` (user-facing label "State / Region"); the+ // column was renamed to stateProvince in migration 20240928155702.+ stateProvince: ext.state || null,+ postalCode: ext.postalCode || null,+ // address.countryCode is TEXT storing ISO 3166-1 alpha-2 (e.g., "US"),+ // post-20240928155702_country-codes.+ countryCode: ext.countryCode || null+ };+ }++ /**+ * Bulk-load the addressId of each entity's primary (lowest-id) location.+ * Used by the supplier/customer extension UPDATE paths to avoid an N+1+ * SELECT per entity inside the per-row loop. New inserts pass undefined+ * since by construction they have no location yet.+ */+ async function preloadPrimaryLocationAddressIds(+ trx: Kysely<KyselyDatabase>,+ entityType: "supplier" | "customer",+ entityIds: string[]+ ): Promise<Map<string, string>> {+ if (entityIds.length === 0) return new Map();+ const rows =+ entityType === "supplier"+ ? await trx+ .selectFrom("supplierLocation")+ .select(["supplierId", "id", "addressId"])+ .where("supplierId", "in", entityIds)+ .orderBy("id")+ .execute()+ : await trx+ .selectFrom("customerLocation")+ .select(["customerId", "id", "addressId"])+ .where("customerId", "in", entityIds)+ .orderBy("id")+ .execute();+ const map = new Map<string, string>();+ for (const row of rows) {+ const key =+ entityType === "supplier"+ ? (row as { supplierId: string }).supplierId+ : (row as { customerId: string }).customerId;+ if (!map.has(key)) map.set(key, row.addressId);+ }+ return map;+ }++ async function writeSupplierExtensions(+ trx: Kysely<KyselyDatabase>,+ supplierId: string,+ ext: PartnerExtensionData,+ companyId: string,+ userId: string,+ // Pre-fetched addressId of the supplier's existing primary location, if+ // any. Caller bulk-loads these for the whole batch to avoid an N+1+ // SELECT per supplier. undefined means "no existing location → insert".+ existingAddressId: string | undefined+ ): Promise<void> {+ const now = datetime.timestamp();++ if (hasAnyAddressField(ext)) {+ const addressFields = buildAddressFields(ext);++ if (existingAddressId) {+ await trx+ .updateTable("address")+ .set(addressFields)+ .where("id", "=", existingAddressId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const inserted = await trx+ .insertInto("address")+ .values({ ...addressFields, companyId })+ .returning(["id"])+ .executeTakeFirst();+ if (inserted?.id) {+ await trx+ .insertInto("supplierLocation")+ .values({+ supplierId,+ companyId,+ addressId: inserted.id,+ // supplierLocation.name is NOT NULL. Prefer the user's+ // Location Name column; fall back to Address Line 1 so the row+ // always has a recognizable label.+ name: (ext.locationName || ext.addressLine1)!+ })+ .execute();+ }+ }+ }++ if (ext.paymentTermId) {+ // The sync_create_supplier_entries interceptor creates the supplierPayment+ // row on supplier INSERT; UPSERT here makes us resilient to edge cases+ // where that row is somehow missing.+ await trx+ .insertInto("supplierPayment")+ .values({+ supplierId,+ paymentTermId: ext.paymentTermId,+ companyId,+ updatedAt: now,+ updatedBy: userId+ })+ .onConflict((oc) =>+ oc.column("supplierId").doUpdateSet({+ paymentTermId: ext.paymentTermId,+ updatedAt: now,+ updatedBy: userId+ })+ )+ .execute();+ }++ if (ext.shippingMethodId || ext.incoterm || ext.incotermLocation) {+ // Build the conditional update separately from the always-set fields so+ // ON CONFLICT only touches columns the user provided in the CSV — blank+ // cells don't overwrite existing values on re-import. The incoterm cast+ // narrows `string` to the Postgres enum union; Postgres rejects invalid+ // values at insert time as a safety net.+ const partialUpdate = {+ ...(ext.shippingMethodId+ ? { shippingMethodId: ext.shippingMethodId }+ : {}),+ ...(ext.incoterm+ ? {+ incoterm: ext.incoterm as Database["public"]["Enums"]["incoterm"]+ }+ : {}),+ ...(ext.incotermLocation+ ? { incotermLocation: ext.incotermLocation }+ : {})+ };+ await trx+ .insertInto("supplierShipping")+ .values({+ supplierId,+ companyId,+ updatedAt: now,+ updatedBy: userId,+ ...partialUpdate+ })+ .onConflict((oc) =>+ oc.column("supplierId").doUpdateSet({+ updatedAt: now,+ updatedBy: userId,+ ...partialUpdate+ })+ )+ .execute();+ }+ }++ async function writeCustomerExtensions(+ trx: Kysely<KyselyDatabase>,+ customerId: string,+ ext: PartnerExtensionData,+ companyId: string,+ userId: string,+ existingAddressId: string | undefined+ ): Promise<void> {+ const now = datetime.timestamp();++ if (hasAnyAddressField(ext)) {+ const addressFields = buildAddressFields(ext);++ if (existingAddressId) {+ await trx+ .updateTable("address")+ .set(addressFields)+ .where("id", "=", existingAddressId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const inserted = await trx+ .insertInto("address")+ .values({ ...addressFields, companyId })+ .returning(["id"])+ .executeTakeFirst();+ if (inserted?.id) {+ await trx+ .insertInto("customerLocation")+ .values({+ customerId,+ companyId,+ addressId: inserted.id,+ // customerLocation.name is NOT NULL. Prefer the user's+ // Location Name column; fall back to Address Line 1.+ name: (ext.locationName || ext.addressLine1)!+ })+ .execute();+ }+ }+ }++ if (ext.paymentTermId) {+ await trx+ .insertInto("customerPayment")+ .values({+ customerId,+ paymentTermId: ext.paymentTermId,+ companyId,+ updatedAt: now,+ updatedBy: userId+ })+ .onConflict((oc) =>+ oc.column("customerId").doUpdateSet({+ paymentTermId: ext.paymentTermId,+ updatedAt: now,+ updatedBy: userId+ })+ )+ .execute();+ }+ }++ /**+ * Idempotent supplierPart writes for the part/material/tool/fixture/consumable+ * import flow. One CSV row optionally creates one supplierPart link; re-imports+ * UPDATE the existing row (matched by (itemId, supplierId) per company).+ */+ type SupplierPartImportLink = {+ itemId: string;+ supplierId: string;+ supplierPartId?: string;+ supplierUnitOfMeasureCode?: string;+ minimumOrderQuantity?: string;+ orderMultiple?: string;+ conversionFactor?: string;+ unitPrice?: string;+ };++ type ItemPurchasingLeadTime = {+ itemId: string;+ leadTime: string;+ };++ type ItemUnitCost = {+ itemId: string;+ unitCost: string;+ };++ type ItemPlanningOrderMultiple = {+ itemId: string;+ orderMultiple: string;+ };++ async function writeSupplierPartLinks(+ trx: Kysely<KyselyDatabase>,+ links: SupplierPartImportLink[],+ companyId: string,+ userId: string+ ): Promise<void> {+ if (links.length === 0) return;+ const itemIds = [...new Set(links.map((l) => l.itemId))];+ const supplierIds = [...new Set(links.map((l) => l.supplierId))];+ const existing = await trx+ .selectFrom("supplierPart")+ .select(["id", "itemId", "supplierId"])+ .where("itemId", "in", itemIds)+ .where("supplierId", "in", supplierIds)+ .where("companyId", "=", companyId)+ .execute();+ const existingByPair = new Map(+ existing.map((e) => [`${e.itemId}:${e.supplierId}`, e.id])+ );++ const now = datetime.timestamp();+ for (const link of links) {+ const key = `${link.itemId}:${link.supplierId}`;+ const existingId = existingByPair.get(key);+ const numericMOQ = link.minimumOrderQuantity+ ? Number.parseInt(link.minimumOrderQuantity, 10)+ : null;+ const numericOrderMultiple = link.orderMultiple+ ? Number.parseInt(link.orderMultiple, 10)+ : null;+ const numericConversion = link.conversionFactor+ ? Number.parseFloat(link.conversionFactor)+ : 1;+ // The price is in the supplier part's currency: an existing part keeps+ // its own, a new one is created in base (currencyCode NULL), which is+ // what an imported price has always meant.+ const numericPrice = link.unitPrice+ ? Number.parseFloat(link.unitPrice)+ : null;++ if (existingId) {+ await trx+ .updateTable("supplierPart")+ .set({+ supplierPartId: link.supplierPartId || null,+ supplierUnitOfMeasureCode: link.supplierUnitOfMeasureCode || null,+ minimumOrderQuantity: numericMOQ,+ orderMultiple: numericOrderMultiple,+ conversionFactor: numericConversion,+ supplierUnitPrice: numericPrice,+ updatedAt: now,+ updatedBy: userId+ })+ .where("id", "=", existingId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ await trx+ .insertInto("supplierPart")+ .values({+ itemId: link.itemId,+ supplierId: link.supplierId,+ supplierPartId: link.supplierPartId || null,+ supplierUnitOfMeasureCode: link.supplierUnitOfMeasureCode || null,+ minimumOrderQuantity: numericMOQ,+ orderMultiple: numericOrderMultiple,+ conversionFactor: numericConversion,+ supplierUnitPrice: numericPrice,+ companyId,+ createdBy: userId+ })+ .execute();+ }+ }+ }++ // Set the item-level purchasing lead time (the "Purchasing" tab field).+ // The itemReplenishment row is created by the create_item_related_records+ // AFTER INSERT trigger on item (default leadTime 7, per migration+ // 20250610000433_demand-planning.sql which renamed purchasingLeadTime →+ // leadTime), so within this transaction the row already exists for every+ // item we just upserted — we only need to UPDATE it.+ async function writeItemPurchasingLeadTimes(+ trx: Kysely<KyselyDatabase>,+ entries: ItemPurchasingLeadTime[],+ companyId: string,+ userId: string+ ): Promise<void> {+ if (entries.length === 0) return;+ const now = datetime.timestamp();+ for (const entry of entries) {+ const numericLeadTime = Number.parseInt(entry.leadTime, 10);+ if (Number.isNaN(numericLeadTime)) continue;+ await trx+ .updateTable("itemReplenishment")+ .set({+ leadTime: numericLeadTime,+ updatedAt: now,+ updatedBy: userId+ })+ .where("itemId", "=", entry.itemId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Set the item-level unit cost (the "Costing" tab field). The itemCost row is+ // created by the create_item_related_records AFTER INSERT trigger on item, so+ // within this transaction the row already exists for every item we upserted —+ // we only need to UPDATE it. Non-numeric/blank values are skipped.+ async function writeItemUnitCosts(+ trx: Kysely<KyselyDatabase>,+ entries: ItemUnitCost[],+ companyId: string,+ userId: string+ ): Promise<void> {+ if (entries.length === 0) return;+ const now = datetime.timestamp();+ for (const entry of entries) {+ const numericUnitCost = Number.parseFloat(entry.unitCost);+ if (Number.isNaN(numericUnitCost)) continue;+ await trx+ .updateTable("itemCost")+ .set({+ unitCost: numericUnitCost,+ updatedAt: now,+ updatedBy: userId+ })+ .where("itemId", "=", entry.itemId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Set the item-level planning order multiple. itemPlanning has one row per+ // (item, location) pair, all created by create_item_related_records at item+ // insert time (SELECT FROM location WHERE companyId = ...). A single UPDATE+ // scoped by itemId + companyId therefore covers every location row for that+ // item — matching the "order multiple is unique across every location"+ // expectation. Mirrors the same CSV value already written to+ // supplierPart.orderMultiple in writeSupplierPartLinks; both are intentionally+ // kept in sync at import time even though they're structurally distinct+ // fields (supplier case-pack vs MRP preferred multiple).+ async function writeItemPlanningOrderMultiples(+ trx: Kysely<KyselyDatabase>,+ entries: ItemPlanningOrderMultiple[],+ companyId: string,+ userId: string+ ): Promise<void> {+ if (entries.length === 0) return;+ const now = datetime.timestamp();+ for (const entry of entries) {+ const numericOrderMultiple = Number.parseInt(entry.orderMultiple, 10);+ if (Number.isNaN(numericOrderMultiple) || numericOrderMultiple < 1)+ continue;+ await trx+ .updateTable("itemPlanning")+ .set({+ orderMultiple: numericOrderMultiple,+ updatedAt: now,+ updatedBy: userId+ })+ .where("itemId", "=", entry.itemId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ async function upsertTaxIdentifiers(+ trx: Kysely<KyselyDatabase>,+ table: "customerTax" | "supplierTax",+ records: Array<{ entityId: string; taxId: string | null | undefined }>,+ cId: string,+ userId: string+ ): Promise<void> {+ if (records.length === 0) return;++ const now = datetime.timestamp();+ if (table === "customerTax") {+ await inChunks(+ records.map((r) => ({+ customerId: r.entityId,+ taxId: r.taxId ?? null,+ companyId: cId,+ updatedAt: now,+ updatedBy: userId+ })),+ (rows) =>+ trx+ .insertInto("customerTax")+ .values(rows)+ .onConflict((oc) =>+ oc.column("customerId").doUpdateSet({+ taxId: sql`excluded."taxId"`,+ updatedAt: now,+ updatedBy: userId+ })+ )+ .execute()+ );+ return;+ }+ await inChunks(+ records.map((r) => ({+ supplierId: r.entityId,+ taxId: r.taxId ?? null,+ companyId: cId,+ updatedAt: now,+ updatedBy: userId+ })),+ (rows) =>+ trx+ .insertInto("supplierTax")+ .values(rows)+ .onConflict((oc) =>+ oc.column("supplierId").doUpdateSet({+ taxId: sql`excluded."taxId"`,+ updatedAt: now,+ updatedBy: userId+ })+ )+ .execute()+ );+ }++ /**+ * Imports an uploaded CSV into `table`, per the caller's column and enum+ * mappings. Run under `importCsvFile`, whose gate holds the table's+ * permission (`importPermissions` in `imports.models.ts`).+ */+ export async function importCsvTable(+ ctx: ServiceContext,+ raw: z.input<typeof importCsvInput>+ ) {+ const {+ table,+ filePath,+ columnMappings,+ enumMappings = {}+ } = importCsvInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;++ importCsvTableLogger.info({+ table,+ filePath,+ columnMappings,+ enumMappings,+ companyId,+ userId+ });++ const client = ctx.asSystem.supabase;++ // The client is service-role, so the company bucket wrapper is what keeps+ // the caller-supplied path inside the company's own files.+ const csvFile = await storage(client).company(companyId).download(filePath);+ if (!csvFile.data) {+ throw new Error("Failed to download file");+ }+ const csvText = new TextDecoder().decode(+ new Uint8Array(await csvFile.data.arrayBuffer())+ );+ // A row whose field count disagrees with the header falls back to the+ // permissive parser for real-world CSVs with quoting/comma issues.+ const strict = parseCsv<Record<string, string>>(csvText);+ const parsedCsv: Record<string, string>[] = strict.errors.some(+ (e) => e.type === "FieldMismatch"+ )+ ? parsePermissiveCsv(csvText)+ : strict.rows;++ let mappedRecords = parsedCsv.map((row) => {+ const record: Record<string, string> = {};+ for (const [key, value] of Object.entries(columnMappings)) {+ if (key in enumMappings) {+ const enumMapping = enumMappings[key];+ const csvValue = row[value];+ if (csvValue! in enumMapping!) {+ record[key] = enumMapping![csvValue!]!;+ } else {+ record[key] = enumMapping!["Default"]!;+ }+ } else if (value && value !== "N/A") {+ record[key] = row[value] || "";+ }+ }+ return record;+ });++ const missingEnumKeys = Object.keys(enumMappings).filter(+ (key) => !(key in mappedRecords[0]!)+ );++ if (missingEnumKeys.length > 0) {+ mappedRecords = mappedRecords.map((record) => {+ const processedRecord = { ...record };++ missingEnumKeys.forEach((key) => {+ processedRecord[key] = enumMappings[key]!["Default"]!;+ });++ return processedRecord;+ });+ }++ const summary = {+ inserted: 0,+ updated: 0,+ // Rows the user should fix and re-import (validation / missing required data).+ errors: [] as Array<{ row: number; reason: string }>,+ // Rows intentionally not written (duplicates, already-existing) — informational.+ skipped: [] as Array<{ row: number; reason: string }>+ };++ const acceptedRows = await rejectForeignReferences(+ db,+ table,+ mappedRecords,+ companyId,+ summary.errors+ );++ switch (table) {+ case "customer": {+ const externalIdMap = await getCsvExternalIdMap(+ db,+ "customer",+ companyId+ );+ const csvNames = Array.from(+ new Set(+ mappedRecords+ .map((r) => r.name)+ .filter((n): n is string => typeof n === "string" && n !== "")+ )+ );+ const nameMap = await getNameMap(db, "customer", companyId, csvNames);+ const customerIds = new Set<string>();+ // Tracks names queued for INSERT in this batch so a second CSV row+ // with the same name doesn't trip the (name, companyId) unique+ // constraint at flush time. The customer table enforces one record+ // per name per company, so duplicates within the CSV collapse.+ const namesQueuedForInsert = new Set<string>();++ await db.transaction().execute(async (trx) => {+ const customerInserts: Database["public"]["Tables"]["customer"]["Insert"][] =+ [];+ const customerTaxForInserts: Array<{+ taxId: string | null | undefined;+ }> = [];+ const csvIdsForInserts: string[] = [];+ const customerUpdates: {+ id: string;+ data: Database["public"]["Tables"]["customer"]["Update"];+ }[] = [];+ const customerTaxUpdates: Array<{+ entityId: string;+ taxId: string | null | undefined;+ }> = [];+ // Updates matched by name (no pre-existing csv mapping). After the+ // updates run, we add csv mappings for these so the next import takes+ // the externalIdMap path directly.+ const csvIdsForNameMatchedUpdates: Array<{+ entityId: string;+ externalId: string;+ }> = [];+ const extForInserts: PartnerExtensionData[] = [];+ const extForUpdates: Array<{+ entityId: string;+ ext: PartnerExtensionData;+ }> = [];++ for (const [rowIndex, record] of acceptedRows) {+ const ext = extractPartnerExtensions(record);+ const {+ id,+ taxId,+ locationName: _ln,+ addressLine1: _a1,+ addressLine2: _a2,+ city: _city,+ state: _state,+ postalCode: _pc,+ countryCode: _cc,+ paymentTermId: _pt,+ shippingMethodId: _sm,+ incoterm: _ic,+ incotermLocation: _icl,+ ...rest+ } = record;+ const matchedByCsvId = id ? externalIdMap.get(id) : undefined;+ const decision = classifyImportRow({+ id: id!,+ name: rest.name!,+ externalIdMap,+ nameMap,+ seenIds: customerIds,+ seenNames: namesQueuedForInsert+ });++ if (decision.action === "skip") {+ const bucket =+ decision.category === "error" ? summary.errors : summary.skipped;+ bucket.push({ row: rowIndex, reason: decision.reason });+ continue;+ }++ if (id) customerIds.add(id);+ if (decision.action === "insert")+ namesQueuedForInsert.add(rest.name!);++ if (decision.action === "update") {+ customerUpdates.push({+ id: decision.entityId,+ data: {+ ...nullifyEmptyStrings(+ pickColumns("customer", rest, CUSTOMER_COLUMNS)+ ),+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ }+ });+ customerTaxUpdates.push({ entityId: decision.entityId, taxId });+ extForUpdates.push({ entityId: decision.entityId, ext });+ // Only attach a CSV->entity mapping when there is a real external id.+ if (matchedByCsvId === undefined && id) {+ csvIdsForNameMatchedUpdates.push({+ entityId: decision.entityId,+ externalId: id+ });+ }+ } else {+ customerInserts.push({+ ...nullifyEmptyStrings(+ pickColumns("customer", rest, CUSTOMER_COLUMNS)+ ),+ readableId: (id || null) as string | undefined,+ companyId,+ createdAt: datetime.timestamp(),+ createdBy: userId+ } as Database["public"]["Tables"]["customer"]["Insert"]);+ customerTaxForInserts.push({ taxId });+ csvIdsForInserts.push(id!);+ extForInserts.push(ext);+ }+ }++ importCsvTableLogger.info({+ totalRecords: mappedRecords.length,+ customerInserts: customerInserts.length,+ customerUpdates: customerUpdates.length+ });+ summary.inserted += customerInserts.length;+ summary.updated += customerUpdates.length;++ if (customerInserts.length > 0) {+ const inserted = await inChunks(customerInserts, (rows) =>+ trx.insertInto(table).values(rows).returning(["id"]).execute()+ );+ await upsertCsvMappings(+ trx,+ "customer",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForInserts[i]!+ })),+ companyId,+ userId+ );+ await upsertTaxIdentifiers(+ trx,+ "customerTax",+ inserted.map((row, i) => ({+ entityId: row.id!,+ taxId: customerTaxForInserts[i]?.taxId+ })),+ companyId,+ userId+ );+ for (let i = 0; i < inserted.length; i++) {+ // Newly-inserted customers can't have an existing location yet.+ await writeCustomerExtensions(+ trx,+ inserted[i]!.id!,+ extForInserts[i] ?? {},+ companyId,+ userId,+ undefined+ );+ }+ }+ if (customerUpdates.length > 0) {+ for (const update of customerUpdates) {+ await trx+ .updateTable(table)+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ await upsertTaxIdentifiers(+ trx,+ "customerTax",+ customerTaxUpdates,+ companyId,+ userId+ );+ const customerAddressByEntity =+ await preloadPrimaryLocationAddressIds(+ trx,+ "customer",+ extForUpdates.map((u) => u.entityId)+ );+ for (const { entityId, ext } of extForUpdates) {+ await writeCustomerExtensions(+ trx,+ entityId,+ ext,+ companyId,+ userId,+ customerAddressByEntity.get(entityId)+ );+ }+ }+ if (csvIdsForNameMatchedUpdates.length > 0) {+ await upsertCsvMappings(+ trx,+ "customer",+ csvIdsForNameMatchedUpdates,+ companyId,+ userId+ );+ }+ });+ break;+ }+ case "supplier": {+ const externalIdMap = await getCsvExternalIdMap(+ db,+ "supplier",+ companyId+ );+ const csvNames = Array.from(+ new Set(+ mappedRecords+ .map((r) => r.name)+ .filter((n): n is string => typeof n === "string" && n !== "")+ )+ );+ const nameMap = await getNameMap(db, "supplier", companyId, csvNames);+ const supplierIds = new Set<string>();+ const namesQueuedForInsert = new Set<string>();++ await db.transaction().execute(async (trx) => {+ const supplierInserts: Database["public"]["Tables"]["supplier"]["Insert"][] =+ [];+ const supplierTaxForInserts: Array<{+ taxId: string | null | undefined;+ }> = [];+ const csvIdsForInserts: string[] = [];+ const supplierUpdates: {+ id: string;+ data: Database["public"]["Tables"]["supplier"]["Update"];+ }[] = [];+ const supplierTaxUpdates: Array<{+ entityId: string;+ taxId: string | null | undefined;+ }> = [];+ const csvIdsForNameMatchedUpdates: Array<{+ entityId: string;+ externalId: string;+ }> = [];+ // Parallel to supplierInserts / supplierUpdates — captures the+ // address/payment/incoterm fields so we can write to side-tables+ // after the parent upsert lands.+ const extForInserts: PartnerExtensionData[] = [];+ const extForUpdates: Array<{+ entityId: string;+ ext: PartnerExtensionData;+ }> = [];++ for (const [rowIndex, record] of acceptedRows) {+ const ext = extractPartnerExtensions(record);+ const {+ id,+ taxId,+ locationName: _ln,+ addressLine1: _a1,+ addressLine2: _a2,+ city: _city,+ state: _state,+ postalCode: _pc,+ countryCode: _cc,+ paymentTermId: _pt,+ shippingMethodId: _sm,+ incoterm: _ic,+ incotermLocation: _icl,+ ...rest+ } = record;+ const matchedByCsvId = id ? externalIdMap.get(id) : undefined;+ const decision = classifyImportRow({+ id: id!,+ name: rest.name!,+ externalIdMap,+ nameMap,+ seenIds: supplierIds,+ seenNames: namesQueuedForInsert+ });++ if (decision.action === "skip") {+ const bucket =+ decision.category === "error" ? summary.errors : summary.skipped;+ bucket.push({ row: rowIndex, reason: decision.reason });+ continue;+ }++ if (id) supplierIds.add(id);+ if (decision.action === "insert")+ namesQueuedForInsert.add(rest.name!);++ if (decision.action === "update") {+ supplierUpdates.push({+ id: decision.entityId,+ data: {+ ...nullifyEmptyStrings(+ pickColumns("supplier", rest, SUPPLIER_COLUMNS)+ ),+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ }+ });+ supplierTaxUpdates.push({ entityId: decision.entityId, taxId });+ extForUpdates.push({ entityId: decision.entityId, ext });+ // Only attach a CSV->entity mapping when there is a real external id.+ if (matchedByCsvId === undefined && id) {+ csvIdsForNameMatchedUpdates.push({+ entityId: decision.entityId,+ externalId: id+ });+ }+ } else {+ supplierInserts.push({+ ...nullifyEmptyStrings(+ pickColumns("supplier", rest, SUPPLIER_COLUMNS)+ ),+ readableId: (id || null) as string | undefined,+ companyId,+ createdAt: datetime.timestamp(),+ createdBy: userId+ } as Database["public"]["Tables"]["supplier"]["Insert"]);+ supplierTaxForInserts.push({ taxId });+ csvIdsForInserts.push(id!);+ extForInserts.push(ext);+ }+ }++ importCsvTableLogger.info({+ totalRecords: mappedRecords.length,+ supplierInserts: supplierInserts.length,+ supplierUpdates: supplierUpdates.length+ });+ summary.inserted += supplierInserts.length;+ summary.updated += supplierUpdates.length;++ if (supplierInserts.length > 0) {+ const inserted = await inChunks(supplierInserts, (rows) =>+ trx.insertInto(table).values(rows).returning(["id"]).execute()+ );+ await upsertCsvMappings(+ trx,+ "supplier",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForInserts[i]!+ })),+ companyId,+ userId+ );+ await upsertTaxIdentifiers(+ trx,+ "supplierTax",+ inserted.map((row, i) => ({+ entityId: row.id!,+ taxId: supplierTaxForInserts[i]?.taxId+ })),+ companyId,+ userId+ );+ for (let i = 0; i < inserted.length; i++) {+ // Newly-inserted suppliers can't have an existing location yet.+ await writeSupplierExtensions(+ trx,+ inserted[i]!.id!,+ extForInserts[i] ?? {},+ companyId,+ userId,+ undefined+ );+ }+ }+ if (supplierUpdates.length > 0) {+ for (const update of supplierUpdates) {+ await trx+ .updateTable(table)+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ await upsertTaxIdentifiers(+ trx,+ "supplierTax",+ supplierTaxUpdates,+ companyId,+ userId+ );+ const supplierAddressByEntity =+ await preloadPrimaryLocationAddressIds(+ trx,+ "supplier",+ extForUpdates.map((u) => u.entityId)+ );+ for (const { entityId, ext } of extForUpdates) {+ await writeSupplierExtensions(+ trx,+ entityId,+ ext,+ companyId,+ userId,+ supplierAddressByEntity.get(entityId)+ );+ }+ }+ if (csvIdsForNameMatchedUpdates.length > 0) {+ await upsertCsvMappings(+ trx,+ "supplier",+ csvIdsForNameMatchedUpdates,+ companyId,+ userId+ );+ }+ });+ break;+ }+ case "material":+ case "consumable":+ case "tool":+ case "fixture":+ case "service":+ case "part": {+ const getExternalId = (id: string) => {+ return `${table}:${id}`;+ };++ // A service can never be shipped, received or stocked. The wizard+ // therefore offers neither a Tracking Type nor a Default Method column+ // for one: the validator below requires a tracking type, and the method+ // is fully determined by the replenishment system — "Pull from+ // Inventory" is not valid for a Non-Inventory item, and an independent+ // column could contradict the replenishment system on the same row.+ // `ServiceForm` derives both the same way and hides the method field.+ // A service is identified by its name: the wizard offers no Service ID,+ // Revision or Unit of Measure column — the name is its readable id and+ // its unit is Each, as in `upsertService`.+ if (table === "service") {+ for (const record of mappedRecords) {+ // A missing name stays undefined, so validation reports it.+ const name = record.name?.trim() as string;+ record.name = name;+ record.readableId = name;+ record.revision = "0";+ record.unitOfMeasureCode = "EA";+ record.itemTrackingType = "Non-Inventory";+ record.defaultMethodType =+ record.replenishmentSystem === "Make"+ ? "Make to Order"+ : "Purchase to Order";+ }+ }++ const externalIdMap = await getCsvExternalIdMap(db, "item", companyId);+ const readableIds = new Set();++ await db.transaction().execute(async (trx) => {+ const itemInserts: Database["public"]["Tables"]["item"]["Insert"][] =+ [];+ const csvIdsForInserts: string[] = [];+ const itemUpdates: {+ id: string;+ data: Database["public"]["Tables"]["item"]["Update"];+ }[] = [];+ const materialPartialInserts: Record<+ string,+ Database["public"]["Tables"]["material"]["Insert"]+ > = {};++ const materialUpdates: {+ id: string;+ data: Database["public"]["Tables"]["material"]["Update"];+ }[] = [];++ // Optional supplier-part fields ride along on each row. Parallel to+ // itemInserts; supplierPartLinks accumulates the full resolved+ // links (with the item's actual DB id) as the inserts/updates land.+ const supplierPartForInserts: Array<{+ supplierId?: string;+ supplierPartId?: string;+ supplierUnitOfMeasureCode?: string;+ minimumOrderQuantity?: string;+ orderMultiple?: string;+ conversionFactor?: string;+ unitPrice?: string;+ }> = [];+ const supplierPartLinks: SupplierPartImportLink[] = [];+ // Item-level purchasing lead times. leadTimeForInserts is parallel to+ // itemInserts (filled in the insert branch); purchasingLeadTimes+ // collects the final {itemId, leadTime} entries once item ids are+ // known (immediately for updates, post-insert for new items).+ const leadTimeForInserts: Array<string | undefined> = [];+ const purchasingLeadTimes: ItemPurchasingLeadTime[] = [];+ // Item-level unit cost — same parallel-array pattern as lead time.+ const unitCostForInserts: Array<string | undefined> = [];+ const itemUnitCosts: ItemUnitCost[] = [];+ // Same shape for the item-level planning order multiple. CSV's+ // "Order Multiple" column populates both supplierPart.orderMultiple+ // (per-supplier case-pack) and itemPlanning.orderMultiple+ // (per-(item, location) MRP setting) at import time.+ const orderMultipleForInserts: Array<string | undefined> = [];+ const itemPlanningOrderMultiples: ItemPlanningOrderMultiple[] = [];++ const itemValidator = z.object({+ // Unique ID is the external-integration mapping key and the upsert+ // key (externalIdMap), so a blank one is broken data, not a new row.+ // Part Number / Description are likewise required for a usable item.+ id: z.string().min(1, { message: "Unique ID is required" }),+ readableId: z.string().min(1, {+ // A service's readable id is its name (set above).+ message:+ table === "service"+ ? "Name is required"+ : "Part Number is required"+ }),+ revision: z.string().optional(),+ name: z.string().min(1, { message: "Description is required" }),+ description: z.string().optional(),+ mpn: z.string().optional(),+ active: z.string().optional(),+ unitOfMeasureCode: z.string().optional(),+ replenishmentSystem: z+ .enum(["Buy", "Make", "Buy and Make"])+ .optional(),+ defaultMethodType: z+ .enum(["Purchase to Order", "Make to Order", "Pull from Inventory"])+ .optional(),+ itemTrackingType: z.enum([+ "Inventory",+ "Non-Inventory",+ "Serial",+ "Batch"+ ])+ });++ const materialValidator = itemValidator.extend({+ materialSubstanceId: z.string().optional(),+ materialFormId: z.string().optional(),+ finishId: z.string().optional(),+ dimensionId: z.string().optional(),+ gradeId: z.string().optional(),+ // Raw text from the mapping UI; resolved to the *Id columns below.+ finish: z.string().optional(),+ grade: z.string().optional(),+ dimensions: z.string().optional()+ });++ // The mapping UI sends Finish / Grade / Dimensions as raw CSV text —+ // materialFinish/materialGrade are scoped by substance and+ // materialDimension by form, so a flat enum mapping can't target+ // them. Resolve the text to taxonomy ids up front (creating+ // company-scoped rows for unmatched names). Rows without a resolved+ // substance/form keep the attribute unset, since the taxonomy+ // tables require the scope.+ let finishIdByKey = new Map<string, string>();+ let gradeIdByKey = new Map<string, string>();+ let dimensionIdByKey = new Map<string, string>();++ if (table === "material") {+ const finishPairs: Array<{ scopeId: string; name: string }> = [];+ const gradePairs: Array<{ scopeId: string; name: string }> = [];+ const dimensionPairs: Array<{ scopeId: string; name: string }> = [];++ // Rejected rows are left out: one may name another company's+ // substance or form, and resolving it would create taxonomy rows+ // under that parent.+ for (const [, record] of acceptedRows) {+ const substanceId = record.materialSubstanceId;+ const formId = record.materialFormId;+ // An explicit *Id (possible via direct invocation) wins over the+ // raw text, so don't resolve — and possibly create — a taxonomy+ // row that nothing would reference.+ if (substanceId && record.finish && !record.finishId) {+ finishPairs.push({ scopeId: substanceId, name: record.finish });+ }+ if (substanceId && record.grade && !record.gradeId) {+ gradePairs.push({ scopeId: substanceId, name: record.grade });+ }+ if (formId && record.dimensions && !record.dimensionId) {+ dimensionPairs.push({+ scopeId: formId,+ name: record.dimensions+ });+ }+ }++ finishIdByKey = await resolveMaterialTaxonomyIds(+ trx,+ "materialFinish",+ "materialSubstanceId",+ finishPairs,+ companyId+ );+ gradeIdByKey = await resolveMaterialTaxonomyIds(+ trx,+ "materialGrade",+ "materialSubstanceId",+ gradePairs,+ companyId+ );+ dimensionIdByKey = await resolveMaterialTaxonomyIds(+ trx,+ "materialDimension",+ "materialFormId",+ dimensionPairs,+ companyId+ );+ }++ const resolveFinishId = (data: {+ materialSubstanceId?: string;+ finish?: string;+ }) =>+ data.materialSubstanceId && data.finish+ ? finishIdByKey.get(+ materialTaxonomyKey(data.materialSubstanceId, data.finish)+ )+ : undefined;++ const resolveGradeId = (data: {+ materialSubstanceId?: string;+ grade?: string;+ }) =>+ data.materialSubstanceId && data.grade+ ? gradeIdByKey.get(+ materialTaxonomyKey(data.materialSubstanceId, data.grade)+ )+ : undefined;++ const resolveDimensionId = (data: {+ materialFormId?: string;+ dimensions?: string;+ }) =>+ data.materialFormId && data.dimensions+ ? dimensionIdByKey.get(+ materialTaxonomyKey(data.materialFormId, data.dimensions)+ )+ : undefined;++ // Rows on the INSERT path whose Unique ID already exists in this+ // company's catalog (e.g. a re-import after the item was deleted,+ // which frees the Unique ID to collide on the un-onConflict'd+ // sub-table inserts) would otherwise abort the whole transaction with+ // an opaque 500. Detect them up front so we can report a clear per-row+ // reason and skip just those rows while the rest still import.+ const candidateReadableIds = [+ ...new Set(+ mappedRecords+ .map((r) => r.readableId)+ .filter((id): id is string => !!id && id.trim() !== "")+ )+ ];+ // readable id with revision → item id, so an update can tell its own+ // key from another item's.+ const existingItemKeys = new Map<string, string>();+ if (candidateReadableIds.length > 0) {+ const existingItems = await trx+ .selectFrom("item")+ .select(["id", "readableId", "revision"])+ .where("companyId", "=", companyId)+ .where(+ "type",+ "=",+ capitalize(table) as+ | "Part"+ | "Service"+ | "Material"+ | "Tool"+ | "Fixture"+ | "Consumable"+ )+ .where("readableId", "in", candidateReadableIds)+ .execute();+ for (const existing of existingItems) {+ existingItemKeys.set(+ getReadableIdWithRevision(existing.readableId, existing.revision),+ existing.id+ );+ }+ }++ for (const [rowIndex, record] of acceptedRows) {+ const item = itemValidator.safeParse(record);++ if (!item.success) {+ summary.errors.push({+ row: rowIndex,+ reason: item.error.issues[0]?.message ?? "Invalid row"+ });+ continue;+ }++ const { id, ...rest } = item.data;+ // A blank Revision cell arrives as "" — not undefined — so the+ // `??` this replaced let it through and the item landed with an+ // empty revision instead of the "0" the wizard advertises as the+ // default. (Unreachable until the route stopped stripping the+ // field, which made `rest.revision` genuinely present-but-empty.)+ // Normalize once, before the dedup key is built from it, so the+ // key and the stored value cannot disagree.+ const revision = rest.revision || "0";+ const readableIdWithRevision = getReadableIdWithRevision(+ item.data.readableId,+ revision+ );++ if (+ externalIdMap.has(getExternalId(id)) &&+ !readableIds.has(readableIdWithRevision)+ ) {+ const existingEntityId = externalIdMap.get(getExternalId(id))!;++ readableIds.add(readableIdWithRevision);+ // Renaming onto another item's readable id would violate+ // item_unique and abort the whole import; refuse just this row.+ const owner = existingItemKeys.get(readableIdWithRevision);+ if (owner && owner !== existingEntityId) {+ summary.errors.push({+ row: rowIndex,+ reason:+ table === "service"+ ? `A service named "${item.data.readableId}" already exists.`+ : `An item with Unique ID "${item.data.readableId}" already exists.`+ });+ continue;+ }+ itemUpdates.push({+ id: existingEntityId,+ data: {+ ...rest,+ revision,+ active: rest.active?.toLowerCase() !== "false",+ unitOfMeasureCode: rest.unitOfMeasureCode || undefined,+ description: rest.description || undefined,+ replenishmentSystem: rest.replenishmentSystem || undefined,+ defaultMethodType: rest.defaultMethodType || undefined,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ }+ });++ // Existing item: we already know its id, so the supplierPart+ // link can be queued directly.+ if (record.supplierId) {+ supplierPartLinks.push({+ itemId: existingEntityId,+ supplierId: record.supplierId,+ supplierPartId: record.supplierPartId,+ supplierUnitOfMeasureCode: record.supplierUnitOfMeasureCode,+ minimumOrderQuantity: record.minimumOrderQuantity,+ orderMultiple: record.orderMultiple,+ conversionFactor: record.conversionFactor,+ unitPrice: record.unitPrice+ });+ }++ if (record.leadTime) {+ purchasingLeadTimes.push({+ itemId: existingEntityId,+ leadTime: record.leadTime+ });+ }++ if (record.unitCost) {+ itemUnitCosts.push({+ itemId: existingEntityId,+ unitCost: record.unitCost+ });+ }++ if (record.orderMultiple) {+ itemPlanningOrderMultiples.push({+ itemId: existingEntityId,+ orderMultiple: record.orderMultiple+ });+ }++ if (table === "material") {+ const material = materialValidator.safeParse(record);+ if (material.success) {+ materialUpdates.push({+ id: material.data.readableId,+ data: {+ materialSubstanceId:+ material.data.materialSubstanceId || undefined,+ materialFormId: material.data.materialFormId || undefined,+ dimensionId:+ material.data.dimensionId ||+ resolveDimensionId(material.data) ||+ undefined,+ gradeId:+ material.data.gradeId ||+ resolveGradeId(material.data) ||+ undefined,+ finishId:+ material.data.finishId ||+ resolveFinishId(material.data) ||+ undefined,+ companyId,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ }+ });+ }+ }+ } else if (!readableIds.has(readableIdWithRevision)) {+ readableIds.add(readableIdWithRevision);+ if (existingItemKeys.has(readableIdWithRevision)) {+ summary.errors.push({+ row: rowIndex,+ reason:+ table === "service"+ ? `A service named "${item.data.readableId}" already exists. Change the Name or delete the existing service, then re-import.`+ : `An item with Unique ID "${item.data.readableId}" already exists. Change the Unique ID (and Name) or delete the existing item, then re-import.`+ });+ continue;+ }+ const newItem = {+ ...rest,+ replenishmentSystem: rest.replenishmentSystem ?? "Buy",+ active: rest.active?.toLowerCase() !== "false",+ unitOfMeasureCode: rest.unitOfMeasureCode || undefined,+ description: rest.description || undefined,+ defaultMethodType: rest.defaultMethodType || undefined,+ type: capitalize(table) as+ | "Part"+ | "Service"+ | "Material"+ | "Tool"+ | "Fixture"+ | "Consumable",+ companyId,+ revision,+ createdAt: datetime.timestamp(),+ createdBy: userId+ };+ itemInserts.push(newItem);+ csvIdsForInserts.push(getExternalId(id));+ // New item: id will come back from the bulk insert. Capture+ // supplier-part data and lead time in parallel arrays so we can+ // build the link / lead-time entry once the id is known.+ supplierPartForInserts.push({+ supplierId: record.supplierId,+ supplierPartId: record.supplierPartId,+ supplierUnitOfMeasureCode: record.supplierUnitOfMeasureCode,+ minimumOrderQuantity: record.minimumOrderQuantity,+ orderMultiple: record.orderMultiple,+ conversionFactor: record.conversionFactor,+ unitPrice: record.unitPrice+ });+ leadTimeForInserts.push(record.leadTime);+ orderMultipleForInserts.push(record.orderMultiple);+ unitCostForInserts.push(record.unitCost);++ if (table === "material") {+ const material = materialValidator.safeParse(record);+ if (!material.success) {+ summary.errors.push({+ row: rowIndex,+ reason:+ material.error.issues[0]?.message ?? "Invalid material row"+ });+ continue;+ }+ if (material.success) {+ materialPartialInserts[material.data.readableId!] = {+ ...material.data,+ id: material.data.readableId,+ dimensionId:+ material.data.dimensionId ||+ resolveDimensionId(material.data),+ gradeId:+ material.data.gradeId || resolveGradeId(material.data),+ finishId:+ material.data.finishId || resolveFinishId(material.data),+ companyId,+ createdAt: datetime.timestamp(),+ createdBy: userId+ };+ }+ }+ }+ }++ if (itemInserts.length > 0) {+ const insertedItems = await inChunks(itemInserts, (rows) =>+ trx+ .insertInto("item")+ .values(rows)+ .onConflict((oc) =>+ oc.constraint("item_unique").doUpdateSet({+ updatedAt: datetime.timestamp(),+ updatedBy: userId,+ name: sql`EXCLUDED."name"`,+ description: sql`EXCLUDED."description"`,+ mpn: sql`EXCLUDED."mpn"`,+ active: sql`EXCLUDED."active"`,+ unitOfMeasureCode: sql`EXCLUDED."unitOfMeasureCode"`,+ replenishmentSystem: sql`EXCLUDED."replenishmentSystem"`,+ defaultMethodType: sql`EXCLUDED."defaultMethodType"`,+ itemTrackingType: sql`EXCLUDED."itemTrackingType"`+ })+ )+ .returning(["id", "readableId"])+ .execute()+ );++ await upsertCsvMappings(+ trx,+ "item",+ insertedItems.map((item, i) => ({+ entityId: item.id!,+ externalId: csvIdsForInserts[i]!+ })),+ companyId,+ userId+ );++ if (+ ["part", "fixture", "tool", "consumable", "service"].includes(table)+ ) {+ const specificInserts = insertedItems.map((item) => ({+ id: item.readableId,+ // `service` has its own `approved` default and a legacy+ // NOT NULL `serviceType` the UI no longer surfaces —+ // `upsertService` writes "External" for the same reason.+ ...(table === "service"+ ? { serviceType: "External" }+ : { approved: true }),+ companyId,+ createdAt: datetime.timestamp(),+ createdBy: userId+ }));++ await inChunks(specificInserts, (rows) =>+ trx+ .insertInto(table)+ .values(rows as unknown as never)+ // Hard-deleting an item does NOT remove its type row: the type+ // tables (part/tool/fixture/consumable) key on readableId and have+ // no FK back to item, so the row is orphaned by (id, companyId).+ // Re-importing that Part Number would otherwise collide on the PK+ // and abort the whole import (the "deleted then re-imported and it+ // failed" case). The orphan already represents this Part Number, so+ // keep it.+ .onConflict((oc: any) =>+ oc.columns(["id", "companyId"]).doNothing()+ )+ .execute()+ );+ }++ if (+ table === "material" &&+ Object.keys(materialPartialInserts).length > 0+ ) {+ const materialInserts = insertedItems.reduce<+ Database["public"]["Tables"]["material"]["Insert"][]+ >((acc, item) => {+ const materialData = materialPartialInserts[item.readableId];+ if (materialData) {+ acc.push({+ id: item.readableId,+ materialSubstanceId:+ materialData.materialSubstanceId || undefined,+ materialFormId: materialData.materialFormId || undefined,+ dimensionId: materialData.dimensionId || undefined,+ gradeId: materialData.gradeId || undefined,+ finishId: materialData.finishId || undefined,+ companyId,+ createdAt: datetime.timestamp(),+ createdBy: userId+ });+ }+ return acc;+ }, []);++ await inChunks(materialInserts, (rows) =>+ trx+ .insertInto("material")+ .values(rows)+ // Same orphan-after-delete case as the type insert above: the+ // material row survives an item delete, so re-import must not+ // collide on the (id, companyId) PK.+ .onConflict((oc) => oc.columns(["id", "companyId"]).doNothing())+ .execute()+ );+ }++ // Build supplier-part links and lead-time entries for the items we+ // just inserted. supplierPartForInserts / leadTimeForInserts are+ // parallel to itemInserts; only rows with a supplier produce a+ // link, only rows with a lead time produce a lead-time entry.+ for (let i = 0; i < insertedItems.length; i++) {+ const sp = supplierPartForInserts[i];+ if (sp?.supplierId && insertedItems[i]!.id) {+ supplierPartLinks.push({+ itemId: insertedItems[i]!.id!,+ supplierId: sp.supplierId,+ supplierPartId: sp.supplierPartId,+ supplierUnitOfMeasureCode: sp.supplierUnitOfMeasureCode,+ minimumOrderQuantity: sp.minimumOrderQuantity,+ orderMultiple: sp.orderMultiple,+ conversionFactor: sp.conversionFactor,+ unitPrice: sp.unitPrice+ });+ }+ const leadTime = leadTimeForInserts[i];+ if (leadTime && insertedItems[i]!.id) {+ purchasingLeadTimes.push({+ itemId: insertedItems[i]!.id!,+ leadTime+ });+ }+ const orderMultiple = orderMultipleForInserts[i];+ if (orderMultiple && insertedItems[i]!.id) {+ itemPlanningOrderMultiples.push({+ itemId: insertedItems[i]!.id!,+ orderMultiple+ });+ }+ const unitCost = unitCostForInserts[i];+ if (unitCost && insertedItems[i]!.id) {+ itemUnitCosts.push({+ itemId: insertedItems[i]!.id!,+ unitCost+ });+ }+ }+ }++ importCsvTableLogger.info({+ totalRecords: mappedRecords.length,+ itemInserts: itemInserts.length,+ itemUpdates: itemUpdates.length,+ materialInserts: Object.keys(materialPartialInserts).length,+ materialUpdates: materialUpdates.length+ });++ if (itemUpdates.length > 0) {+ const currentItems = await trx+ .selectFrom("item")+ .select(["id", "readableId"])+ .where(+ "id",+ "in",+ itemUpdates.map((u) => u.id)+ )+ .execute();+ const currentReadableIdMap = new Map(+ currentItems.map((i) => [i.id, i.readableId])+ );++ for (const update of itemUpdates) {+ await trx+ .updateTable("item")+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ for (const update of itemUpdates) {+ const oldReadableId = currentReadableIdMap.get(update.id);+ const newReadableId = update.data.readableId;+ if (+ newReadableId &&+ oldReadableId &&+ oldReadableId !== newReadableId+ ) {+ await trx+ .updateTable(table)+ .set({ id: newReadableId } as never)+ .where("id", "=", oldReadableId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (materialUpdates.length > 0) {+ for (const update of materialUpdates) {+ await trx+ .updateTable("material")+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ }++ await writeSupplierPartLinks(trx, supplierPartLinks, companyId, userId);++ await writeItemPurchasingLeadTimes(+ trx,+ purchasingLeadTimes,+ companyId,+ userId+ );++ await writeItemPlanningOrderMultiples(+ trx,+ itemPlanningOrderMultiples,+ companyId,+ userId+ );++ await writeItemUnitCosts(trx, itemUnitCosts, companyId, userId);++ // Items were silently uncounted before — only customer/supplier+ // incremented the summary. Count inserts/updates here so the toast+ // reports the real totals instead of "Imported 0, Updated 0".+ summary.inserted += itemInserts.length;+ summary.updated += itemUpdates.length;+ });++ break;+ }+ case "customerContact": {+ const externalContactIdMap = await getCsvExternalIdMap(+ db,+ "contact",+ companyId+ );+ const externalCustomerIdMap = await getCsvExternalIdMap(+ db,+ "customer",+ companyId+ );++ await db.transaction().execute(async (trx) => {+ const contactInserts: Database["public"]["Tables"]["contact"]["Insert"][] =+ [];+ const csvIdsForContactInserts: string[] = [];+ const contactUpdates: {+ id: string;+ data: Database["public"]["Tables"]["contact"]["Update"];+ }[] = [];+ const customerContactInserts: Database["public"]["Tables"]["customerContact"]["Insert"][] =+ [];++ const isContactValid = (record: {+ email?: string | null;+ }): record is {+ email: string;+ } => {+ return typeof record.email === "string" && record.email.trim() !== "";+ };++ for (const [rowIndex, record] of mappedRecords.entries()) {+ // `companyId` here is the parent's External Company ID; only+ // contact columns are written.+ const { id, companyId: customerId } = record;+ const contactData = pickColumns("contact", record, CONTACT_COLUMNS);++ if (externalContactIdMap.has(id!)) {+ const existingEntityId = externalContactIdMap.get(id!)!;+ if (isContactValid(contactData)) {+ contactUpdates.push({+ id: existingEntityId,+ data: {+ ...contactData+ }+ });+ }+ } else if (+ isContactValid(contactData) &&+ externalCustomerIdMap.has(customerId!)+ ) {+ const existingCustomerId = externalCustomerIdMap.get(customerId!)!;+ const contactId = nanoid();+ const newContact = {+ id: contactId,+ ...contactData,+ companyId+ };++ contactInserts.push(newContact);+ csvIdsForContactInserts.push(id!);+ customerContactInserts.push({+ contactId,+ customerId: existingCustomerId,+ companyId,+ customFields: {}+ });+ } else {+ summary.errors.push({+ row: rowIndex,+ reason: isContactValid(contactData)+ ? `No customer found for External Company ID "${customerId}"`+ : "Invalid contact (missing required fields)"+ });+ }+ }++ summary.inserted += contactInserts.length;+ summary.updated += contactUpdates.length;++ importCsvTableLogger.info({+ totalRecords: mappedRecords.length,+ contactInserts: contactInserts.length,+ contactUpdates: contactUpdates.length,+ customerContactInserts: customerContactInserts.length+ });++ if (contactInserts.length > 0) {+ const inserted = await inChunks(contactInserts, (rows) =>+ trx.insertInto("contact").values(rows).returning(["id"]).execute()+ );+ await upsertCsvMappings(+ trx,+ "contact",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForContactInserts[i]!+ })),+ companyId,+ userId+ );+ }++ if (contactUpdates.length > 0) {+ for (const update of contactUpdates) {+ await trx+ .updateTable("contact")+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (customerContactInserts.length > 0) {+ await inChunks(customerContactInserts, (rows) =>+ trx.insertInto("customerContact").values(rows).execute()+ );+ }+ });++ break;+ }+ case "supplierContact": {+ const externalContactIdMap = await getCsvExternalIdMap(+ db,+ "contact",+ companyId+ );+ const externalSupplierIdMap = await getCsvExternalIdMap(+ db,+ "supplier",+ companyId+ );++ await db.transaction().execute(async (trx) => {+ const contactInserts: Database["public"]["Tables"]["contact"]["Insert"][] =+ [];+ const csvIdsForContactInserts: string[] = [];+ const contactUpdates: {+ id: string;+ data: Database["public"]["Tables"]["contact"]["Update"];+ }[] = [];+ const supplierContactInserts: Database["public"]["Tables"]["supplierContact"]["Insert"][] =+ [];++ const isContactValid = (record: {+ email?: string | null;+ }): record is {+ email: string;+ } => {+ return typeof record.email === "string" && record.email.trim() !== "";+ };++ for (const [rowIndex, record] of mappedRecords.entries()) {+ // `companyId` here is the parent's External Company ID; only+ // contact columns are written.+ const { id, companyId: supplierId } = record;+ const contactData = pickColumns("contact", record, CONTACT_COLUMNS);++ if (externalContactIdMap.has(id!)) {+ const existingEntityId = externalContactIdMap.get(id!)!;+ if (isContactValid(contactData)) {+ contactUpdates.push({+ id: existingEntityId,+ data: {+ ...contactData+ }+ });+ }+ } else if (+ isContactValid(contactData) &&+ externalSupplierIdMap.has(supplierId!)+ ) {+ const existingSupplierId = externalSupplierIdMap.get(supplierId!)!;+ const contactId = nanoid();+ const newContact = {+ id: contactId,+ ...contactData,+ companyId+ };+ contactInserts.push(newContact);+ csvIdsForContactInserts.push(id!);+ supplierContactInserts.push({+ contactId,+ supplierId: existingSupplierId,+ companyId,+ customFields: {}+ });+ } else {+ summary.errors.push({+ row: rowIndex,+ reason: isContactValid(contactData)+ ? `No supplier found for External Company ID "${supplierId}"`+ : "Invalid contact (missing required fields)"+ });+ }+ }++ summary.inserted += contactInserts.length;+ summary.updated += contactUpdates.length;++ importCsvTableLogger.info({+ totalRecords: mappedRecords.length,+ contactInserts: contactInserts.length,+ contactUpdates: contactUpdates.length,+ supplierContactInserts: supplierContactInserts.length+ });++ if (contactInserts.length > 0) {+ const inserted = await inChunks(contactInserts, (rows) =>+ trx.insertInto("contact").values(rows).returning(["id"]).execute()+ );+ await upsertCsvMappings(+ trx,+ "contact",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForContactInserts[i]!+ })),+ companyId,+ userId+ );+ }++ if (contactUpdates.length > 0) {+ for (const update of contactUpdates) {+ await trx+ .updateTable("contact")+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (supplierContactInserts.length > 0) {+ await inChunks(supplierContactInserts, (rows) =>+ trx.insertInto("supplierContact").values(rows).execute()+ );+ }+ });++ break;+ }+ case "workCenter": {+ const externalIdMap = await getCsvExternalIdMap(+ db,+ "workCenter",+ companyId+ );+ const workCenterIds = new Set();++ await db.transaction().execute(async (trx) => {+ const workCenterInserts: Database["public"]["Tables"]["workCenter"]["Insert"][] =+ [];+ const csvIdsForInserts: string[] = [];+ const workCenterUpdates: {+ id: string;+ data: Database["public"]["Tables"]["workCenter"]["Update"];+ }[] = [];++ const isWorkCenterValid = (+ record: Record<string, string>+ ): record is Record<string, string> & {+ name: string;+ locationId: string;+ } => {+ return (+ typeof record.name === "string" &&+ record.name.trim() !== "" &&+ typeof record.locationId === "string" &&+ record.locationId.trim() !== ""+ );+ };++ for (const [, record] of acceptedRows) {+ const { id, ...rest } = record;+ if (externalIdMap.has(id!)) {+ const existingEntityId = externalIdMap.get(id!)!;+ if (isWorkCenterValid(rest) && !workCenterIds.has(id)) {+ workCenterIds.add(id);+ workCenterUpdates.push({+ id: existingEntityId,+ data: {+ ...pickColumns("workCenter", rest, WORK_CENTER_COLUMNS),+ laborRate: rest.laborRate ? parseFloat(rest.laborRate) : 0,+ machineRate: rest.machineRate+ ? parseFloat(rest.machineRate)+ : 0,+ overheadRate: rest.overheadRate+ ? parseFloat(rest.overheadRate)+ : 0,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ }+ });+ }+ } else if (isWorkCenterValid(rest) && !workCenterIds.has(id)) {+ workCenterIds.add(id);+ workCenterInserts.push({+ ...pickColumns("workCenter", rest, WORK_CENTER_COLUMNS),+ laborRate: rest.laborRate ? parseFloat(rest.laborRate) : 0,+ machineRate: rest.machineRate ? parseFloat(rest.machineRate) : 0,+ overheadRate: rest.overheadRate+ ? parseFloat(rest.overheadRate)+ : 0,+ companyId,+ createdAt: datetime.timestamp(),+ createdBy: userId+ } as never);+ csvIdsForInserts.push(id!);+ }+ }++ importCsvTableLogger.info({+ totalRecords: mappedRecords.length,+ workCenterInserts: workCenterInserts.length,+ workCenterUpdates: workCenterUpdates.length+ });++ if (workCenterInserts.length > 0) {+ const inserted = await inChunks(workCenterInserts, (rows) =>+ trx+ .insertInto("workCenter")+ .values(rows)+ .returning(["id"])+ .execute()+ );+ await upsertCsvMappings(+ trx,+ "workCenter",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForInserts[i]!+ })),+ companyId,+ userId+ );+ }+ if (workCenterUpdates.length > 0) {+ for (const update of workCenterUpdates) {+ await trx+ .updateTable("workCenter")+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ });+ break;+ }+ case "process": {+ const externalIdMap = await getCsvExternalIdMap(db, "process", companyId);+ const processIds = new Set();++ await db.transaction().execute(async (trx) => {+ const processInserts: Database["public"]["Tables"]["process"]["Insert"][] =+ [];+ const csvIdsForInserts: string[] = [];+ const processUpdates: {+ id: string;+ data: Database["public"]["Tables"]["process"]["Update"];+ }[] = [];++ // Legacy CSV templates may still use the old Inside/Outside process types.+ const normalizeProcessType = (value: string) =>+ (value === "Inside"+ ? "Process"+ : value === "Outside" || value === "Inside and Outside"+ ? "Outside Processing"+ : value) as Database["public"]["Enums"]["operationType"];++ const validProcessTypes = [+ "Process",+ "Assembly",+ "Inspection",+ "Outside Processing"+ ];++ const isProcessValid = (+ record: Record<string, string>+ ): record is Record<string, string> & {+ name: string;+ processType: string;+ } => {+ return (+ typeof record.name === "string" &&+ record.name.trim() !== "" &&+ typeof record.processType === "string" &&+ validProcessTypes.includes(normalizeProcessType(record.processType))+ );+ };++ for (const record of mappedRecords) {+ const { id, ...rest } = record;+ if (externalIdMap.has(id!)) {+ const existingEntityId = externalIdMap.get(id!)!;+ if (isProcessValid(rest) && !processIds.has(id)) {+ processIds.add(id);+ processUpdates.push({+ id: existingEntityId,+ data: {+ ...pickColumns("process", rest, PROCESS_COLUMNS),+ processType: normalizeProcessType(rest.processType),+ completeAllOnScan:+ rest.completeAllOnScan?.toLowerCase() === "true",+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ }+ });+ }+ } else if (isProcessValid(rest) && !processIds.has(id)) {+ processIds.add(id);+ processInserts.push({+ ...pickColumns("process", rest, PROCESS_COLUMNS),+ processType: normalizeProcessType(rest.processType),+ completeAllOnScan:+ rest.completeAllOnScan?.toLowerCase() === "true",+ companyId,+ createdAt: datetime.timestamp(),+ createdBy: userId+ } as never);+ csvIdsForInserts.push(id!);+ }+ }++ importCsvTableLogger.info({+ totalRecords: mappedRecords.length,+ processInserts: processInserts.length,+ processUpdates: processUpdates.length+ });++ if (processInserts.length > 0) {+ const inserted = await inChunks(processInserts, (rows) =>+ trx.insertInto("process").values(rows).returning(["id"]).execute()+ );+ await upsertCsvMappings(+ trx,+ "process",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForInserts[i]!+ })),+ companyId,+ userId+ );+ }+ if (processUpdates.length > 0) {+ for (const update of processUpdates) {+ await trx+ .updateTable("process")+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ });+ break;+ }+ case "storageUnit": {+ const externalIdMap = await getCsvExternalIdMap(+ db,+ "storageUnit",+ companyId+ );+ // Entities that already carry a csv mapping. externalIntegrationMapping+ // is unique on (entityType, entityId, integration, companyId) — ONE+ // external id per entity — so a name-matched update must NOT attach a+ // second external id to an entity that already has one (it would violate+ // that index and roll back the whole import).+ const alreadyMappedEntityIds = new Set(externalIdMap.values());++ // Stored location of each already-mapped entity. A csv-id match that+ // resolves to a unit in a DIFFERENT location than the row states is a+ // conflict, not a move — used below to reject it instead of silently+ // renaming the wrong unit or crashing on storageUnit_name_locationId_key.+ const mappedEntityIds = Array.from(alreadyMappedEntityIds);+ const entityLocation = new Map<string, string>(+ (mappedEntityIds.length > 0+ ? await db+ .selectFrom("storageUnit")+ .select(["id", "locationId"])+ .where("id", "in", mappedEntityIds)+ .execute()+ : []+ ).map((r) => [r.id, r.locationId])+ );++ // Storage unit names are unique per location+ // (storageUnit_name_locationId_key), so the natural key for both in-file+ // dedup and match-existing-to-update is (locationId + lowercased name).+ const naturalKey = (locationId: string, name: string) =>+ `${locationId}::${name.trim().toLowerCase()}`;++ // Preload existing units for the referenced locations so a name that+ // already exists updates instead of tripping the unique constraint, and+ // so parent references can resolve against pre-existing units.+ const referencedLocationIds = Array.from(+ new Set(+ mappedRecords+ .map((r) => r.locationId)+ .filter(+ (l): l is string => typeof l === "string" && l.trim() !== ""+ )+ )+ );+ const existingUnits =+ referencedLocationIds.length > 0+ ? await db+ .selectFrom("storageUnit")+ .select(["id", "name", "locationId"])+ .where("companyId", "=", companyId)+ .where("locationId", "in", referencedLocationIds)+ .execute()+ : [];+ // (locationId + lowercased name) -> storageUnit id. Grows as we insert,+ // so a child whose parent is defined later in the same file resolves.+ const naturalKeyMap = new Map<string, string>();+ for (const u of existingUnits) {+ naturalKeyMap.set(naturalKey(u.locationId, u.name), u.id);+ }++ // Preload existing storage types (lowercased name -> id). Unmatched+ // names create a company-scoped storageType, mirroring the creatable+ // StorageTypes combobox on the storage-unit form.+ const existingTypes = await db+ .selectFrom("storageType")+ .select(["id", "name"])+ .where("companyId", "=", companyId)+ .execute();+ const storageTypeByName = new Map<string, string>();+ for (const st of existingTypes) {+ storageTypeByName.set(st.name.trim().toLowerCase(), st.id);+ }++ const parseActive = (value: string | undefined): boolean => {+ const v = (value ?? "").trim().toLowerCase();+ // Default active; only explicit falsey values deactivate.+ return !["false", "no", "0", "inactive", "n"].includes(v);+ };+ const parseTypeNames = (value: string | undefined): string[] =>+ (value ?? "")+ .split(",")+ .map((s) => s.trim())+ .filter((s) => s !== "");++ const seenNaturalKeys = new Set<string>();+ const seenCsvIds = new Set<string>();+ // Parent links are applied in a second pass (after all inserts) so a+ // parent defined later in the same file resolves and a bad parent+ // reports a row error instead of rolling back the whole import.+ const parentIntents: Array<{+ locationId: string;+ childKey: string;+ parentName: string;+ rowIndex: number;+ }> = [];++ await db.transaction().execute(async (trx) => {+ const inserts: Database["public"]["Tables"]["storageUnit"]["Insert"][] =+ [];+ const csvIdsForInserts: string[] = [];+ const updates: {+ id: string;+ data: Database["public"]["Tables"]["storageUnit"]["Update"];+ }[] = [];+ const csvIdsForNameMatchedUpdates: Array<{+ entityId: string;+ externalId: string;+ }> = [];++ // Resolve storage type names to ids, creating any that don't exist.+ const resolveTypeIds = async (names: string[]): Promise<string[]> => {+ const ids: string[] = [];+ for (const name of names) {+ const key = name.toLowerCase();+ let id = storageTypeByName.get(key);+ if (!id) {+ const created = await trx+ .insertInto("storageType")+ .values({+ id: nanoid(),+ name,+ companyId,+ createdBy: userId,+ createdAt: datetime.timestamp()+ } as never)+ .returning(["id"])+ .execute();+ id = created[0]?.id ?? undefined;+ if (id) storageTypeByName.set(key, id);+ }+ if (id && !ids.includes(id)) ids.push(id);+ }+ return ids;+ };++ for (const [rowIndex, record] of acceptedRows) {+ const id = record.id ?? "";+ const name = (record.name ?? "").trim();+ const locationId = (record.locationId ?? "").trim();+ const parentName = (record.parentName ?? "").trim();++ if (name === "" || locationId === "") {+ summary.errors.push({+ row: rowIndex,+ reason:+ name === ""+ ? "Missing required Name"+ : "Missing required Location"+ });+ continue;+ }+ if (id && seenCsvIds.has(id)) {+ summary.skipped.push({+ row: rowIndex,+ reason: `Duplicate ID "${id}" in file`+ });+ continue;+ }+ const key = naturalKey(locationId, name);+ if (seenNaturalKeys.has(key)) {+ summary.skipped.push({+ row: rowIndex,+ reason: `Duplicate storage unit "${name}" for this location in file`+ });+ continue;+ }+ // Resolve the row to an existing unit. A csv-id match is honored only+ // when it is in the SAME location the row states — a storage unit's+ // location is immutable via import. Updates never touch locationId, so+ // a cross-location id match would otherwise silently rename the unit in+ // its old location (ignoring the CSV Location) or crash the whole+ // import on storageUnit_name_locationId_key.+ const matchedByCsvId = id ? externalIdMap.get(id) : undefined;+ const csvIdLocation =+ matchedByCsvId !== undefined+ ? entityLocation.get(matchedByCsvId)+ : undefined;+ if (+ matchedByCsvId !== undefined &&+ csvIdLocation !== undefined &&+ csvIdLocation !== locationId+ ) {+ summary.errors.push({+ row: rowIndex,+ reason: `Unique ID "${id}" already belongs to a storage unit in a different location; import cannot move a storage unit between locations`+ });+ continue;+ }+ const matchedByName =+ matchedByCsvId === undefined ? naturalKeyMap.get(key) : undefined;+ // An id-matched update renames the unit to `name`. If a DIFFERENT unit+ // in this location already owns that name, the rename would violate+ // storageUnit_name_locationId_key — report it instead of crashing.+ if (matchedByCsvId !== undefined) {+ const nameOwner = naturalKeyMap.get(key);+ if (nameOwner !== undefined && nameOwner !== matchedByCsvId) {+ summary.errors.push({+ row: rowIndex,+ reason: `A different storage unit named "${name}" already exists in this location`+ });+ continue;+ }+ }+ const existingEntityId = matchedByCsvId ?? matchedByName;++ // Row is valid — claim its dedup slots now (after the guards, so a+ // rejected row never blocks a later legitimate row with the same+ // name/id from being processed).+ seenNaturalKeys.add(key);+ if (id) seenCsvIds.add(id);++ const storageTypeIds = await resolveTypeIds(+ parseTypeNames(record.storageTypeNames)+ );+ const active = parseActive(record.active);++ if (parentName) {+ parentIntents.push({+ locationId,+ childKey: key,+ parentName,+ rowIndex+ });+ }++ if (existingEntityId !== undefined) {+ // Deliberately does not touch locationId (the match/natural key)+ // to avoid the "cannot move a unit with children" interceptor.+ updates.push({+ id: existingEntityId,+ data: {+ name,+ storageTypeIds,+ active,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ }+ });+ if (+ matchedByCsvId === undefined &&+ id &&+ !alreadyMappedEntityIds.has(existingEntityId)+ ) {+ csvIdsForNameMatchedUpdates.push({+ entityId: existingEntityId,+ externalId: id+ });+ // Guard against two name-matched rows in the same file both+ // trying to first-map the same entity (they can't share a+ // natural key, but belt-and-braces for the unique index).+ alreadyMappedEntityIds.add(existingEntityId);+ }+ naturalKeyMap.set(key, existingEntityId);+ } else {+ const newId = nanoid();+ inserts.push({+ id: newId,+ name,+ locationId,+ storageTypeIds,+ active,+ companyId,+ createdBy: userId,+ createdAt: datetime.timestamp()+ } as never);+ csvIdsForInserts.push(id);+ naturalKeyMap.set(key, newId);+ }+ }++ importCsvTableLogger.info({+ totalRecords: mappedRecords.length,+ storageUnitInserts: inserts.length,+ storageUnitUpdates: updates.length+ });+ summary.inserted += inserts.length;+ summary.updated += updates.length;++ if (inserts.length > 0) {+ const inserted = await inChunks(inserts, (rows) =>+ trx+ .insertInto("storageUnit")+ .values(rows)+ .returning(["id"])+ .execute()+ );+ await upsertCsvMappings(+ trx,+ "storageUnit",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForInserts[i]!+ })),+ companyId,+ userId+ );+ }+ for (const update of updates) {+ await trx+ .updateTable("storageUnit")+ .set(update.data)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ if (csvIdsForNameMatchedUpdates.length > 0) {+ await upsertCsvMappings(+ trx,+ "storageUnit",+ csvIdsForNameMatchedUpdates,+ companyId,+ userId+ );+ }+ });++ // Second pass: link parents by (locationId + name) now that every unit+ // in the file exists. Individual UPDATEs (outside the insert txn) so an+ // unresolved or cyclic parent reports a row error without discarding the+ // successful imports. The DB same-location / no-cycle interceptors are+ // the final guard; their exceptions are caught per-row.+ for (const intent of parentIntents) {+ const childId = naturalKeyMap.get(intent.childKey);+ const parentId = naturalKeyMap.get(+ naturalKey(intent.locationId, intent.parentName)+ );+ if (!childId) continue;+ if (!parentId) {+ summary.errors.push({+ row: intent.rowIndex,+ reason: `Parent storage unit "${intent.parentName}" not found in the same location`+ });+ continue;+ }+ if (parentId === childId) {+ summary.errors.push({+ row: intent.rowIndex,+ reason: `Storage unit cannot be its own parent`+ });+ continue;+ }+ try {+ await db+ .updateTable("storageUnit")+ .set({+ parentId,+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", childId)+ .where("companyId", "=", companyId)+ .execute();+ } catch (parentErr) {+ summary.errors.push({+ row: intent.rowIndex,+ reason: `Could not set parent "${intent.parentName}": ${+ (parentErr as Error).message+ }`+ });+ }+ }+ break;+ }+ case "bom":+ case "operations":+ case "partWithMethod": {+ await importMethods(db, {+ table,+ mappedRecords,+ companyId,+ userId,+ summary+ });+ break;+ }+ case "unitOfMeasure":+ case "itemPostingGroup":+ case "storageType":+ case "scrapReason":+ case "department": {+ await importConfigLookups(db, {+ table,+ mappedRecords,+ companyId,+ userId,+ summary+ });+ break;+ }+ case "materialSubstance":+ case "materialForm":+ case "materialFinish":+ case "materialGrade":+ case "materialType":+ case "materialDimension": {+ await importMaterialProperties(db, {+ table,+ mappedRecords,+ companyId,+ userId,+ summary+ });+ break;+ }+ case "inventoryQuantity":+ case "batchQuantity":+ case "serialQuantity": {+ await importStockQuantities(db, client, {+ table,+ mappedRecords,+ companyId,+ userId,+ summary+ });+ break;+ }+ default: {+ throw new Error(`Invalid table: ${table}`);+ }+ }++ // Attach each failed/skipped row's original CSV cells (keyed by the user's+ // headers) so the results UI renders the exact rows the server parsed — no+ // dependence on a second, client-side parse. `row` is the 0-based index into+ // parsedCsv for both the standard and method importers.+ const withValues = (issues: Array<{ row: number; reason: string }>) =>+ issues.map((issue) => ({ ...issue, values: parsedCsv[issue.row] ?? {} }));++ return {+ success: true,+ inserted: summary.inserted,+ updated: summary.updated,+ errors: withValues(summary.errors),+ skipped: withValues(summary.skipped)+ };+ }++ function capitalize(str: string) {+ return str.charAt(0).toUpperCase() + str.slice(1);+ }+ const convertDocumentLogger = getLogger("server-functions", "convert");++ export const convertInput = z.discriminatedUnion("type", [+ z.object({+ type: z.literal("methodVersionToActive"),+ id: z.string()+ }),+ z.object({+ type: z.literal("purchaseOrderToPurchaseInvoice"),+ id: z.string()+ }),+ z.object({+ type: z.literal("quoteToSalesOrder"),+ id: z.string(),+ purchaseOrderNumber: z.string().optional(),+ // Only `quantity` is trusted (it selects a quantity break). Every financial+ // field is derived server-side from quoteLinePrice in the handler; the money+ // fields below are accepted-but-ignored for backward compatibility with+ // existing clients that still send them.+ selectedLines: z.record(+ z.string(),+ z.object({+ quantity: z.number().min(0),+ netUnitPrice: z.number().optional(),+ convertedNetUnitPrice: z.number().optional(),+ addOn: z.number().optional(),+ convertedAddOn: z.number().optional(),+ taxableAddOn: z.number().optional(),+ convertedTaxableAddOn: z.number().optional(),+ shippingCost: z.number().optional(),+ convertedShippingCost: z.number().optional(),+ leadTime: z.number().optional()+ })+ ),+ digitalQuoteAcceptedBy: z.string().optional(),+ digitalQuoteAcceptedByEmail: z.string().optional()+ }),++ z.object({+ type: z.literal("salesOrderToSalesInvoice"),+ id: z.string()+ }),+ z.object({+ type: z.literal("salesRfqToQuote"),+ id: z.string()+ }),+ z.object({+ type: z.literal("shipmentToSalesInvoice"),+ id: z.string()+ }),+ z.object({+ type: z.literal("supplierQuoteToPurchaseOrder"),+ id: z.string(),+ selectedLines: z.record(+ z.string(),+ z.object({+ leadTime: z.number(),+ quantity: z.number(),+ shippingCost: z.number(),+ supplierShippingCost: z.number(),+ supplierUnitPrice: z.number(),+ supplierTaxAmount: z.number(),+ // Mirrors selectedLineSchema in purchasing.models.ts — a 0..1 fraction.+ // Left optional so existing clients keep working; resolveTaxPercent+ // derives it from the amount rather than storing 0 beside a real one.+ taxPercent: z.number().min(0).max(1).optional().default(0),+ unitPrice: z.number()+ })+ )+ }),+ z.object({+ type: z.literal("warehouseTransferToShipment"),+ id: z.string()+ }),+ z.object({+ type: z.literal("warehouseTransferToReceipt"),+ id: z.string()+ })+ ]);++ /**+ * taxPercent and the tax amount are one value pair — a write that sets one sets+ * both. The payload's rate is optional for client compatibility, so when a+ * client sends a real amount without a rate, derive the rate once from the+ * canonical denominator (unit price x quantity + shipping) instead of storing 0+ * next to it, which the form would then treat as "no tax" and zero out.+ */+ function resolveTaxPercent(line: {+ taxPercent?: number;+ supplierTaxAmount: number;+ supplierUnitPrice: number;+ quantity: number;+ supplierShippingCost: number;+ }): number {+ if (line.taxPercent) return line.taxPercent;+ if (!line.supplierTaxAmount) return 0;+ return deriveRate(+ line.supplierTaxAmount,+ line.supplierUnitPrice * line.quantity + line.supplierShippingCost+ );+ }++ /**+ * Where an order's goods go, for the invoice's customer ship-to: a drop+ * shipment's own location, else the order header's ship-to. The same rule as+ * `resolveSalesOrderShipTo` (sales rules) — never the bill-to.+ */+ function orderShipToCustomerLocationId(+ order: { customerLocationId: string | null },+ orderShipment: { dropShipment: boolean; customerLocationId: string | null }+ ): string | null {+ return orderShipment.dropShipment+ ? orderShipment.customerLocationId+ : order.customerLocationId;+ }++ /** `id` for the three document-to-invoice conversions, `convertedId` for the rest. */+ export type ConvertResult = { id?: string; convertedId?: string };++ export const convertDocumentPermission = {+ by: "type",+ rules: {+ methodVersionToActive: { update: "resources" },+ purchaseOrderToPurchaseInvoice: { update: "invoicing" },+ quoteToSalesOrder: { update: "sales" },+ salesOrderToSalesInvoice: { update: "invoicing" },+ salesRfqToQuote: { update: "sales" },+ shipmentToSalesInvoice: { update: "invoicing" },+ supplierQuoteToPurchaseOrder: { update: "purchasing" },+ warehouseTransferToShipment: { update: "inventory" },+ warehouseTransferToReceipt: { update: "inventory" }+ }+ } satisfies PermissionRule<z.output<typeof convertInput>>;++ /** Converts one document into the next (quote → order, order → invoice, …). */+ export async function convertDocument(+ ctx: ServiceContext,+ raw: z.input<typeof convertInput>+ ) {+ const payload = convertInput.parse(raw);++ const { type, id } = payload;+ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ let convertedId = "";++ convertDocumentLogger.info("convert", { type, id, companyId, userId });++ const client = ctx.asSystem.supabase;++ switch (payload.type) {+ case "methodVersionToActive": {+ const makeMethodId = id;+ const makeMethod = await maybeSingle(db, "makeMethod", {+ id: makeMethodId,+ companyId+ });+ if (makeMethod.error) throw new Error(makeMethod.error.message);+ if (!makeMethod.data) throw new NotFoundError("Make method not found");++ const [relatedMakeMethods, draftQuotes, draftJobs] = await inOrder([+ () =>+ many(db, "makeMethod", {+ itemId: makeMethod.data?.itemId,+ companyId+ }),+ () => many(db, "quote", { companyId, status: "Draft" }),+ () => many(db, "job", { companyId, status: "Draft" })+ ]);++ if (relatedMakeMethods.error)+ throw new Error(relatedMakeMethods.error.message);++ if (draftQuotes.error) throw new Error(draftQuotes.error.message);+ if (draftJobs.error) throw new Error(draftJobs.error.message);++ const draftMakeMethodIds = relatedMakeMethods.data+ ?.filter(+ (makeMethod) =>+ makeMethod.id !== makeMethodId && makeMethod.status === "Draft"+ )+ ?.map((makeMethod) => makeMethod.id);++ const activeMakeMethodIds = relatedMakeMethods.data+ ?.filter(+ (makeMethod) =>+ makeMethod.id !== makeMethodId && makeMethod.status === "Active"+ )+ ?.map((makeMethod) => makeMethod.id);++ const relatedMakeMethodIds = [+ ...(draftMakeMethodIds ?? []),+ ...(activeMakeMethodIds ?? [])+ ];++ const [methodMaterials] = await inOrder([+ () =>+ many(db, "methodMaterial", {+ materialMakeMethodId: relatedMakeMethodIds,+ companyId+ })+ ]);++ if (methodMaterials.error) throw new Error(methodMaterials.error.message);++ await db.transaction().execute(async (trx) => {+ if (activeMakeMethodIds.length > 0) {+ await trx+ .updateTable("makeMethod")+ .set({ status: "Archived" })+ .where("id", "in", activeMakeMethodIds)+ .where("companyId", "=", companyId)+ .execute();+ }++ await trx+ .updateTable("makeMethod")+ .set({ status: "Active" })+ .where("id", "=", makeMethodId)+ .where("companyId", "=", companyId)+ .execute();++ if (relatedMakeMethodIds.length > 0) {+ await trx+ .updateTable("methodMaterial")+ .set({ materialMakeMethodId: makeMethodId })+ .where("materialMakeMethodId", "in", relatedMakeMethodIds)+ .where("companyId", "=", companyId)+ .execute();+ }+ });++ break;+ }+ case "purchaseOrderToPurchaseInvoice": {+ const purchaseOrderId = id;+ const [+ purchaseOrder,+ purchaseOrderLines,+ purchaseOrderPayment,+ purchaseOrderDelivery+ ] = await inOrder([+ () =>+ maybeSingle(db, "purchaseOrder", {+ id: purchaseOrderId,+ companyId+ }),+ () => many(db, "purchaseOrderLine", { purchaseOrderId, companyId }),+ () =>+ maybeSingle(db, "purchaseOrderPayment", {+ id: purchaseOrderId,+ companyId+ }),+ () =>+ maybeSingle(db, "purchaseOrderDelivery", {+ id: purchaseOrderId,+ companyId+ })+ ]);++ if (!purchaseOrder.data)+ throw new NotFoundError("Purchase order not found");+ if (purchaseOrderLines.error)+ throw new Error(purchaseOrderLines.error.message);+ if (!purchaseOrderPayment.data)+ throw new NotFoundError("Purchase order payment not found");+ if (!purchaseOrderDelivery.data)+ throw new NotFoundError("Purchase order delivery not found");++ // Short-closed lines ("Stop Receiving") only bill what was received,+ // so quantities go through getRemainingQuantityToInvoice rather than+ // the generated quantityToInvoice column (ordered - invoiced).+ const uninvoicedLines = purchaseOrderLines?.data?.reduce<+ (typeof purchaseOrderLines)["data"]+ >((acc, line) => {+ if (+ line &&+ !line.invoicedComplete &&+ getRemainingQuantityToInvoice(line) > 0+ ) {+ acc.push(line);+ }++ return acc;+ }, []);++ if (!uninvoicedLines || uninvoicedLines.length === 0) {+ throw new Error(+ "No lines available to invoice. All lines may already be marked as invoiced complete."+ );+ }++ const uninvoicedSubtotal = uninvoicedLines.reduce((acc, line) => {+ if (line?.unitPrice) {+ acc += getRemainingQuantityToInvoice(line) * line.unitPrice;+ }++ return acc;+ }, 0);++ // Flat header/line amounts (shipping, tax) must not be duplicated+ // when a PO is invoiced in multiple partial invoices: the header+ // shipping goes on the first (non-voided) invoice only, and flat+ // line amounts are prorated by the fraction being invoiced.+ // Untyped client: this embedded select exceeds TypeScript's+ // instantiation depth, and only the row count is read.+ const priorInvoiceLines = await (client as unknown as SupabaseClient)+ .from("purchaseInvoiceLine")+ .select("id, purchaseInvoice!inner(status)")+ .eq("purchaseOrderId", purchaseOrderId)+ .eq("companyId", companyId)+ .neq("purchaseInvoice.status", "Voided")+ .limit(1);+ const hasPriorInvoice = (priorInvoiceLines.data?.length ?? 0) > 0;++ const uninvoicedFraction = (line: {+ purchaseQuantity: number | null;+ quantityReceived: number | null;+ quantityInvoiced: number | null;+ receivedComplete: boolean | null;+ }) => {+ const ordered = line.purchaseQuantity ?? 0;+ if (ordered <= 0) return 1;+ return Math.min(getRemainingQuantityToInvoice(line) / ordered, 1);+ };++ let purchaseInvoiceId = "";++ await db.transaction().execute(async (trx) => {+ purchaseInvoiceId = await getNextSequence(+ trx,+ "purchaseInvoice",+ companyId+ );++ const purchaseInvoice = await trx+ .insertInto("purchaseInvoice")+ .values({+ invoiceId: purchaseInvoiceId!,+ status: "Draft",+ supplierId: purchaseOrder.data!.supplierId,+ supplierReference: purchaseOrder.data!.supplierReference ?? "",+ invoiceSupplierId: purchaseOrderPayment.data!.invoiceSupplierId,+ invoiceSupplierContactId:+ purchaseOrderPayment.data!.invoiceSupplierContactId,+ invoiceSupplierLocationId:+ purchaseOrderPayment.data!.invoiceSupplierLocationId,+ locationId: purchaseOrderDelivery.data!.locationId,+ paymentTermId: purchaseOrderPayment.data!.paymentTermId,+ currencyCode: purchaseOrder.data!.currencyCode ?? "USD",+ dateIssued: datetime+ .today(await resolveCompanyTimeZone(trx, companyId))+ .toString(),+ exchangeRate: purchaseOrder.data!.exchangeRate ?? 1,+ subtotal: uninvoicedSubtotal ?? 0,+ supplierInteractionId: purchaseOrder.data!.supplierInteractionId,+ totalDiscount: 0,+ totalAmount: uninvoicedSubtotal ?? 0,+ totalTax: 0,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!purchaseInvoice.id)+ throw new Error("Purchase invoice not created");+ purchaseInvoiceId = purchaseInvoice.id;++ await trx+ .insertInto("purchaseInvoiceDelivery")+ .values({+ id: purchaseInvoiceId,+ locationId: purchaseOrderDelivery.data!.locationId,+ supplierShippingCost: hasPriorInvoice+ ? 0+ : (purchaseOrderDelivery.data!.supplierShippingCost ?? 0),+ shippingMethodId: purchaseOrderDelivery.data!.shippingMethodId,+ shippingTermId: purchaseOrderDelivery.data!.shippingTermId,+ incoterm: purchaseOrderDelivery.data!.incoterm,+ incotermLocation: purchaseOrderDelivery.data!.incotermLocation,+ companyId,+ updatedBy: userId+ })+ .execute();++ const purchaseInvoiceLines: Database["public"]["Tables"]["purchaseInvoiceLine"]["Insert"][] =+ uninvoicedLines.map((line) => ({+ invoiceId: purchaseInvoiceId,+ invoiceLineType: line.purchaseOrderLineType,+ purchaseOrderId: line.purchaseOrderId,+ purchaseOrderLineId: line.id,+ itemId: line.itemId,+ locationId: line.locationId,+ storageUnitId: line.storageUnitId,+ accountId: line.accountId,+ costCenterId: line.costCenterId,+ assetId: line.assetId,+ description: line.description,+ quantity: getRemainingQuantityToInvoice(line),+ supplierUnitPrice: line.supplierUnitPrice ?? 0,+ supplierShippingCost:+ (line.supplierShippingCost ?? 0) * uninvoicedFraction(line),+ supplierTaxAmount:+ (line.supplierTaxAmount ?? 0) * uninvoicedFraction(line),+ // The rate is invariant under proration; only the amount scales+ taxPercent: line.taxPercent ?? 0,+ purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,+ conversionFactor: line.conversionFactor,+ exchangeRate: line.exchangeRate ?? 1,+ jobOperationId: line.jobOperationId,+ sortOrder: line.sortOrder ?? 1,+ companyId,+ createdBy: userId+ }));++ await trx+ .insertInto("purchaseInvoiceLine")+ .values(purchaseInvoiceLines)+ .execute();+ });++ return { id: purchaseInvoiceId };+ }+ case "quoteToSalesOrder": {+ const {+ selectedLines,+ purchaseOrderNumber,+ digitalQuoteAcceptedBy,+ digitalQuoteAcceptedByEmail+ } = payload;+ const [+ quote,+ quoteLines,+ quoteLinePrices,+ quotePayment,+ quoteShipping,+ company+ ] = await inOrder([+ () => single(db, "quote", { id, companyId }),+ // Read in full: the direct connection has no row cap to page around.+ () => many(db, "quoteLine", { quoteId: id, companyId }),+ () => many(db, "quoteLinePrice", { quoteId: id, companyId }),+ () => single(db, "quotePayment", { id, companyId }),+ () => single(db, "quoteShipment", { id, companyId }),+ () => single(db, "company", { id: companyId })+ ]);++ if (quote.error) throw new NotFoundError(`Quote with id ${id} not found`);+ if (quoteLines.error || !quoteLines.data)+ throw new NotFoundError(`Quote Lines with id ${id} not found`);+ if (quoteLinePrices.error || !quoteLinePrices.data)+ throw new NotFoundError(`Quote line prices with id ${id} not found`);+ const quoteLineRows = quoteLines.data;+ if (quotePayment.error)+ throw new NotFoundError(`Quote payment with id ${id} not found`);+ if (quoteShipping.error)+ throw new NotFoundError(`Quote shipping with id ${id} not found`);++ // SECURITY: every financial field on the resulting sales order line is+ // derived here from the canonical quoteLinePrice rows, keyed by+ // (quoteLineId, quantity). The digital-quote accept endpoint is+ // unauthenticated, so the client `selectedLines` payload is trusted only+ // as a selection of quantity break — never as a source of prices. Do not+ // read money fields (netUnitPrice, shippingCost, addOn, …) from it.+ const canonicalPriceByLineQty = new Map<+ string,+ NonNullable<typeof quoteLinePrices.data>[number]+ >();+ for (const price of quoteLinePrices.data ?? []) {+ canonicalPriceByLineQty.set(+ `${price.quoteLineId}:${price.quantity}`,+ price+ );+ }++ const computeAddOns = (+ additionalCharges: unknown,+ quantity: number+ ): { addOn: number; taxableAddOn: number } => {+ const charges =+ (additionalCharges as Record<+ string,+ { amounts?: Record<string, number>; taxable?: boolean }+ > | null) ?? {};+ let addOn = 0;+ let taxableAddOn = 0;+ for (const charge of Object.values(charges)) {+ const amount = Number(charge?.amounts?.[quantity] ?? 0) || 0;+ addOn += amount;+ if (charge?.taxable !== false) taxableAddOn += amount;+ }+ return { addOn, taxableAddOn };+ };++ let insertedSalesOrderId = "";+ await db.transaction().execute(async (trx) => {+ const todayDate = datetime.today(+ await resolveCompanyTimeZone(trx, companyId)+ );+ const today = todayDate.toString();+ const salesOrderId = await getNextSequence(+ trx,+ "salesOrder",+ companyId+ );++ // Check if any selected lines have quantity 0+ const hasZeroQuantityLines = quoteLineRows.some(+ (line) =>+ line.id &&+ selectedLines &&+ line.id in selectedLines &&+ selectedLines[line.id]!.quantity === 0+ );++ // Only the selected lines become sales order lines below. A No Quote+ // line is never offered to the customer, so it never converts —+ // whatever the (unauthenticated) selection payload says.+ const selectedQuoteLines = quoteLineRows.filter(+ (line) =>+ line.id &&+ line.status !== "No Quote" &&+ selectedLines &&+ line.id in selectedLines &&+ selectedLines[line.id]!.quantity > 0+ );++ // Never create an empty order: the share page gates Accept, but this+ // payload comes from an unauthenticated endpoint.+ if (selectedQuoteLines.length === 0) {+ throw new Error("No quote lines selected to convert");+ }++ // Services are never shipped — a service-only order goes straight to+ // "To Invoice" so it isn't stuck waiting on a shipment that can't happen.+ const hasShippableLine = selectedQuoteLines.some(+ (line) => line.itemType !== "Service"+ );+ const salesOrderStatus = hasShippableLine+ ? "To Ship and Invoice"+ : "To Invoice";++ // An order always has a location. A quote can reach here without+ // one (Paperless Parts imports never set it), so fall back to the+ // quote's shipment location, then the company's first location.+ const locationId =+ quote.data.locationId ??+ quoteShipping.data.locationId ??+ (+ await trx+ .selectFrom("location")+ .select("id")+ .where("companyId", "=", companyId)+ .orderBy("createdAt")+ .orderBy("id")+ .executeTakeFirst()+ )?.id;+ if (!locationId) {+ throw new Error("The company has no location for the sales order");+ }++ const salesOrder = await trx+ .insertInto("salesOrder")+ .values([+ {+ salesOrderId,+ revisionId: 0,+ orderDate: today,+ customerId: quote.data.customerId,+ customerContactId: quote.data.customerContactId,+ customerEngineeringContactId:+ quote.data.customerEngineeringContactId,+ customerLocationId: quote.data.customerLocationId,+ customerReference: purchaseOrderNumber ?? "",+ locationId,+ salesPersonId: quote.data.salesPersonId ?? userId,+ status: salesOrderStatus,+ createdBy: userId,+ companyId: companyId,+ currencyCode:+ quote.data.currencyCode ??+ company.data?.baseCurrencyCode ??+ "USD",+ externalNotes: toJson(quote.data.externalNotes),+ internalNotes: toJson(quote.data.internalNotes),+ exchangeRate: quote.data.exchangeRate ?? 1,+ exchangeRateUpdatedAt:+ quote.data.exchangeRateUpdatedAt ?? datetime.timestamp(),+ opportunityId: quote.data.opportunityId+ }+ ])+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!salesOrder.id) {+ throw new Error("sales order is not created");+ }+ insertedSalesOrderId = salesOrder.id;++ // Copy quotePayment data to salesOrderPayment+ await trx+ .insertInto("salesOrderPayment")+ .values({+ ...quotePayment.data,+ id: insertedSalesOrderId+ })+ .execute();++ // One read for every picked line's default bin, keyed by item and location.+ const pickedLines = selectedQuoteLines.flatMap((line) => {+ return line.id && line.itemId && line.methodType !== "Make to Order"+ ? [+ {+ id: line.id,+ itemId: line.itemId,+ locationId: line.locationId ?? locationId+ }+ ]+ : [];+ });+ const pickMethods = pickedLines.length+ ? await trx+ .selectFrom("pickMethod")+ .where(+ "itemId",+ "in",+ pickedLines.map((line) => line.itemId)+ )+ .where(+ "locationId",+ "in",+ pickedLines.map((line) => line.locationId)+ )+ .where("companyId", "=", companyId)+ .select(["itemId", "locationId", "defaultStorageUnitId"])+ .execute()+ : [];+ const defaultBinByItemLocation = new Map(+ pickMethods.map((pm) => [+ `${pm.itemId}:${pm.locationId}`,+ pm.defaultStorageUnitId+ ])+ );+ const pickMethodDefaultsByLineId = new Map(+ pickedLines.map((line) => [+ line.id,+ defaultBinByItemLocation.get(`${line.itemId}:${line.locationId}`) ??+ null+ ])+ );++ const salesOrderLineInserts: Database["public"]["Tables"]["salesOrderLine"]["Insert"][] =+ selectedQuoteLines.map((line) => {+ const selectedQuantity = selectedLines![line.id!]!.quantity;+ const price = canonicalPriceByLineQty.get(+ `${line.id}:${selectedQuantity}`+ );+ if (!price) {+ throw new Error(+ `No quote price found for line ${line.id} at quantity ${selectedQuantity}`+ );+ }+ const { addOn, taxableAddOn } = computeAddOns(+ line.additionalCharges,+ price.quantity+ );+ return {+ id: line.id,+ salesOrderId: insertedSalesOrderId,+ salesOrderLineType: line.itemType as "Part",+ addOnCost: taxableAddOn,+ nonTaxableAddOnCost: addOn - taxableAddOn,+ description: line.description,+ itemId: line.itemId,+ locationId: line.locationId ?? locationId,+ methodType: line.methodType,+ storageUnitId: pickMethodDefaultsByLineId.get(line.id!) ?? null,+ internalNotes: toJson(line.internalNotes),+ externalNotes: toJson(line.externalNotes),+ saleQuantity: price.quantity,+ status: "Ordered",+ unitOfMeasureCode: line.unitOfMeasureCode,+ unitPrice: price.netUnitPrice ?? 0,+ // How the quoted price was reached, carried onto the order.+ priceTrace: toJson(+ quoteToOrderPriceTrace(+ price.priceTrace,+ price.unitPrice ?? 0,+ price.netUnitPrice ?? 0,+ price.discountPercent ?? 0+ )+ ),+ promisedDate: todayDate+ .add({ days: price.leadTime ?? 0 })+ .toString(),+ createdBy: userId,+ companyId,+ exchangeRate: quote.data.exchangeRate ?? 1,+ taxPercent: line.taxPercent,+ shippingCost: price.shippingCost ?? 0,+ sortOrder: line.sortOrder ?? 1,+ configuration: toJson(line.configuration)+ };+ });++ // The order is promised when its last line is: the latest line+ // promise (today + that line's quoted lead time). A requested date+ // the quote already carries is the customer's and is kept.+ const receiptPromisedDate =+ salesOrderLineInserts+ .map((insert) => insert.promisedDate)+ .filter((date): date is string => !!date)+ .sort()+ .at(-1) ?? null;++ // Copy quoteShipment data to salesOrderShipment+ await trx+ .insertInto("salesOrderShipment")+ .values({+ ...quoteShipping.data,+ id: insertedSalesOrderId,+ locationId: quoteShipping.data.locationId ?? locationId,+ receiptRequestedDate:+ quoteShipping.data.receiptRequestedDate ?? receiptPromisedDate,+ receiptPromisedDate+ })+ .execute();++ if (salesOrderLineInserts.length > 0) {+ await trx+ .insertInto("salesOrderLine")+ .values(salesOrderLineInserts)+ .execute();++ await trx+ .updateTable("item")+ .set({ active: true })+ .where(+ "id",+ "in",+ salesOrderLineInserts.map((insert) => insert.itemId as string)+ )+ .where("companyId", "=", companyId)+ .execute();+ }++ const newQuoteStatus: "Ordered" | "Partial" = hasZeroQuantityLines+ ? "Partial"+ : "Ordered";+ // Atomic guard: only convert a quote that is still "Sent". Both the+ // internal "convert to order" flow and the unauthenticated digital+ // quote accept run from "Sent" only. If a concurrent or replayed+ // request already converted it, 0 rows update here and the throw rolls+ // the whole transaction back — no duplicate sales order is committed.+ const quoteStatusUpdate = await trx+ .updateTable("quote")+ .set({+ status: newQuoteStatus,+ digitalQuoteAcceptedBy: digitalQuoteAcceptedBy ?? null,+ digitalQuoteAcceptedByEmail: digitalQuoteAcceptedByEmail ?? null+ })+ .where("id", "=", quote.data.id)+ .where("status", "=", "Sent")+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ if (Number(quoteStatusUpdate.numUpdatedRows ?? 0) === 0) {+ throw new Error(+ `Quote ${quote.data.id} is no longer in a convertible state`+ );+ }++ const customerPartSeen = new Set<string>();+ const customerPartToItemInserts = quoteLineRows+ .map((line) => ({+ companyId,+ customerId: quote.data?.customerId!,+ customerPartId: line.customerPartId!,+ customerPartRevision: line.customerPartRevision ?? "",+ itemId: line.itemId!+ }))+ .filter((line) => {+ if (!line.itemId || !line.customerPartId) return false;+ const key = `${line.customerId}-${line.itemId}`;+ if (customerPartSeen.has(key)) return false;+ customerPartSeen.add(key);+ return true;+ });+ if (customerPartToItemInserts.length > 0) {+ await trx+ .insertInto("customerPartToItem")+ .values(customerPartToItemInserts)+ .onConflict((oc) =>+ oc.columns(["customerId", "itemId"]).doUpdateSet((eb) => ({+ customerPartId: eb.ref("excluded.customerPartId"),+ customerPartRevision: eb.ref("excluded.customerPartRevision")+ }))+ )+ .execute();+ }++ const updatedItemModels = quoteLineRows+ .filter((line) => !!line.modelUploadId && !!line.itemId)+ .map((line) => ({+ id: line.itemId!,+ modelUploadId: line.modelUploadId!+ }));++ if (updatedItemModels.length > 0) {+ for await (const update of updatedItemModels) {+ await trx+ .updateTable("item")+ .set(update)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ });++ if (!insertedSalesOrderId) {+ throw new Error("Failed to insert sales order");+ }++ convertedId = insertedSalesOrderId;+ break;+ }+ case "salesOrderToSalesInvoice": {+ const salesOrderId = id;+ const [+ salesOrder,+ salesOrderLines,+ salesOrderPayment,+ salesOrderShipment+ ] = await inOrder([+ () => maybeSingle(db, "salesOrder", { id: salesOrderId, companyId }),+ () => many(db, "salesOrderLine", { salesOrderId, companyId }),+ () =>+ maybeSingle(db, "salesOrderPayment", {+ id: salesOrderId,+ companyId+ }),+ () =>+ maybeSingle(db, "salesOrderShipment", {+ id: salesOrderId,+ companyId+ })+ ]);++ if (salesOrder.error) throw new Error(salesOrder.error.message);+ if (!salesOrder.data) throw new NotFoundError("Sales order not found");+ const order = salesOrder.data;+ if (salesOrderLines.error) throw new Error(salesOrderLines.error.message);+ if (salesOrderPayment.error)+ throw new Error(salesOrderPayment.error.message);+ if (!salesOrderPayment.data)+ throw new NotFoundError("Sales order payment details not found");+ if (salesOrderShipment.error)+ throw new Error(salesOrderShipment.error.message);+ if (!salesOrderShipment.data)+ throw new NotFoundError("Sales order delivery details not found");+ const orderShipment = salesOrderShipment.data;++ // Lines a contract bills are marked invoicedComplete when the+ // contract is created; the lines inserted below skip them, so the+ // subtotal must too.+ const uninvoicedLines = salesOrderLines?.data?.reduce<+ (typeof salesOrderLines)["data"]+ >((acc, line) => {+ if (+ line?.quantityToInvoice &&+ line.quantityToInvoice > 0 &&+ !line.invoicedComplete+ ) {+ acc.push(line);+ }++ return acc;+ }, []);++ const uninvoicedSubtotal = uninvoicedLines?.reduce((acc, line) => {+ if (+ line?.quantityToInvoice &&+ line.unitPrice &&+ line.quantityToInvoice > 0+ ) {+ acc += line.quantityToInvoice * line.unitPrice;+ }++ return acc;+ }, 0);++ let salesInvoiceId = "";++ await db.transaction().execute(async (trx) => {+ salesInvoiceId = await getNextSequence(trx, "salesInvoice", companyId);++ const salesInvoice = await trx+ .insertInto("salesInvoice")+ .values({+ invoiceId: salesInvoiceId!,+ status: "Draft",+ customerId: order.customerId,+ customerReference: order.customerReference ?? "",+ invoiceCustomerId: salesOrderPayment.data!.invoiceCustomerId,+ invoiceCustomerContactId:+ salesOrderPayment.data!.invoiceCustomerContactId,+ invoiceCustomerLocationId:+ salesOrderPayment.data!.invoiceCustomerLocationId,+ locationId: orderShipment.locationId,+ paymentTermId: salesOrderPayment.data!.paymentTermId,+ currencyCode: order.currencyCode ?? "USD",+ dateIssued: datetime+ .today(await resolveCompanyTimeZone(trx, companyId))+ .toString(),+ exchangeRate: order.exchangeRate ?? 1,+ subtotal: uninvoicedSubtotal ?? 0,+ opportunityId: order.opportunityId,+ totalDiscount: 0,+ totalAmount: uninvoicedSubtotal ?? 0,+ totalTax: 0,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!salesInvoice.id) throw new Error("Sales invoice not created");+ salesInvoiceId = salesInvoice.id;++ await trx+ .insertInto("salesInvoiceShipment")+ .values({+ id: salesInvoiceId,+ locationId: orderShipment.locationId,+ customerLocationId: orderShipToCustomerLocationId(+ order,+ orderShipment+ ),+ shippingCost: orderShipment.shippingCost ?? 0,+ shippingMethodId: orderShipment.shippingMethodId,+ shippingTermId: orderShipment.shippingTermId,+ incoterm: orderShipment.incoterm,+ incotermLocation: orderShipment.incotermLocation,+ companyId,+ createdBy: userId+ })+ .execute();++ const salesInvoiceLines = uninvoicedLines?.reduce<+ Database["public"]["Tables"]["salesInvoiceLine"]["Insert"][]+ >((acc, line) => {+ if (+ line?.quantityToInvoice &&+ line.quantityToInvoice > 0 &&+ !line.invoicedComplete+ ) {+ acc.push({+ invoiceId: salesInvoiceId,+ invoiceLineType: line.salesOrderLineType,+ salesOrderId: line.salesOrderId,+ salesOrderLineId: line.id,+ methodType: line.methodType,+ itemId: line.itemId,+ locationId: line.locationId,+ storageUnitId: line.storageUnitId,+ accountId: line.accountId,+ assetId: line.assetId,+ description: line.description,+ quantity: line.quantityToInvoice,+ unitPrice: line.unitPrice ?? 0,+ addOnCost: line.addOnCost ?? 0,+ nonTaxableAddOnCost: line.nonTaxableAddOnCost ?? 0,+ shippingCost: line.shippingCost ?? 0,+ taxPercent: line.taxPercent ?? 0,+ unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",+ exchangeRate: line.exchangeRate ?? 1,+ serviceStartDate: line.serviceStartDate ?? null,+ serviceEndDate: line.serviceEndDate ?? null,+ sortOrder: line.sortOrder ?? 1,+ companyId,+ createdBy: userId+ });+ }+ return acc;+ }, []);++ if (salesInvoiceLines.length > 0) {+ await trx+ .insertInto("salesInvoiceLine")+ .values(salesInvoiceLines)+ .execute();+ }+ });++ return { id: salesInvoiceId };+ }+ case "salesRfqToQuote": {+ const [salesRfq, salesRfqLines] = await inOrder([+ () => single(db, "salesRfq", { id, companyId }),+ () => many(db, "salesRfqLines", { salesRfqId: id, companyId })+ ]);++ if (salesRfq.error)+ throw new NotFoundError(`Sales RFQ with id ${id} not found`);+ if (salesRfq.data?.status !== "Ready for Quote")+ throw new Error(+ `Sales RFQ with id ${id} is not in Ready for Quote status`+ );++ if (salesRfqLines.error) {+ throw new NotFoundError(`Sales RFQ Lines with id ${id} not found`);+ }++ // Create Item records for each line that does not yet have one assigned+ const linesToCreateItems = salesRfqLines.data.filter(+ (line) => !line.itemId+ );++ const readableIdToLineIdMapping = new Map<string, string>();+ let itemInserts: Database["public"]["Tables"]["item"]["Insert"][] = [];+ if (linesToCreateItems.length > 0) {+ itemInserts = await Promise.all(+ linesToCreateItems.map(async (line) => {+ let revisionId = line.customerPartRevision ?? "0";+ let readableId = line.customerPartId ?? "";+ let suffix = 1;++ // Check for uniqueness and append a suffix if necessary+ while (true) {+ const { data, error } = await single(+ db,+ "item",+ { readableId, revision: revisionId, companyId },+ { columns: ["id"] }+ );++ if (+ // If multiple line items in the RFQ have the same customer part number and revision,+ // make sure they get assiged different readableIds+ !readableIdToLineIdMapping.has(readableId) &&+ (error || !data)+ ) {+ // readableId is unique, we can use it+ break;+ }++ // If not unique, append or increment suffix+ revisionId = `${revisionId} (${suffix})`;+ suffix++;+ }++ readableIdToLineIdMapping.set(readableId, line.id!);+ return {+ readableId,+ revision: revisionId,+ type: "Part" as const,+ active: false,+ name: line.description ?? line.itemName ?? "",+ description: "",+ itemTrackingType: "Inventory" as const,+ replenishmentSystem: "Make" as const,+ defaultMethodType: "Make to Order" as const,+ unitOfMeasureCode: "EA",+ companyId: companyId,+ createdBy: userId+ };+ })+ );+ }++ if (!salesRfq.data.customerId) {+ throw new Error(`Sales RFQ with id ${id} has no customerId`);+ }++ // Handle customer payment terms, shipping, currency codes, etc.+ const [customerPayment, customerShipping, customer, company] =+ await inOrder([+ () =>+ single(db, "customerPayment", {+ customerId: salesRfq.data.customerId,+ companyId+ }),+ () =>+ single(db, "customerShipping", {+ customerId: salesRfq.data.customerId,+ companyId+ }),+ () =>+ single(db, "customer", {+ id: salesRfq.data.customerId,+ companyId+ }),+ () => single(db, "company", { id: companyId })+ ]);++ if (customerPayment.error) throw customerPayment.error;+ if (customerShipping.error) throw customerShipping.error;+ if (customer.error) throw customer.error;+ if (company.error) throw company.error;++ const currencyCode =+ customer.data?.currencyCode ?? company.data?.baseCurrencyCode ?? "USD";+ // get_exchange_rate returns 1 for the base currency, prefers a+ // company override, falls back to the global store, and raises on a+ // missing rate -- a foreign-currency customer is never quoted at par.+ const exchangeRateResult = await rpcValue(db, "get_exchange_rate", {+ p_company_id: companyId,+ p_currency_code: currencyCode+ });+ if (exchangeRateResult.error) {+ throw new Error(exchangeRateResult.error.message);+ }+ const exchangeRate = Number(exchangeRateResult.data);++ const {+ paymentTermId,+ invoiceCustomerId,+ invoiceCustomerContactId,+ invoiceCustomerLocationId+ } = customerPayment.data;++ const { shippingMethodId, shippingTermId, incoterm, incotermLocation } =+ customerShipping.data;++ let insertedQuoteId = "";+ let insertedQuoteLines: {+ id?: string;+ itemId?: string;+ methodType?:+ | "Purchase to Order"+ | "Make to Order"+ | "Pull from Inventory";+ }[] = [];++ await db.transaction().execute(async (trx) => {+ // Create the items for any salesRfqLines that do not yet have an itemId+ if (itemInserts.length > 0) {+ const itemIds = await trx+ .insertInto("item")+ .values(itemInserts)+ .returning(["id", "readableId", "revision"])+ .execute();++ const partInserts: Database["public"]["Tables"]["part"]["Insert"][] =+ itemIds.map((item) => ({+ id: item.readableId!,+ companyId,+ createdBy: userId+ }));+ await trx+ .insertInto("part")+ .values(partInserts)+ .onConflict((oc) =>+ oc.columns(["id", "companyId"]).doUpdateSet({+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ )+ .execute();++ const salesRfqLineUpdates: Database["public"]["Tables"]["salesRfqLine"]["Update"][] =+ itemIds.map((item) => ({+ itemId: item.id!,+ id: readableIdToLineIdMapping.get(item.readableId!)!+ }));+ for await (const update of salesRfqLineUpdates) {+ await trx+ .updateTable("salesRfqLine")+ .set({ itemId: update.itemId })+ .where("id", "=", update.id!)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Create the quote+ const quoteId = await getNextSequence(trx, "quote", companyId);+ const externalLinkId = await trx+ .insertInto("externalLink")+ .values({+ documentId: quoteId,+ documentType: "Quote",+ companyId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!salesRfq.data.customerId) {+ throw new Error(`Sales RFQ with id ${id} has no customerId`);+ }++ const quote = await trx+ .insertInto("quote")+ .values([+ {+ quoteId,+ customerId: salesRfq.data?.customerId,+ customerContactId: salesRfq.data?.customerContactId,+ customerEngineeringContactId:+ salesRfq.data?.customerEngineeringContactId,+ customerLocationId: salesRfq.data?.customerLocationId,+ customerReference: salesRfq.data?.customerReference,+ locationId: salesRfq.data?.locationId,+ expirationDate: datetime+ .today(await resolveCompanyTimeZone(trx, companyId))+ .add({ days: 30 })+ .toString(),+ salesPersonId: salesRfq.data?.salesPersonId ?? userId,+ status: "Draft",+ externalNotes: toJson(salesRfq.data?.externalNotes),+ internalNotes: toJson(salesRfq.data?.internalNotes),+ companyId,+ createdBy: userId,+ currencyCode,+ exchangeRate,+ exchangeRateUpdatedAt: datetime.timestamp(),+ externalLinkId: externalLinkId.id,+ opportunityId: salesRfq.data.opportunityId+ }+ ])+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!quote.id) {+ throw new Error("Failed to insert quote");+ }++ // Insert quotePayment+ await trx+ .insertInto("quotePayment")+ .values({+ id: quote.id,+ invoiceCustomerId: invoiceCustomerId,+ invoiceCustomerContactId: invoiceCustomerContactId,+ invoiceCustomerLocationId: invoiceCustomerLocationId,+ paymentTermId: paymentTermId,+ companyId+ })+ .execute();++ // Insert quoteShipment+ await trx+ .insertInto("quoteShipment")+ .values({+ id: quote.id,+ locationId: salesRfq.data?.locationId,+ shippingMethodId: shippingMethodId,+ shippingTermId: shippingTermId,+ incoterm: incoterm,+ incotermLocation: incotermLocation,+ companyId+ })+ .execute();++ const salesRfqLinesWithItemIds = await trx+ .selectFrom("salesRfqLines")+ .selectAll()+ .where("salesRfqId", "=", id)+ .execute();++ const quoteLineInserts: Database["public"]["Tables"]["quoteLine"]["Insert"][] =+ salesRfqLinesWithItemIds.map((line) => ({+ id: line.id ?? undefined,+ quoteId: quote.id!,+ itemId: line.itemId!,+ customerPartId: line.customerPartId,+ customerPartRevision: line.customerPartRevision,+ description: line.description ?? line.itemName ?? "",+ itemType: line.itemType!,+ locationId: salesRfq.data?.locationId,+ methodType: line.methodType!,+ modelUploadId: line.modelUploadId,+ internalNotes: toJson(line.internalNotes),+ externalNotes: toJson(line.externalNotes),+ quantity: line.quantity,+ status: "Not Started",+ unitOfMeasureCode: line.unitOfMeasureCode,+ // Sales RFQ uses "order" column; map it to quoteLine.sortOrder+ sortOrder: line.order ?? 1,+ companyId,+ createdBy: userId+ }));++ if (quoteLineInserts.length > 0) {+ insertedQuoteLines = await trx+ .insertInto("quoteLine")+ .values(quoteLineInserts)+ .returning(["id", "itemId", "methodType"])+ .execute();+ }++ // update salesRfq status+ await trx+ .updateTable("salesRfq")+ .set({ status: "Ready for Quote" })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ const rfqCustomerPartSeen = new Set<string>();+ const customerPartToItemInserts = salesRfqLinesWithItemIds+ .map((line) => ({+ companyId,+ customerId: salesRfq.data?.customerId!,+ customerPartId: line.customerPartId!,+ customerPartRevision: line.customerPartRevision ?? "",+ itemId: line.itemId!+ }))+ .filter((line) => {+ if (!line.itemId || !line.customerPartId) return false;+ const key = `${line.customerId}-${line.itemId}`;+ if (rfqCustomerPartSeen.has(key)) return false;+ rfqCustomerPartSeen.add(key);+ return true;+ });+ if (customerPartToItemInserts.length > 0) {+ await trx+ .insertInto("customerPartToItem")+ .values(customerPartToItemInserts)+ .onConflict((oc) =>+ oc.columns(["customerId", "itemId"]).doUpdateSet((eb) => ({+ customerPartId: eb.ref("excluded.customerPartId"),+ customerPartRevision: eb.ref("excluded.customerPartRevision")+ }))+ )+ .execute();+ }++ await trx+ .updateTable("salesRfq")+ .set({+ status: "Quoted"+ })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ const updatedItemModels = salesRfqLinesWithItemIds+ .filter((line) => !!line.modelUploadId && !!line.itemId)+ .map((line) => ({+ id: line.itemId!,+ modelUploadId: line.modelUploadId!+ }));++ if (updatedItemModels.length > 0) {+ for await (const update of updatedItemModels) {+ await trx+ .updateTable("item")+ .set(update)+ .where("id", "=", update.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ insertedQuoteId = quote.id!;+ convertedId = insertedQuoteId;+ });++ // Copy each make line's method. Each copy holds a pooled connection+ // for its whole tree, so a few at a time rather than all at once.+ const makeLines = insertedQuoteLines.filter(+ (line) => line.methodType === "Make to Order"+ );+ const copies = await async.map(+ makeLines,+ (line) =>+ invokePosting(+ { db, companyId, userId },+ "get-method",+ {+ type: "itemToQuoteLine",+ sourceId: line.itemId!,+ targetId: `${insertedQuoteId}:${line.id}`+ },+ getMethod+ ),+ { concurrency: 2 }+ );+ // The quote stands either way; a line's method can be copied again.+ for (const [index, copy] of copies.entries()) {+ if (copy.error) {+ convertDocumentLogger.error(+ "Failed to copy the method onto a quote line",+ {+ quoteId: insertedQuoteId,+ quoteLineId: makeLines[index]?.id,+ error: copy.error+ }+ );+ }+ }+ break;+ }+ case "shipmentToSalesInvoice": {+ const shipmentId = id;+ const [shipment, shipmentLines, shipmentFixedAssetLines] = await inOrder([+ () => maybeSingle(db, "shipment", { id: shipmentId, companyId }),+ () => many(db, "shipmentLine", { shipmentId, companyId }),+ () =>+ many(db, "shipmentFixedAssetLine", {+ shipmentId,+ companyId,+ shipped: true+ })+ ]);++ if (shipment.error) throw shipment.error;+ if (!shipment.data) throw new NotFoundError("Shipment not found");+ if (shipmentLines.error) throw shipmentLines.error;+ if (shipmentFixedAssetLines.error) throw shipmentFixedAssetLines.error;++ // Accumulate quantities for each sales order line+ const quantitiesByLine = shipmentLines.data.reduce<+ Record<string, number>+ >((acc, line) => {+ const lineId = line.lineId!;+ acc[lineId] = (acc[lineId] || 0) + line.shippedQuantity;+ return acc;+ }, {});++ // Each shipped fixed asset line counts as quantity 1+ for (const line of shipmentFixedAssetLines.data) {+ const lineId = line.salesOrderLineId;+ if (!lineId) continue;+ quantitiesByLine[lineId] = (quantitiesByLine[lineId] || 0) + 1;+ }++ const salesOrderLineIds = Object.keys(quantitiesByLine);++ if (+ !shipment.data?.sourceDocumentId ||+ shipment.data?.sourceDocument !== "Sales Order"+ ) {+ throw new Error(+ "This shipment isn't linked to a sales order, so there's nothing to invoice."+ );+ }++ const [+ salesOrder,+ salesOrderLines,+ salesOrderPayment,+ salesOrderShipment+ ] = await inOrder([+ () =>+ maybeSingle(db, "salesOrder", {+ id: shipment.data?.sourceDocumentId,+ companyId+ }),+ () => many(db, "salesOrderLine", { id: salesOrderLineIds, companyId }),+ () =>+ maybeSingle(db, "salesOrderPayment", {+ id: shipment.data?.sourceDocumentId,+ companyId+ }),+ () =>+ maybeSingle(db, "salesOrderShipment", {+ id: shipment.data?.sourceDocumentId,+ companyId+ })+ ]);++ if (salesOrder.error) throw new Error(salesOrder.error.message);+ if (!salesOrder.data) throw new NotFoundError("Sales order not found");+ const order = salesOrder.data;+ if (salesOrderLines.error) throw new Error(salesOrderLines.error.message);+ if (salesOrderPayment.error)+ throw new Error(salesOrderPayment.error.message);+ if (!salesOrderPayment.data)+ throw new NotFoundError("Sales order payment details not found");+ if (salesOrderShipment.error)+ throw new Error(salesOrderShipment.error.message);+ if (!salesOrderShipment.data)+ throw new NotFoundError("Sales order delivery details not found");+ const orderShipment = salesOrderShipment.data;++ const uninvoicedLines = salesOrderLines?.data?.reduce<+ (typeof salesOrderLines)["data"]+ >((acc, line) => {+ if (line.id in quantitiesByLine) {+ const shippedInThisShipment = quantitiesByLine[line.id]!;+ const remainingToInvoice = line.quantityToInvoice ?? 0;+ const quantityToInvoice = Math.min(+ shippedInThisShipment,+ remainingToInvoice+ );++ if (quantityToInvoice > 0) {+ acc.push({+ ...line,+ quantityToInvoice+ });+ }+ }++ return acc;+ }, []);++ const uninvoicedSubtotal = uninvoicedLines?.reduce((acc, line) => {+ if (+ line?.quantityToInvoice &&+ line.unitPrice &&+ line.quantityToInvoice > 0+ ) {+ acc += line.quantityToInvoice * line.unitPrice;+ }++ return acc;+ }, 0);++ let salesInvoiceId = "";++ await db.transaction().execute(async (trx) => {+ salesInvoiceId = await getNextSequence(trx, "salesInvoice", companyId);++ const salesInvoice = await trx+ .insertInto("salesInvoice")+ .values({+ invoiceId: salesInvoiceId!,+ status: "Draft",+ customerId: order.customerId,+ customerReference: order.customerReference ?? "",+ invoiceCustomerId: salesOrderPayment.data!.invoiceCustomerId,+ invoiceCustomerContactId:+ salesOrderPayment.data!.invoiceCustomerContactId,+ invoiceCustomerLocationId:+ salesOrderPayment.data!.invoiceCustomerLocationId,+ locationId: orderShipment.locationId,+ paymentTermId: salesOrderPayment.data!.paymentTermId,+ currencyCode: order.currencyCode ?? "USD",+ dateIssued: datetime+ .today(await resolveCompanyTimeZone(trx, companyId))+ .toString(),+ exchangeRate: order.exchangeRate ?? 1,+ subtotal: uninvoicedSubtotal ?? 0,+ opportunityId: order.opportunityId,+ shipmentId: shipmentId,+ totalDiscount: 0,+ totalAmount: uninvoicedSubtotal ?? 0,+ totalTax: 0,+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!salesInvoice.id) throw new Error("Sales invoice not created");+ salesInvoiceId = salesInvoice.id;++ await trx+ .insertInto("salesInvoiceShipment")+ .values({+ id: salesInvoiceId,+ locationId: orderShipment.locationId,+ customerLocationId: orderShipToCustomerLocationId(+ order,+ orderShipment+ ),+ shippingCost: orderShipment.shippingCost ?? 0,+ shippingMethodId: orderShipment.shippingMethodId,+ shippingTermId: orderShipment.shippingTermId,+ incoterm: orderShipment.incoterm,+ incotermLocation: orderShipment.incotermLocation,+ companyId,+ createdBy: userId+ })+ .execute();++ const salesInvoiceLines = uninvoicedLines?.reduce<+ Database["public"]["Tables"]["salesInvoiceLine"]["Insert"][]+ >((acc, line) => {+ if (+ line?.quantityToInvoice &&+ line.quantityToInvoice > 0 &&+ !line.invoicedComplete+ ) {+ acc.push({+ invoiceId: salesInvoiceId,+ invoiceLineType: line.salesOrderLineType,+ salesOrderId: line.salesOrderId,+ salesOrderLineId: line.id,+ methodType: line.methodType,+ itemId: line.itemId,+ locationId: line.locationId,+ storageUnitId: line.storageUnitId,+ accountId: line.accountId,+ assetId: line.assetId,+ description: line.description,+ quantity: line.quantityToInvoice,+ unitPrice: line.unitPrice ?? 0,+ addOnCost: line.addOnCost ?? 0,+ nonTaxableAddOnCost: line.nonTaxableAddOnCost ?? 0,+ shippingCost: line.shippingCost ?? 0,+ taxPercent: line.taxPercent ?? 0,+ unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",+ exchangeRate: line.exchangeRate ?? 1,+ serviceStartDate: line.serviceStartDate ?? null,+ serviceEndDate: line.serviceEndDate ?? null,+ sortOrder: line.sortOrder ?? 1,+ companyId,+ createdBy: userId+ });+ }+ return acc;+ }, []);++ if (salesInvoiceLines.length > 0) {+ await trx+ .insertInto("salesInvoiceLine")+ .values(salesInvoiceLines)+ .execute();+ }+ });++ return { id: salesInvoiceId };+ }+ case "supplierQuoteToPurchaseOrder": {+ const { selectedLines } = payload;++ const [quote, quoteLines, company, employeeJob] = await inOrder([+ () => single(db, "supplierQuote", { id, companyId }),+ () =>+ many<+ "supplierQuoteLine",+ rows.Tables["supplierQuoteLine"]["Row"] & {+ item: Pick<rows.Tables["item"]["Row"], "type"> | null;+ }+ >(+ db,+ "supplierQuoteLine",+ { supplierQuoteId: id, companyId },+ {+ embed: {+ item: { table: "item", via: "itemId", columns: ["type"] }+ }+ }+ ),+ () => single(db, "company", { id: companyId }),+ () => single(db, "employeeJob", { id: userId, companyId })+ ]);++ if (quote.error) throw new NotFoundError(`Quote with id ${id} not found`);+ if (quoteLines.error)+ throw new NotFoundError(`Quote Lines with id ${id} not found`);++ const [supplierPayment, supplierShipping, supplier, pickMethods] =+ await inOrder([+ () =>+ single(db, "supplierPayment", {+ supplierId: quote.data.supplierId,+ companyId+ }),+ () =>+ single(db, "supplierShipping", {+ supplierId: quote.data.supplierId,+ companyId+ }),+ () =>+ single(db, "supplier", { id: quote.data.supplierId, companyId }),++ () =>+ many(db, "pickMethod", {+ itemId: quoteLines.data.map((line) => line.itemId as string),+ locationId: employeeJob.data?.locationId ?? "",+ companyId+ })+ ]);++ if (supplierPayment.error) throw supplierPayment.error;+ if (supplierShipping.error) throw supplierShipping.error;+ if (supplier.error) throw supplier.error;++ let insertedPurchaseOrderId = "";+ await db.transaction().execute(async (trx) => {+ const purchaseOrderId = await getNextSequence(+ trx,+ "purchaseOrder",+ companyId+ );++ const purchaseOrder = await trx+ .insertInto("purchaseOrder")+ .values([+ {+ purchaseOrderId,+ purchaseOrderType: quote.data.supplierQuoteType,+ supplierId: quote.data.supplierId,+ supplierContactId: quote.data.supplierContactId,+ supplierLocationId: quote.data.supplierLocationId,+ supplierReference: quote.data.supplierReference,+ supplierInteractionId: quote.data.supplierInteractionId,+ createdBy: userId,+ companyId: companyId,+ currencyCode:+ quote.data.currencyCode ??+ supplier.data?.currencyCode ??+ company.data?.baseCurrencyCode ??+ "USD",+ exchangeRate: quote.data.exchangeRate ?? 1,+ exchangeRateUpdatedAt:+ quote.data.exchangeRateUpdatedAt ?? datetime.timestamp()+ }+ ])+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!purchaseOrder.id) {+ throw new Error("purchase order is not created");+ }+ insertedPurchaseOrderId = purchaseOrder.id;++ await Promise.all([+ trx+ .insertInto("purchaseOrderPayment")+ .values({+ id: insertedPurchaseOrderId,+ invoiceSupplierId: supplierPayment.data.invoiceSupplierId,+ invoiceSupplierContactId:+ supplierPayment.data.invoiceSupplierContactId,+ invoiceSupplierLocationId:+ supplierPayment.data.invoiceSupplierLocationId,+ paymentTermId: supplierPayment.data.paymentTermId,+ companyId: companyId+ })+ .execute(),+ trx+ .insertInto("purchaseOrderDelivery")+ .values({+ id: insertedPurchaseOrderId,+ locationId: employeeJob.data?.locationId,+ shippingMethodId: supplierShipping.data.shippingMethodId,+ shippingTermId: supplierShipping.data.shippingTermId,+ incoterm: supplierShipping.data.incoterm,+ incotermLocation: supplierShipping.data.incotermLocation,+ companyId: companyId+ })+ .execute()+ ]);++ const purchaseOrderLineInserts: Database["public"]["Tables"]["purchaseOrderLine"]["Insert"][] =+ quoteLines.data+ .filter(+ (line) =>+ line.id &&+ selectedLines &&+ line.id in selectedLines &&+ selectedLines[line.id]!.quantity > 0+ )+ .map((line) => {+ const isIndirect = line.supplierQuoteLineType === "G/L Account";+ return {+ purchaseOrderId: insertedPurchaseOrderId,+ purchaseOrderLineType: isIndirect+ ? ("G/L Account" as const)+ : (line.item?.type as "Part"),+ description: line.description,+ itemId: isIndirect ? null : line.itemId,+ accountId: isIndirect ? line.accountId : null,+ costCenterId: isIndirect ? line.costCenterId : null,+ locationId: isIndirect ? null : employeeJob.data?.locationId,+ storageUnitId:+ pickMethods.data?.find(+ (method) => method.itemId === line.itemId+ )?.defaultStorageUnitId ?? null,+ exchangeRate: quote.data.exchangeRate ?? 1,+ conversionFactor: line.conversionFactor,+ internalNotes: toJson(line.internalNotes),+ externalNotes: toJson(line.externalNotes),+ purchaseQuantity: selectedLines![line.id!]!.quantity,+ inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,+ purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ supplierUnitPrice: selectedLines![line.id!]!.supplierUnitPrice,+ supplierShippingCost:+ selectedLines![line.id!]!.supplierShippingCost,+ supplierTaxAmount: selectedLines![line.id!]!.supplierTaxAmount,+ taxPercent: resolveTaxPercent(selectedLines![line.id!]!),+ sortOrder: line.sortOrder ?? 1,+ createdBy: userId,+ companyId+ };+ });++ if (purchaseOrderLineInserts.length > 0) {+ await trx+ .insertInto("purchaseOrderLine")+ .values(purchaseOrderLineInserts)+ .execute();++ const itemIdsToActivate = purchaseOrderLineInserts+ .map((insert) => insert.itemId)+ .filter((id): id is string => !!id);+ if (itemIdsToActivate.length > 0) {+ await trx+ .updateTable("item")+ .set({ active: true })+ .where("id", "in", itemIdsToActivate)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ // Record the ordered prices in the supplier's price list, as quoted:+ // per purchase unit, in the quote's currency. A part created here+ // takes that currency; an existing part keeps its own and gets the+ // price converted into it.+ const pricedLines = quoteLines.data.filter(+ (line) =>+ !!line.itemId &&+ line.id &&+ selectedLines &&+ line.id in selectedLines+ );++ // One supplier part per item; the later line wins.+ const supplierPartInserts = [+ ...new Map(+ pricedLines.map((line) => [+ line.itemId!,+ {+ companyId,+ supplierId: quote.data.supplierId,+ supplierPartId: line.supplierPartId,+ supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ conversionFactor: line.conversionFactor ?? 1,+ currencyCode: quote.data.currencyCode,+ itemId: line.itemId!,+ createdBy: userId+ }+ ])+ ).values()+ ];++ if (supplierPartInserts.length > 0) {+ await trx+ .insertInto("supplierPart")+ .values(supplierPartInserts)+ .onConflict((oc) =>+ oc+ .columns(["itemId", "supplierId", "companyId"])+ .doUpdateSet((eb) => ({+ supplierPartId: eb.ref("excluded.supplierPartId")+ }))+ )+ .execute();++ const supplierParts = await trx+ .selectFrom("supplierPart")+ .select(["id", "itemId", "currencyCode"])+ .where("supplierId", "=", quote.data.supplierId)+ .where("companyId", "=", companyId)+ .where(+ "itemId",+ "in",+ supplierPartInserts.map((insert) => insert.itemId)+ )+ .execute();+ const supplierPartByItemId = new Map(+ supplierParts.map((sp) => [sp.itemId, sp])+ );++ const converter = await getSupplierPartPriceConverter(+ trx,+ companyId,+ {+ currencyCode: quote.data.currencyCode,+ exchangeRate: quote.data.exchangeRate ?? 1+ },+ supplierParts.map((sp) => sp.currencyCode)+ );++ // One break per (part, quantity); the later line wins.+ const priceBreaks = new Map<+ string,+ Database["public"]["Tables"]["supplierPartPrice"]["Insert"]+ >();+ for (const line of pricedLines) {+ const supplierPart = supplierPartByItemId.get(line.itemId!);+ if (!supplierPart) continue;+ const selectedLine = selectedLines![line.id!]!;+ priceBreaks.set(`${supplierPart.id}:${selectedLine.quantity}`, {+ supplierPartId: supplierPart.id,+ quantity: selectedLine.quantity,+ supplierUnitPrice: converter.toPartCurrency(+ selectedLine.supplierUnitPrice,+ supplierPart.currencyCode+ ),+ leadTime: selectedLine.leadTime ?? 0,+ sourceType: "Purchase Order",+ sourceDocumentId: insertedPurchaseOrderId,+ companyId,+ createdBy: userId,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ });+ }++ if (priceBreaks.size > 0) {+ await trx+ .insertInto("supplierPartPrice")+ .values([...priceBreaks.values()])+ .onConflict((oc) =>+ oc+ .columns(["supplierPartId", "quantity"])+ .doUpdateSet((eb) => ({+ supplierUnitPrice: eb.ref("excluded.supplierUnitPrice"),+ leadTime: eb.ref("excluded.leadTime"),+ sourceType: eb.ref("excluded.sourceType"),+ sourceDocumentId: eb.ref("excluded.sourceDocumentId"),+ updatedBy: eb.ref("excluded.updatedBy"),+ updatedAt: eb.ref("excluded.updatedAt")+ }))+ )+ .execute();+ }++ // Each part's own price and minimum order quantity follow its+ // cheapest break.+ const supplierPartIds = supplierParts.map((sp) => sp.id);+ if (supplierPartIds.length > 0) {+ await sql`+ UPDATE "supplierPart" sp+ SET "supplierUnitPrice" = best."supplierUnitPrice",+ "minimumOrderQuantity" = best."quantity"+ FROM (+ SELECT DISTINCT ON ("supplierPartId")+ "supplierPartId", "supplierUnitPrice", "quantity"+ FROM "supplierPartPrice"+ WHERE "supplierPartId" = ANY(${supplierPartIds}::text[])+ AND "companyId" = ${companyId}+ ORDER BY "supplierPartId", "supplierUnitPrice" ASC+ ) best+ WHERE sp."id" = best."supplierPartId"+ AND sp."companyId" = ${companyId}+ `.execute(trx);+ }+ }+ });++ if (!insertedPurchaseOrderId) {+ throw new Error("Failed to insert purchase order");+ }++ // Create RFQ→PurchaseOrder links if this quote came from an RFQ+ const { data: linkedRfqs } = await many(+ db,+ "purchasingRfqToSupplierQuote",+ { supplierQuoteId: id, companyId },+ { columns: ["purchasingRfqId"] }+ );++ if (linkedRfqs && linkedRfqs.length > 0) {+ await insertRows(+ db,+ "purchasingRfqToPurchaseOrder",+ linkedRfqs.map((rfq) => ({+ purchasingRfqId: rfq.purchasingRfqId,+ purchaseOrderId: insertedPurchaseOrderId,+ companyId+ }))+ );+ }++ convertedId = insertedPurchaseOrderId;++ break;+ }++ case "warehouseTransferToShipment": {+ const warehouseTransferId = id;+ const [warehouseTransfer, warehouseTransferLines] = await inOrder([+ () =>+ maybeSingle(db, "warehouseTransfer", {+ id: warehouseTransferId,+ companyId+ }),+ () =>+ many(db, "warehouseTransferLine", {+ transferId: warehouseTransferId,+ companyId+ })+ ]);++ if (warehouseTransfer.error)+ throw new Error(warehouseTransfer.error.message);+ if (!warehouseTransfer.data)+ throw new NotFoundError("Warehouse transfer not found");+ if (warehouseTransferLines.error)+ throw new Error(warehouseTransferLines.error.message);++ let shipmentId = "";++ await db.transaction().execute(async (trx) => {+ // Create shipment for outbound transfer+ shipmentId = await getNextSequence(trx, "shipment", companyId);++ const shipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId,+ status: "Draft",+ sourceDocument: "Outbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data!.transferId,+ locationId: warehouseTransfer.data!.fromLocationId,+ createdBy: userId,+ companyId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!shipment.id) throw new Error("Failed to create shipment");+ shipmentId = shipment.id;++ // Create shipment lines+ const shipmentLineInserts = warehouseTransferLines.data.map((line) => ({+ shipmentId,+ lineId: line.id,+ itemId: line.itemId,+ locationId: line.fromLocationId,+ storageUnitId: line.fromStorageUnitId,+ orderQuantity: line.quantity,+ shippedQuantity: 0,+ unitOfMeasure: line.unitOfMeasureCode || "EA",+ unitPrice: 0,+ companyId,+ createdBy: userId+ }));++ if (shipmentLineInserts.length > 0) {+ await trx+ .insertInto("shipmentLine")+ .values(shipmentLineInserts)+ .execute();+ }+ });++ convertedId = shipmentId;+ break;+ }++ case "warehouseTransferToReceipt": {+ const warehouseTransferId = id;+ const [warehouseTransfer, warehouseTransferLines] = await inOrder([+ () =>+ maybeSingle(db, "warehouseTransfer", {+ id: warehouseTransferId,+ companyId+ }),+ () =>+ many(db, "warehouseTransferLine", {+ transferId: warehouseTransferId,+ companyId+ })+ ]);++ if (warehouseTransfer.error)+ throw new Error(warehouseTransfer.error.message);+ if (!warehouseTransfer.data)+ throw new NotFoundError("Warehouse transfer not found");+ if (warehouseTransferLines.error)+ throw new Error(warehouseTransferLines.error.message);++ let receiptId = "";++ await db.transaction().execute(async (trx) => {+ // Create receipt for inbound transfer+ receiptId = await getNextSequence(trx, "receipt", companyId);++ const receipt = await trx+ .insertInto("receipt")+ .values({+ receiptId,+ status: "Draft",+ sourceDocument: "Inbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data!.transferId,+ locationId: warehouseTransfer.data!.toLocationId,+ createdBy: userId,+ companyId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!receipt.id) throw new Error("Failed to create receipt");+ receiptId = receipt.id;++ // Create receipt lines+ const receiptLineInserts = warehouseTransferLines.data.map((line) => ({+ receiptId,+ lineId: line.id,+ itemId: line.itemId,+ locationId: line.toLocationId,+ storageUnitId: line.toStorageUnitId,+ orderQuantity: line.quantity,+ receivedQuantity: 0,+ unitOfMeasure: line.unitOfMeasureCode || "EA",+ unitPrice: 0,+ companyId,+ createdBy: userId+ }));++ if (receiptLineInserts.length > 0) {+ await trx+ .insertInto("receiptLine")+ .values(receiptLineInserts)+ .execute();+ }+ });++ convertedId = receiptId;+ break;+ }++ default:+ throw new Error(`Invalid type ${type}`);+ }++ return { convertedId };+ }++ /** A server function's refusal as this function's error, mapped as `run`+ * maps it; an empty message (our own failure) is `fallback`. */+ export function fromServerFn(+ ctx: ServiceContext,+ error: { status: number; message: string },+ fallback: string+ ): CarbonError {+ return serverFnRefusal(ctx, error, fallback);+ }+ const createDocumentLogger = getLogger("server-functions", "create");++ // Resolves a fallback location when a caller omits locationId, so creating a+ // blank shipment degrades gracefully instead of failing payload validation.+ // Prefers the creating user's assigned employeeJob location, then the company's+ // earliest-created location. Only safe where locationId does not scope which+ // source-document lines are shipped (i.e. shipmentDefault).+ async function getFallbackLocationId(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ userId: string+ ): Promise<string | null> {+ const employeeJob = await maybeSingle(+ db,+ "employeeJob",+ { id: userId, companyId },+ { columns: ["locationId"] }+ );+ if (employeeJob.data?.locationId) return employeeJob.data.locationId;++ const location = await maybeSingle(+ db,+ "location",+ { companyId },+ { columns: ["id"], orderBy: ["createdAt"], limit: 1 }+ );+ return location.data?.id ?? null;+ }+++// Blind receiving (`companySettings.receiptQuantitiesStartAtZero`): when on, a++// new receipt's lines start at a received quantity of 0 rather than what is++// still to receive, so the receiver enters what actually arrived and a line++// nothing arrived for stays at 0.++async function receiptQuantitiesStartAtZero(++ db: Kysely<KyselyDatabase>,++ companyId: string++): Promise<boolean> {++ const row = await db++ .selectFrom("companySettings")++ .select("receiptQuantitiesStartAtZero")++ .where("id", "=", companyId)++ .executeTakeFirst();++ return row?.receiptQuantitiesStartAtZero === true;++}+++ export const createDocumentPermission = {+ by: "type",+ rules: {+ nonConformanceTasks: { update: "quality" },+ purchaseOrderFromJob: { create: ["purchasing", "production"] },+ receiptDefault: { create: "inventory" },+ receiptFromPurchaseOrder: { create: "inventory" },+ receiptFromInboundTransfer: { create: "inventory" },+ receiptFromSalesReturnOrder: { create: "inventory" },+ receiptFromWarehouseTransfer: { create: "inventory" },+ receiptLineSplit: { create: "inventory" },+ shipmentDefault: { create: "inventory" },+ shipmentFromPurchaseOrder: { create: "inventory" },+ shipmentFromWarehouseTransfer: { create: "inventory" },+ shipmentFromPurchaseReturnOrder: { create: "inventory" },+ shipmentFromSalesOrder: { create: "inventory" },+ shipmentFromSalesReturnOrder: { create: "inventory" },+ shipmentFromSalesOrderLine: { create: "inventory" },+ shipmentLineSplit: { create: "inventory" },+ shipmentFromRentalAgreement: { create: "inventory" },+ receiptFromRentalAgreement: { create: "inventory" },+ journalEntry: { create: "accounting" }+ }+ } satisfies PermissionRule<z.output<typeof createInput>>;++ /** Creates receipts, shipments, NCR tasks, purchase orders and journal entries, per `type`. */+ export async function createDocument(+ ctx: ServiceContext,+ raw: CreateInput+ ): Promise<CreateResult> {+ const input = createInput.parse(raw);++ const db = ctx.asSystem.pg;+ const companyId = ctx.company.id;+ const userId = ctx.auditUserId;+ const payload = { ...input, companyId, userId };+ const { type } = payload;++ // Every receipt/shipment type writes the body's locationId onto the new+ // document (and its lines); the FK alone accepts another company's location.+ await assertCompanyRecords(+ db,+ "location",+ ["locationId" in payload ? payload.locationId : undefined],+ companyId,+ "Location"+ );++ switch (payload.type) {+ case "nonConformanceTasks": {+ const { id } = payload;++ createDocumentLogger.info({ type, id });++ const [nonConformance, actionTasks, approvalTasks, existingReviewers] =+ await inOrder([+ () => maybeSingle(db, "nonConformance", { id, companyId }),+ () =>+ many(db, "nonConformanceActionTask", {+ nonConformanceId: id,+ companyId+ }),+ () =>+ many(db, "nonConformanceApprovalTask", {+ nonConformanceId: id,+ companyId+ }),+ () =>+ many(db, "nonConformanceReviewer", {+ nonConformanceId: id,+ companyId+ })+ ]);++ if (nonConformance.error) throw new Error(nonConformance.error.message);+ if (!nonConformance.data)+ throw new NotFoundError("Non-conformance not found");++ const workflow = nonConformance.data?.nonConformanceWorkflowId+ ? await maybeSingle(db, "nonConformanceWorkflow", {+ id: nonConformance.data?.nonConformanceWorkflowId,+ companyId+ })+ : null;++ if (workflow?.error) throw new Error(workflow.error.message);++ const currentActionTasks =+ actionTasks.data?.reduce<Record<string, string>>((acc, d) => {+ if (d.actionTypeId && !acc[d.actionTypeId]) {+ acc[d.actionTypeId] = d.id;+ }+ return acc;+ }, {}) ?? {};++ const currentApprovalTasks =+ approvalTasks.data?.reduce<Record<string, string>>((acc, d) => {+ if (d.approvalType && !acc[d.approvalType]) {+ acc[d.approvalType] = d.id;+ }+ return acc;+ }, {}) ?? {};++ const actionTasksToDelete: string[] = [];+ const approvalTasksToDelete: string[] = [];+ const reviewersToDelete: string[] = [];++ Object.keys(currentActionTasks).forEach((actionTypeId) => {+ if (+ !(nonConformance.data?.requiredActionIds ?? []).some(+ (d) => d === actionTypeId+ )+ ) {+ actionTasksToDelete.push(currentActionTasks[actionTypeId]!);+ }+ });++ Object.keys(currentApprovalTasks).forEach((approvalType) => {+ if (+ !(nonConformance.data?.approvalRequirements ?? []).some(+ (d) => d === approvalType+ )+ ) {+ approvalTasksToDelete.push(currentApprovalTasks[approvalType]!);+ }+ });++ const actionTaskInserts: Database["public"]["Tables"]["nonConformanceActionTask"]["Insert"][] =+ [];+ const approvalTaskInserts: Database["public"]["Tables"]["nonConformanceApprovalTask"]["Insert"][] =+ [];++ const reviewerInserts: Database["public"]["Tables"]["nonConformanceReviewer"]["Insert"][] =+ [];++ nonConformance.data?.requiredActionIds?.forEach((actionTypeId, index) => {+ if (!currentActionTasks[actionTypeId]) {+ actionTaskInserts.push({+ nonConformanceId: id,+ actionTypeId,+ sortOrder: index + 1,+ companyId,+ createdBy: userId+ });+ }+ });++ nonConformance.data?.approvalRequirements?.forEach((approvalType) => {+ if (!currentApprovalTasks[approvalType]) {+ approvalTaskInserts.push({+ nonConformanceId: id,+ approvalType,+ companyId,+ createdBy: userId+ });+ }+ });++ // Check if MRB approval is required+ const hasMRBApproval =+ Array.isArray(nonConformance.data?.approvalRequirements) &&+ nonConformance.data?.approvalRequirements.includes("MRB");++ const hasExistingMRBTask =+ Object.keys(currentApprovalTasks).includes("MRB");+ const hasExistingReviewers = (existingReviewers.data?.length ?? 0) > 0;++ // If MRB is no longer required but we have existing reviewers, delete them+ if (!hasMRBApproval && hasExistingReviewers) {+ existingReviewers.data?.forEach((reviewer) => {+ reviewersToDelete.push(reviewer.id);+ });+ }+ // Only add reviewers if MRB is required and either:+ // 1. MRB task is newly added (not in currentApprovalTasks)+ // 2. There are no existing reviewers+ else if (+ hasMRBApproval &&+ (!hasExistingMRBTask || !hasExistingReviewers)+ ) {+ reviewerInserts.push({+ nonConformanceId: id,+ title: "Engineering",+ companyId,+ createdBy: userId+ });++ reviewerInserts.push({+ nonConformanceId: id,+ title: "Quality",+ companyId,+ createdBy: userId+ });+ }++ await db.transaction().execute(async (trx) => {+ if (+ typeof nonConformance.data?.content === "object" &&+ // @ts-ignore -- content is json+ Object.keys(nonConformance.data?.content ?? {}).length === 0+ ) {+ const contentFromWorkflow =+ (workflow?.data?.content as { content?: unknown[] } | null)+ ?.content ?? [];+ const insertedContent = {+ type: "doc",+ content: contentFromWorkflow+ };++ if (nonConformance.data?.description) {+ insertedContent.content.unshift({+ type: "paragraph",+ content: [+ { type: "text", text: nonConformance.data?.description }+ ]+ });+ }++ createDocumentLogger.debug({+ description: nonConformance.data?.description,+ insertedContent+ });++ if (insertedContent.content.length > 0) {+ await trx+ .updateTable("nonConformance")+ .set({+ content: JSON.stringify(insertedContent)+ })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (actionTaskInserts.length > 0) {+ await trx+ .insertInto("nonConformanceActionTask")+ .values(actionTaskInserts)+ .execute();+ }+ if (approvalTaskInserts.length > 0) {+ await trx+ .insertInto("nonConformanceApprovalTask")+ .values(approvalTaskInserts)+ .execute();+ }++ if (actionTasksToDelete.length > 0) {+ await trx+ .deleteFrom("nonConformanceActionTask")+ .where("id", "in", actionTasksToDelete)+ .where("companyId", "=", companyId)+ .execute();+ }+ if (approvalTasksToDelete.length > 0) {+ await trx+ .deleteFrom("nonConformanceApprovalTask")+ .where("id", "in", approvalTasksToDelete)+ .where("companyId", "=", companyId)+ .execute();+ }++ if (reviewerInserts.length > 0) {+ await trx+ .insertInto("nonConformanceReviewer")+ .values(reviewerInserts)+ .execute();+ }++ if (reviewersToDelete.length > 0) {+ await trx+ .deleteFrom("nonConformanceReviewer")+ .where("id", "in", reviewersToDelete)+ .where("companyId", "=", companyId)+ .execute();+ }+ });+ return { success: true };+ }++ case "purchaseOrderFromJob": {+ const { jobId, purchaseOrdersBySupplierId } = payload;+ // The PO each supplier's lines landed on (created or chosen), so a caller+ // releasing several jobs can put them on one PO per supplier.+ const purchaseOrderIdsBySupplierId: Record<string, string> = {};++ createDocumentLogger.info({ type, jobId, companyId, userId });+ const [job, jobOperations] = await inOrder([+ () => maybeSingle(db, "job", { id: jobId, companyId }),+ () =>+ many<+ "jobOperation",+ rowsModule.Tables["jobOperation"]["Row"] & {+ jobMakeMethod: Pick<+ rowsModule.Tables["jobMakeMethod"]["Row"],+ "itemId"+ > | null;+ }+ >(+ db,+ "jobOperation",+ { jobId, companyId },+ {+ embed: {+ jobMakeMethod: {+ table: "jobMakeMethod",+ via: "jobMakeMethodId",+ columns: ["itemId"]+ }+ }+ }+ )+ ]);++ if (job.error) throw new Error(job.error.message);+ if (!job.data) throw new NotFoundError("Job not found");+ if (jobOperations.error) throw new Error(jobOperations.error.message);++ // Caller-chosen existing POs must belong to this company — lines are+ // appended to them by id below.+ await assertCompanyRecords(+ db,+ "purchaseOrder",+ Object.values(+ purchaseOrdersBySupplierId as Record<string, string>+ ).filter((poId) => poId && poId !== "new"),+ companyId,+ "Purchase order"+ );++ const outsideOperations = jobOperations.data?.filter(+ (d) => d.operationType === "Outside Processing"+ );++ if (outsideOperations.length > 0) {+ const supplierProcessIds = new Set(+ outsideOperations+ .map((d) => d.operationSupplierProcessId)+ .filter(Boolean)+ );+ const outsideProcessIds = new Set(+ outsideOperations.map((d) => d.processId).filter(Boolean)+ );+ const [+ supplierProcesses,+ supplierProcessesByProcess,+ existingPurchaseOrderLines+ ] = await inOrder([+ () =>+ supplierProcessIds.size > 0+ ? many(db, "supplierProcess", {+ id: Array.from(supplierProcessIds) as string[],+ companyId+ })+ : Promise.resolve({ data: [], error: null }),+ () =>+ outsideProcessIds.size > 0+ ? many(db, "supplierProcess", {+ processId: Array.from(outsideProcessIds),+ companyId+ })+ : Promise.resolve({ data: [], error: null }),+ () =>+ many(db, "purchaseOrderLine", {+ jobId,+ companyId,+ jobOperationId: outsideOperations.map((d) => d.id)+ })+ ]);++ if (supplierProcesses.error)+ throw new Error(supplierProcesses.error.message);+ if (supplierProcessesByProcess.error)+ throw new Error(supplierProcessesByProcess.error.message);++ // Resolve an operation's supplier process: its own, or — when it has none+ // — the sole supplier configured for its process (a process with exactly+ // one supplier is unambiguous). Mirrors the release modal's resolution so+ // an operation the modal counted as "has a supplier" actually gets a PO.+ const allSupplierProcesses = [+ ...(supplierProcesses.data ?? []),+ ...(supplierProcessesByProcess.data ?? [])+ ];+ const supplierProcessById = new Map(+ allSupplierProcesses.map((sp) => [sp.id, sp])+ );+ const supplierProcessesByProcessId = new Map<+ string,+ typeof allSupplierProcesses+ >();+ for (const sp of supplierProcessesByProcess.data ?? []) {+ const list = supplierProcessesByProcessId.get(sp.processId) ?? [];+ list.push(sp);+ supplierProcessesByProcessId.set(sp.processId, list);+ }+ const resolveSupplierProcess = (oo: {+ operationSupplierProcessId: string | null;+ processId: string | null;+ }) => {+ if (oo.operationSupplierProcessId) {+ return supplierProcessById.get(oo.operationSupplierProcessId);+ }+ const candidates = oo.processId+ ? (supplierProcessesByProcessId.get(oo.processId) ?? [])+ : [];+ return candidates.length === 1 ? candidates[0] : undefined;+ };++ const outsideOperationsBySupplierId = outsideOperations.reduce<+ Record<+ string,+ (Database["public"]["Tables"]["jobOperation"]["Row"] & {+ jobMakeMethod: { itemId: string } | null;+ })[]+ >+ >((acc, oo) => {+ const supplierProcess = resolveSupplierProcess(oo);+ if (+ existingPurchaseOrderLines.data?.find(+ (d) => d.jobOperationId === oo.id+ )+ ) {+ return acc;+ }+ if (!supplierProcess) return acc;+ if (!acc[supplierProcess.supplierId]) {+ acc[supplierProcess.supplierId] = [];+ }+ acc[supplierProcess.supplierId]!.push(oo);+ return acc;+ }, {});++ const supplierIds = new Set(Object.keys(outsideOperationsBySupplierId));+ const itemIds = new Set(+ outsideOperations.map((d) => d.jobMakeMethod?.itemId).filter(Boolean)+ );++ const [suppliers, supplierPayments, supplierShipping, items] =+ await inOrder([+ () =>+ many(db, "supplier", {+ id: Array.from(supplierIds),+ companyId+ }),+ () =>+ many(db, "supplierPayment", {+ supplierId: Array.from(supplierIds),+ companyId+ }),+ () =>+ many(db, "supplierShipping", {+ supplierId: Array.from(supplierIds),+ companyId+ }),+ () =>+ many(db, "item", {+ id: Array.from(itemIds) as string[],+ companyId+ })+ ]);++ if (suppliers.error) throw new Error(suppliers.error.message);+ if (supplierPayments.error)+ throw new Error(supplierPayments.error.message);+ if (supplierShipping.error)+ throw new Error(supplierShipping.error.message);++ // A supplier with no configured currency means "the company's own+ // base currency" (rate 1 by definition) -- never a hardcoded USD,+ // which is only correct for USD-base companies.+ const companyRecord = await single(+ db,+ "company",+ { id: companyId },+ { columns: ["baseCurrencyCode"] }+ );+ if (companyRecord.error) {+ throw new Error(companyRecord.error.message);+ }+ const baseCurrencyCode = companyRecord.data.baseCurrencyCode;++ const currencyCodes = new Set(+ suppliers.data?.map((d) => d.currencyCode ?? baseCurrencyCode)+ );++ // get_exchange_rate raises on a missing rate -- a resolver error+ // must fail the operation rather than default the rate.+ const exchangeRates = await Promise.all(+ Array.from(currencyCodes).map(async (currencyCode) => {+ const exchangeRate = await rpcValue(db, "get_exchange_rate", {+ p_company_id: companyId,+ p_currency_code: currencyCode+ });+ if (exchangeRate.error) {+ throw new Error(exchangeRate.error.message);+ }+ return {+ currencyCode,+ exchangeRate: Number(exchangeRate.data)+ };+ })+ );++ await db.transaction().execute(async (trx) => {+ for await (const supplier of Object.keys(+ outsideOperationsBySupplierId+ )) {+ const outsideOperations = outsideOperationsBySupplierId[supplier];++ const payment = supplierPayments.data?.find(+ (d) => d.supplierId === supplier+ );+ const shipping = supplierShipping.data?.find(+ (d) => d.supplierId === supplier+ );++ const supplierCurrencyCode =+ suppliers.data?.find((d) => d.id === supplier)?.currencyCode ??+ baseCurrencyCode;+ const exchangeRate = exchangeRates.find(+ (d) => d.currencyCode === supplierCurrencyCode+ )?.exchangeRate;+ if (exchangeRate === undefined) {+ throw new Error(+ `No exchange rate resolved for currency ${supplierCurrencyCode}`+ );+ }++ let purchaseOrderId =+ purchaseOrdersBySupplierId[supplier] === "new"+ ? undefined+ : purchaseOrdersBySupplierId[supplier];++ if (!purchaseOrderId) {+ const supplierInteraction = await trx+ .insertInto("supplierInteraction")+ .values({+ companyId,+ supplierId: supplier+ })+ .returning(["id"])+ .execute();++ const supplierInteractionId = supplierInteraction?.[0]?.id;+ const nextSequence = await getNextSequence(+ trx,+ "purchaseOrder",+ companyId+ );++ if (!nextSequence) throw new Error("Failed to get next sequence");+ if (!supplierInteractionId)+ throw new Error("Failed to create supplier interaction");++ const order = await trx+ .insertInto("purchaseOrder")+ .values({+ purchaseOrderId: nextSequence,+ status: "Draft",+ supplierId: supplier,+ jobId: jobId,+ jobReadableId: job.data?.jobId,+ companyId: companyId,+ createdBy: userId,+ purchaseOrderType: "Outside Processing",+ supplierInteractionId: supplierInteractionId,+ currencyCode: supplierCurrencyCode,+ exchangeRate,+ exchangeRateUpdatedAt: datetime.timestamp()+ })+ .returning(["id"])+ .execute();++ if (!order?.[0]?.id)+ throw new Error("Failed to create purchase order");++ purchaseOrderId = order[0].id;++ // Create purchase order delivery and payment+ const locationId = job.data?.locationId ?? null; // Default location+ const shippingMethodId = shipping?.shippingMethodId;+ const shippingTermId = shipping?.shippingTermId;++ const paymentTermId = payment?.paymentTermId;+ const invoiceSupplierId = payment?.invoiceSupplierId;+ const invoiceSupplierContactId =+ payment?.invoiceSupplierContactId;+ const invoiceSupplierLocationId =+ payment?.invoiceSupplierLocationId;++ await Promise.all([+ trx+ .insertInto("purchaseOrderDelivery")+ .values({+ id: purchaseOrderId,+ locationId,+ shippingMethodId,+ shippingTermId,+ companyId+ })+ .execute(),+ trx+ .insertInto("purchaseOrderPayment")+ .values({+ id: purchaseOrderId,+ invoiceSupplierId,+ invoiceSupplierContactId,+ invoiceSupplierLocationId,+ paymentTermId,+ companyId+ })+ .execute()+ ]);+ }++ purchaseOrderIdsBySupplierId[supplier] = purchaseOrderId;++ const purchaseOrderLineInserts: Database["public"]["Tables"]["purchaseOrderLine"]["Insert"][] =+ [];++ // Create purchase order lines for each process+ for await (const operation of outsideOperations!) {+ // Get the item associated with the operation+ const item = items.data?.find(+ (d) => d.id === operation.jobMakeMethod?.itemId+ );+ const supplierProcess = resolveSupplierProcess(operation);++ if (item && supplierProcess) {+ const totalCostWithUnitPrice =+ (operation.operationUnitCost ?? 0) *+ (operation.operationQuantity ?? 0);+ const totalCostWithMinimumCost =+ (operation.operationMinimumCost ?? 0) > totalCostWithUnitPrice+ ? (operation.operationMinimumCost ?? 0)+ : totalCostWithUnitPrice;++ // Create purchase order line+ purchaseOrderLineInserts.push({+ purchaseOrderId,+ purchaseOrderLineType: item.type,+ itemId: item.id,+ description: item.name || item.description,+ purchaseQuantity: operation.operationQuantity || 1,+ purchaseUnitOfMeasureCode: item.unitOfMeasureCode,+ inventoryUnitOfMeasureCode: item.unitOfMeasureCode,+ conversionFactor: 1,+ supplierUnitPrice:+ operation.operationQuantity &&+ operation.operationQuantity > 0+ ? totalCostWithMinimumCost / operation.operationQuantity+ : totalCostWithMinimumCost,+ locationId: job.data?.locationId,+ jobId: job.data?.id,+ jobOperationId: operation.id,+ companyId,+ createdBy: userId,+ exchangeRate+ });+ }+ }++ // Insert all purchase order lines+ if (purchaseOrderLineInserts.length > 0) {+ await trx+ .insertInto("purchaseOrderLine")+ .values(purchaseOrderLineInserts)+ .execute();+ }+ }+ });+ }++ return { success: true, purchaseOrderIdsBySupplierId };+ }+ case "receiptDefault": {+ const { locationId } = payload;+ let createdDocumentId;+ createDocumentLogger.info({ type, locationId, companyId, userId });+ const id = await db.transaction().execute(async (trx) => {+ createdDocumentId = await getNextSequence(trx, "receipt", companyId);+ const newReceipt = await trx+ .insertInto("receipt")+ .values({+ receiptId: createdDocumentId,+ companyId: companyId,+ locationId: locationId,+ createdBy: userId+ })+ .returning(["id", "receiptId"])+ .execute();++ createdDocumentId = newReceipt?.[0]?.id;+ if (!createdDocumentId) throw new Error("Failed to create receipt");+ return createdDocumentId;+ });++ return { id };+ }+ case "receiptFromPurchaseOrder": {+ const {+ purchaseOrderId,+ receiptId: existingReceiptId,+ locationId: userLocationId+ } = payload;++ createDocumentLogger.info({+ type,+ companyId,+ purchaseOrderId,+ existingReceiptId,+ userLocationId,+ userId+ });++ const [purchaseOrder, purchaseOrderLines, fixedAssetPoLines, receipt] =+ await inOrder([+ () =>+ single(db, "purchaseOrders", { companyId, id: purchaseOrderId }),+ () =>+ many(db, "purchaseOrderLine", {+ companyId,+ purchaseOrderId,+ purchaseOrderLineType: [+ "Part",+ "Material",+ "Tool",+ "Fixture",+ "Consumable"+ ]+ }),+ () =>+ many(+ db,+ "purchaseOrderLine",+ {+ companyId,+ purchaseOrderId,+ purchaseOrderLineType: "Fixed Asset"+ },+ {+ columns: [+ "id",+ "purchaseOrderLineType",+ "assetId",+ "purchaseQuantity",+ "quantityReceived",+ "receivedComplete"+ ]+ }+ ),+ () =>+ maybeSingle(db, "receipt", { companyId, id: existingReceiptId! })+ ]);++ if (!purchaseOrder.data)+ throw new NotFoundError("Purchase order not found");+ if (purchaseOrderLines.error)+ throw new Error(purchaseOrderLines.error.message);++ let locationId = purchaseOrder.data.locationId;+ if (+ purchaseOrderLines.data.some(+ (d) => d.locationId !== locationId && d.locationId === userLocationId+ )+ ) {+ locationId = userLocationId ?? null;+ }++ const items = await many(+ db,+ "item",+ {+ companyId,+ id: purchaseOrderLines.data+ .filter((d) => d.locationId === locationId)+ .map((d) => d.itemId) as string[]+ },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ // Map (itemId, locationId) -> defaultStorageUnitId. Receipt lines+ // fall back to the pickMethod-configured storage unit for their+ // destination location when the purchase order line doesn't pin+ // one explicitly. Scoped by locationId because a single item can+ // be stocked across multiple locations with different defaults+ // per location (that's why pickMethod exists).+ const receiptItemIds = purchaseOrderLines.data+ .filter((d): d is typeof d & { itemId: string } => !!d.itemId)+ .map((d) => d.itemId);+ const pickMethods = await many(+ db,+ "pickMethod",+ { companyId, itemId: receiptItemIds },+ { columns: ["itemId", "locationId", "defaultStorageUnitId"] }+ );+ const pickMethodKey = (itemId: string, loc: string | null) =>+ `${itemId}::${loc ?? ""}`;+ const defaultStorageUnitByItemLocation = new Map<string, string>();+ for (const row of pickMethods.data ?? []) {+ if (row.defaultStorageUnitId) {+ defaultStorageUnitByItemLocation.set(+ pickMethodKey(row.itemId, row.locationId),+ row.defaultStorageUnitId+ );+ }+ }++ // A supplied id that is not this company's receipt is a 404, not a+ // silent create-new.+ if (existingReceiptId && !receipt.data)+ throw new NotFoundError("Receipt not found");+ const hasReceipt = !!receipt.data?.id;+ const isOutsideOperation =+ purchaseOrder.data.purchaseOrderType === "Outside Processing";++ const previouslyReceivedQuantitiesByLine = (+ purchaseOrderLines.data ?? []+ ).reduce<Record<string, number>>((acc, d) => {+ if (d.id) acc[d.id] = d.quantityReceived ?? 0;+ return acc;+ }, {});+++ const startAtZero = await receiptQuantitiesStartAtZero(db, companyId);+++ const receiptLineItems = purchaseOrderLines.data.reduce<+ ReceiptLineItem[]+ >((acc, d) => {+ if (+ !d.itemId ||+ !d.purchaseQuantity ||+ d.receivedComplete ||+ d.purchaseOrderLineType === "Service" ||+ d.purchaseOrderLineType === "G/L Account"+ ) {+ return acc;+ }++ const unitPrice = d.unitPrice ?? 0;+ const outstandingQuantity =+ d.purchaseQuantity - (previouslyReceivedQuantitiesByLine[d.id!] ?? 0);++ const shippingAndTaxUnitCost =+ ((d.taxAmount ?? 0) + (d.shippingCost ?? 0)) /+ (d.purchaseQuantity * (d.conversionFactor ?? 1));++ acc.push({+ lineId: d.id,+ companyId: companyId,+ itemId: d.itemId,+ orderQuantity: d.purchaseQuantity * (d.conversionFactor ?? 1),+ outstandingQuantity: outstandingQuantity * (d.conversionFactor ?? 1),- receivedQuantity: outstandingQuantity * (d.conversionFactor ?? 1),++ receivedQuantity: startAtZero++ ? 0++ : outstandingQuantity * (d.conversionFactor ?? 1),+ conversionFactor: d.conversionFactor ?? 1,+ requiresSerialTracking:+ serializedItems.has(d.itemId) && !isOutsideOperation,+ requiresBatchTracking:+ batchItems.has(d.itemId) && !isOutsideOperation,+ unitPrice:+ unitPrice / (d.conversionFactor ?? 1) + shippingAndTaxUnitCost,+ unitOfMeasure: d.inventoryUnitOfMeasureCode ?? "EA",+ locationId: d.locationId ?? null,+ storageUnitId:+ d.storageUnitId ??+ defaultStorageUnitByItemLocation.get(+ pickMethodKey(d.itemId!, d.locationId ?? null)+ ) ??+ null,+ createdBy: userId ?? ""+ });++ return acc;+ }, []);++ const hasUnreceivedFaLines = (fixedAssetPoLines.data ?? []).some(+ (d) => d.assetId && d.purchaseQuantity && !d.receivedComplete+ );+ if (receiptLineItems.length === 0 && !hasUnreceivedFaLines) {+ throw new Error("No valid receipt line items found");+ }++ let receiptId = hasReceipt ? receipt.data?.id! : "";+ let receiptIdReadable = hasReceipt ? receipt.data?.receiptId! : "";++ await db.transaction().execute(async (trx) => {+ if (hasReceipt) {+ // update existing receipt+ await trx+ .updateTable("receipt")+ .set({+ sourceDocument: "Purchase Order",+ sourceDocumentId: purchaseOrder.data.id,+ sourceDocumentReadableId: purchaseOrder.data.purchaseOrderId,+ locationId: locationId,+ updatedBy: userId+ })+ .where("id", "=", receiptId)+ .returning(["id", "receiptId"])+ .where("companyId", "=", companyId)+ .execute();+ // delete existing receipt lines+ await trx+ .deleteFrom("receiptLine")+ .where("receiptId", "=", receiptId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ receiptIdReadable = await getNextSequence(trx, "receipt", companyId);+ const newReceipt = await trx+ .insertInto("receipt")+ .values({+ receiptId: receiptIdReadable,+ sourceDocument: "Purchase Order",+ sourceDocumentId: purchaseOrder.data.id,+ sourceDocumentReadableId: purchaseOrder.data.purchaseOrderId,+ supplierId: purchaseOrder.data.supplierId,+ supplierInteractionId: purchaseOrder.data.supplierInteractionId,+ companyId: companyId,+ locationId: locationId,+ createdBy: userId+ })+ .returning(["id", "receiptId"])+ .execute();++ receiptId = newReceipt?.[0]?.id!;+ receiptIdReadable = newReceipt?.[0]?.receiptId!;+ }++ if (receiptLineItems.length > 0) {+ await trx+ .insertInto("receiptLine")+ .values(+ receiptLineItems.map((line) => ({+ ...line,+ receiptId: receiptId,+ locationId+ }))+ )+ .execute();+ }++ const unreceivedFaLines = (fixedAssetPoLines.data ?? []).filter(+ (d) => d.assetId && d.purchaseQuantity && !d.receivedComplete+ );+ if (unreceivedFaLines.length > 0) {+ await trx+ .deleteFrom("receiptFixedAssetLine")+ .where("receiptId", "=", receiptId)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .insertInto("receiptFixedAssetLine")+ .values(+ unreceivedFaLines.map((line) => ({+ receiptId: receiptId,+ purchaseOrderLineId: line.id,- received: true,++ received: !startAtZero,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }+ });++ return { id: receiptId };+ }+ case "receiptFromInboundTransfer": {+ const { warehouseTransferId, receiptId: existingReceiptId } = payload;++ createDocumentLogger.info({+ type,+ companyId,+ warehouseTransferId,+ existingReceiptId,+ userId+ });++ const [warehouseTransfer, warehouseTransferLines, receipt] =+ await inOrder([+ () =>+ single(db, "warehouseTransfer", {+ companyId,+ id: warehouseTransferId+ }),+ () =>+ many(db, "warehouseTransferLine", {+ companyId,+ transferId: warehouseTransferId+ }),+ () =>+ maybeSingle(db, "receipt", { companyId, id: existingReceiptId! })+ ]);++ if (!warehouseTransfer.data)+ throw new NotFoundError("Warehouse transfer not found");+ if (warehouseTransferLines.error)+ throw new Error(warehouseTransferLines.error.message);++ const locationId = warehouseTransfer.data.toLocationId;++ const items = await many(+ db,+ "item",+ {+ companyId,+ id: warehouseTransferLines.data+ .map((d) => d.itemId)+ .filter(Boolean) as string[]+ },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ // A supplied id that is not this company's receipt is a 404, not a+ // silent create-new.+ if (existingReceiptId && !receipt.data)+ throw new NotFoundError("Receipt not found");+ const hasReceipt = !!receipt.data?.id;++ const previouslyReceivedQuantitiesByLine = (+ warehouseTransferLines.data ?? []+ ).reduce<Record<string, number>>((acc, d) => {+ if (d.id) acc[d.id] = d.receivedQuantity ?? 0;+ return acc;+ }, {});+++ const startAtZero = await receiptQuantitiesStartAtZero(db, companyId);+++ const receiptLineItems = warehouseTransferLines.data.reduce<+ ReceiptLineItem[]+ >((acc, d) => {+ if (!d.itemId || !d.quantity) return acc;++ const serialTracking = serializedItems.has(d.itemId);+ const batchTracking = batchItems.has(d.itemId);+ // For unshipped lines, we want all lines where shippedQuantity < quantity+ const quantityToReceive = Math.max(+ 0,+ (d.shippedQuantity ?? 0) -+ (previouslyReceivedQuantitiesByLine[d.id] ?? 0)+ );++ if (quantityToReceive === 0) return acc;++ acc.push({+ lineId: d.id,+ itemId: d.itemId,+ locationId: d.toLocationId ?? locationId,+ storageUnitId: d.toStorageUnitId,+ requiresSerialTracking: serialTracking,+ requiresBatchTracking: batchTracking,- receivedQuantity: quantityToReceive,++ receivedQuantity: startAtZero ? 0 : quantityToReceive,+ outstandingQuantity: quantityToReceive,+ unitPrice: 0, // Transfers don't have a unit price+ conversionFactor: 1,+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",+ companyId,+ createdBy: userId,+ orderQuantity: d.quantity ?? 0+ });++ return acc;+ }, []);++ if (receiptLineItems.length === 0) {+ throw new Error("No lines to receive");+ }++ const result = await db.transaction().execute(async (trx) => {+ const receiptId = await getNextSequence(trx, "receipt", companyId);++ let id: string;+ if (hasReceipt) {+ id = receipt.data!.id;+ await trx+ .updateTable("receipt")+ .set({+ sourceDocument: "Inbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data.transferId,+ locationId,+ updatedBy: userId+ })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const insertReceipt = await trx+ .insertInto("receipt")+ .values({+ receiptId,+ sourceDocument: "Inbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data.transferId,+ locationId,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ id = insertReceipt[0]?.id ?? "";+ }++ await trx+ .deleteFrom("receiptLine")+ .where("receiptId", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .insertInto("receiptLine")+ .values(+ receiptLineItems.map((lineItem) => ({+ ...lineItem,+ receiptId: id+ }))+ )+ .execute();++ return { id };+ });++ return result;+ }+ case "receiptFromSalesReturnOrder": {+ const {+ salesReturnOrderId,+ receiptId: existingReceiptId,+ locationId: userLocationId+ } = payload;++ createDocumentLogger.info({+ function: "create",+ type,+ companyId,+ salesReturnOrderId,+ existingReceiptId,+ userId+ });++ const [salesReturnOrder, salesReturnOrderLines, receipt] = await inOrder([+ () =>+ single(db, "salesReturnOrder", {+ id: salesReturnOrderId,+ companyId+ }),+ () =>+ many(db, "salesReturnOrderLine", {+ salesReturnOrderId,+ companyId+ }),+ () => maybeSingle(db, "receipt", { companyId, id: existingReceiptId! })+ ]);++ if (!salesReturnOrder.data)+ throw new NotFoundError("Sales return order not found");+ if (salesReturnOrder.data.status !== "To Receive")+ throw new Error(+ `Cannot receive against a return order in ${salesReturnOrder.data.status} status`+ );+ if (salesReturnOrderLines.error)+ throw new Error(salesReturnOrderLines.error.message);++ const locationId =+ userLocationId ?? salesReturnOrder.data.locationId ?? null;+ if (!locationId)+ throw new Error(+ "The return order has no receiving location — set one before creating a receipt"+ );++ const returnItemIds = salesReturnOrderLines.data+ .map((d) => d.itemId)+ .filter(Boolean) as string[];+ const items = await many(+ db,+ "item",+ { companyId, id: returnItemIds },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ const pickMethods = await many(+ db,+ "pickMethod",+ { companyId, itemId: returnItemIds },+ { columns: ["itemId", "locationId", "defaultStorageUnitId"] }+ );+ const defaultStorageUnitByItem = new Map<string, string>();+ for (const row of pickMethods.data ?? []) {+ if (row.defaultStorageUnitId && row.locationId === locationId) {+ defaultStorageUnitByItem.set(row.itemId, row.defaultStorageUnitId);+ }+ }++ // A supplied id that is not this company's receipt is a 404, not a+ // silent create-new.+ if (existingReceiptId && !receipt.data)+ throw new NotFoundError("Receipt not found");+ const hasReceipt = !!receipt.data?.id;+ // Re-targeting deletes and rebuilds the lines — only a Draft may be+ // rebuilt; a Posted document's lines are referenced by ledger rows.+ if (hasReceipt && receipt.data!.status !== "Draft")+ throw new Error(`Cannot re-source a ${receipt.data!.status} receipt`);+++ const startAtZero = await receiptQuantitiesStartAtZero(db, companyId);+++ const receiptLineItems = salesReturnOrderLines.data.reduce<+ ReceiptLineItem[]+ >((acc, d) => {+ if (!d.itemId || !d.quantity || d.closedComplete) return acc;++ const outstanding = Math.max(+ 0,+ (d.quantity ?? 0) - (d.quantityReceived ?? 0)+ );+ if (outstanding === 0) return acc;++ acc.push({+ lineId: d.id,+ itemId: d.itemId,+ locationId,+ storageUnitId: defaultStorageUnitByItem.get(d.itemId) ?? null,+ requiresSerialTracking: serializedItems.has(d.itemId),+ requiresBatchTracking: batchItems.has(d.itemId),- receivedQuantity: outstanding,++ receivedQuantity: startAtZero ? 0 : outstanding,+ outstandingQuantity: outstanding,+ // Cost is resolved at posting (original outbound cost / current /+ // zero-value reason) — never the line's credit-basis unitPrice.+ unitPrice: 0,+ conversionFactor: 1,+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",+ companyId,+ createdBy: userId,+ orderQuantity: d.quantity ?? 0+ });++ return acc;+ }, []);++ if (receiptLineItems.length === 0) {+ throw new Error("No lines to receive");+ }++ const result = await db.transaction().execute(async (trx) => {+ const receiptId = await getNextSequence(trx, "receipt", companyId);++ let id: string;+ if (hasReceipt) {+ id = receipt.data!.id;+ await trx+ .updateTable("receipt")+ .set({+ sourceDocument: "Sales Return Order",+ sourceDocumentId: salesReturnOrderId,+ sourceDocumentReadableId:+ salesReturnOrder.data.salesReturnOrderId,+ locationId,+ updatedBy: userId+ })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const insertReceipt = await trx+ .insertInto("receipt")+ .values({+ receiptId,+ sourceDocument: "Sales Return Order",+ sourceDocumentId: salesReturnOrderId,+ sourceDocumentReadableId:+ salesReturnOrder.data.salesReturnOrderId,+ locationId,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ id = insertReceipt[0]?.id ?? "";+ }++ await trx+ .deleteFrom("receiptLine")+ .where("receiptId", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .insertInto("receiptLine")+ .values(+ receiptLineItems.map((lineItem) => ({+ ...lineItem,+ receiptId: id+ }))+ )+ .execute();++ return { id };+ });++ return result;+ }+ case "receiptFromWarehouseTransfer": {+ const { warehouseTransferId, receiptId: existingReceiptId } = payload;++ createDocumentLogger.info({+ type,+ companyId,+ warehouseTransferId,+ existingReceiptId,+ userId+ });++ const [warehouseTransfer, warehouseTransferLines, receipt] =+ await inOrder([+ () =>+ single(db, "warehouseTransfer", {+ companyId,+ id: warehouseTransferId+ }),+ () =>+ many(db, "warehouseTransferLine", {+ companyId,+ transferId: warehouseTransferId+ }),+ () =>+ maybeSingle(db, "receipt", { companyId, id: existingReceiptId! })+ ]);++ if (!warehouseTransfer.data)+ throw new NotFoundError("Warehouse transfer not found");+ if (warehouseTransferLines.error)+ throw new Error(warehouseTransferLines.error.message);++ const locationId = warehouseTransfer.data.toLocationId;++ const items = await many(+ db,+ "item",+ {+ companyId,+ id: warehouseTransferLines.data+ .map((d) => d.itemId)+ .filter(Boolean) as string[]+ },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ // A supplied id that is not this company's receipt is a 404, not a+ // silent create-new.+ if (existingReceiptId && !receipt.data)+ throw new NotFoundError("Receipt not found");+ const hasReceipt = !!receipt.data?.id;++ const previouslyReceivedQuantitiesByLine = (+ warehouseTransferLines.data ?? []+ ).reduce<Record<string, number>>((acc, d) => {+ if (d.id) acc[d.id] = d.receivedQuantity ?? 0;+ return acc;+ }, {});+++ const startAtZero = await receiptQuantitiesStartAtZero(db, companyId);+++ const receiptLineItems = warehouseTransferLines.data.reduce<+ ReceiptLineItem[]+ >((acc, d) => {+ if (!d.itemId || !d.quantity) return acc;++ const serialTracking = serializedItems.has(d.itemId);+ const batchTracking = batchItems.has(d.itemId);+ const quantityToReceive = Math.max(+ 0,+ (d.shippedQuantity ?? 0) -+ (previouslyReceivedQuantitiesByLine[d.id] ?? 0)+ );++ if (quantityToReceive === 0) return acc;++ acc.push({+ lineId: d.id,+ itemId: d.itemId,+ locationId: d.toLocationId ?? locationId,+ storageUnitId: d.toStorageUnitId,+ requiresSerialTracking: serialTracking,+ requiresBatchTracking: batchTracking,- receivedQuantity: quantityToReceive,++ receivedQuantity: startAtZero ? 0 : quantityToReceive,+ outstandingQuantity: quantityToReceive,+ unitPrice: 0, // Transfers don't have a unit price+ conversionFactor: 1,+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",+ companyId,+ createdBy: userId,+ orderQuantity: d.quantity ?? 0+ });++ return acc;+ }, []);++ if (receiptLineItems.length === 0) {+ throw new Error("No lines to receive");+ }++ const result = await db.transaction().execute(async (trx) => {+ const receiptId = await getNextSequence(trx, "receipt", companyId);++ let id: string;+ if (hasReceipt) {+ id = receipt.data!.id;+ await trx+ .updateTable("receipt")+ .set({+ sourceDocument: "Inbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data.transferId,+ locationId,+ updatedBy: userId+ })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const insertReceipt = await trx+ .insertInto("receipt")+ .values({+ receiptId,+ sourceDocument: "Inbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data.transferId,+ locationId,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ id = insertReceipt[0]?.id ?? "";+ }++ await trx+ .insertInto("receiptLine")+ .values(+ receiptLineItems.map((d) => ({+ receiptId: id,+ lineId: d.lineId,+ itemId: d.itemId,+ locationId: d.locationId,+ storageUnitId: d.storageUnitId,+ requiresSerialTracking: d.requiresSerialTracking,+ requiresBatchTracking: d.requiresBatchTracking,+ receivedQuantity: d.receivedQuantity,+ outstandingQuantity: d.outstandingQuantity,+ unitPrice: d.unitPrice,+ conversionFactor: d.conversionFactor,+ unitOfMeasure: d.unitOfMeasure,+ orderQuantity: d.orderQuantity,+ companyId,+ createdBy: userId+ }))+ )+ .execute();++ return { id };+ });++ return result;+ }+ case "receiptLineSplit": {+ const { receiptId, receiptLineId, quantity, locationId } = payload;++ createDocumentLogger.info({+ type,+ locationId,+ receiptId,+ receiptLineId,+ quantity,+ userId+ });++ const [receiptLine, trackedEntities] = await inOrder([+ () => single(db, "receiptLine", { companyId, id: receiptLineId }),+ () =>+ many(db, "trackedEntity", {+ companyId,+ attributes: contains({ "Receipt Line": receiptLineId })+ })+ ]);++ createDocumentLogger.debug({ trackedEntities });++ if (!receiptLine.data) throw new NotFoundError("Receipt line not found");++ await db.transaction().execute(async (trx) => {+ const { id: _id, ...data } = receiptLine.data;++ if (+ receiptLine.data.requiresSerialTracking &&+ trackedEntities.data?.length+ ) {+ // TODO: update the Receipt Line and Index attributes to point to the new line+ await trx+ .deleteFrom("trackedEntity")+ .where("id", "in", trackedEntities.data?.map((d) => d.id) ?? [])+ .where("companyId", "=", companyId)+ .execute();+ }++ const newReceiptLineRows = await trx+ .insertInto("receiptLine")+ .values({+ ...data,+ orderQuantity: quantity,+ outstandingQuantity: quantity,+ receivedQuantity: quantity,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ const newReceiptLineId = newReceiptLineRows[0]?.id;++ await trx+ .updateTable("receiptLine")+ .set({+ orderQuantity: receiptLine.data.orderQuantity - quantity,+ outstandingQuantity:+ receiptLine.data.outstandingQuantity - quantity,+ receivedQuantity: receiptLine.data.receivedQuantity - quantity,+ updatedBy: userId+ })+ .where("id", "=", receiptLineId)+ .where("companyId", "=", companyId)+ .execute();++ // Carry batch tracking onto the new line: clone each existing+ // trackedEntity (batch number + expirationDate + attributes) and+ // shrink the original entity's quantity by the split amount.+ if (+ !receiptLine.data.requiresSerialTracking &&+ newReceiptLineId &&+ trackedEntities.data?.length+ ) {+ for (const entity of trackedEntities.data) {+ const attrs = (entity.attributes ?? {}) as Record<string, unknown>;+ const { "Receipt Line Index": _ignored, ...rest } = attrs;+ const newAttributes = {+ ...rest,+ "Receipt Line": newReceiptLineId+ };++ await trx+ .insertInto("trackedEntity")+ .values({+ id: nanoid(),+ quantity: round(quantity),+ status: entity.status,+ sourceDocument: entity.sourceDocument,+ sourceDocumentId: entity.sourceDocumentId,+ sourceDocumentReadableId: entity.sourceDocumentReadableId,+ readableId: entity.readableId,+ attributes: newAttributes,+ companyId: entity.companyId,+ createdBy: userId,+ itemId: entity.itemId,+ expirationDate: entity.expirationDate+ })+ .execute();++ await trx+ .updateTable("trackedEntity")+ // A parent drained to zero by the split is Consumed, not a+ // zero-quantity Available husk; a Scrapped parent stays so.+ // The Math.max clamp is kept deliberately: a receipt-line+ // split over the parent's quantity has always clamped here+ // rather than refused, and that is not this change to make.+ .set(+ settleQuantity({+ quantity: Math.max(0, (entity.quantity ?? 0) - quantity),+ status: entity.status+ })+ )+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }+ });++ return { id: receiptLineId };+ }+ case "shipmentDefault": {+ let createdDocumentId;+ const { locationId } = payload;+ createDocumentLogger.info({ type, companyId, locationId, userId });+ const effectiveLocationId =+ locationId ?? (await getFallbackLocationId(db, companyId, userId));++ const id = await db.transaction().execute(async (trx) => {+ createdDocumentId = await getNextSequence(trx, "shipment", companyId);++ const newShipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId: createdDocumentId,+ companyId: companyId,+ locationId: effectiveLocationId,+ createdBy: userId+ })+ .returning(["id", "shipmentId"])+ .execute();++ createdDocumentId = newShipment?.[0]?.id;+ if (!createdDocumentId) throw new Error("Failed to create shipment");+ return createdDocumentId;+ });++ return { id };+ }+ case "shipmentFromWarehouseTransfer": {+ const { warehouseTransferId, shipmentId: existingShipmentId } = payload;++ createDocumentLogger.info({+ type,+ companyId,+ warehouseTransferId,+ existingShipmentId,+ userId+ });++ const [warehouseTransfer, warehouseTransferLines, shipment] =+ await inOrder([+ () =>+ single(db, "warehouseTransfer", {+ companyId,+ id: warehouseTransferId+ }),+ () =>+ many(db, "warehouseTransferLine", {+ companyId,+ transferId: warehouseTransferId+ }),+ () =>+ maybeSingle(db, "shipment", {+ companyId,+ id: existingShipmentId!+ })+ ]);++ if (!warehouseTransfer.data)+ throw new NotFoundError("Warehouse transfer not found");+ if (warehouseTransferLines.error)+ throw new Error(warehouseTransferLines.error.message);++ const locationId = warehouseTransfer.data.toLocationId;++ const items = await many(+ db,+ "item",+ {+ companyId,+ id: warehouseTransferLines.data+ .map((d) => d.itemId)+ .filter(Boolean) as string[]+ },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ // A supplied id that is not this company's shipment is a 404, not a+ // silent create-new.+ if (existingShipmentId && !shipment.data)+ throw new NotFoundError("Shipment not found");+ const hasShipment = !!shipment.data?.id;++ const previouslyShippedQuantitiesByLine = (+ warehouseTransferLines.data ?? []+ ).reduce<Record<string, number>>((acc, d) => {+ if (d.id) acc[d.id] = d.shippedQuantity ?? 0;+ return acc;+ }, {});++ const shipmentLineItems = warehouseTransferLines.data.reduce<+ ShipmentLineItem[]+ >((acc, d) => {+ if (!d.itemId || !d.quantity) return acc;++ const serialTracking = serializedItems.has(d.itemId);+ const batchTracking = batchItems.has(d.itemId);+ // For unshipped lines, we want all lines where shippedQuantity < quantity+ const quantityToShip = Math.max(+ 0,+ (d.quantity ?? 0) - (previouslyShippedQuantitiesByLine[d.id] ?? 0)+ );++ if (quantityToShip === 0) return acc;++ acc.push({+ lineId: d.id,+ itemId: d.itemId,+ locationId: d.fromLocationId ?? locationId,+ storageUnitId: d.fromStorageUnitId,+ requiresSerialTracking: serialTracking,+ requiresBatchTracking: batchTracking,+ shippedQuantity: quantityToShip,+ outstandingQuantity: quantityToShip,+ unitPrice: 0, // Transfers don't have a unit price+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",+ companyId,+ createdBy: userId,+ orderQuantity: d.quantity ?? 0+ });++ return acc;+ }, []);++ if (shipmentLineItems.length === 0) {+ throw new Error("No lines to ship");+ }++ const result = await db.transaction().execute(async (trx) => {+ const shipmentId = await getNextSequence(trx, "shipment", companyId);++ let id: string;+ if (hasShipment) {+ id = shipment.data!.id;+ await trx+ .updateTable("shipment")+ .set({+ sourceDocument: "Outbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data.transferId,+ locationId,+ updatedBy: userId+ })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const insertShipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId,+ sourceDocument: "Outbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data.transferId,+ locationId,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ id = insertShipment[0]?.id ?? "";+ }++ await trx+ .deleteFrom("shipmentLine")+ .where("shipmentId", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .insertInto("shipmentLine")+ .values(+ shipmentLineItems.map((lineItem) => ({+ ...lineItem,+ shipmentId: id+ }))+ )+ .execute();++ return { id };+ });++ return result;+ }+ case "shipmentFromSalesReturnOrder": {+ // Return-to-customer shipment: ships back RECEIVED quantity on lines+ // dispositioned "Return to Customer", minus what earlier posted+ // shipments of this source already sent back.+ const {+ salesReturnOrderId,+ shipmentId: existingShipmentId,+ locationId: userLocationId+ } = payload;++ createDocumentLogger.info({+ function: "create",+ type,+ companyId,+ salesReturnOrderId,+ existingShipmentId,+ userId+ });++ const [salesReturnOrder, salesReturnOrderLines, shipment] = await inOrder(+ [+ () =>+ single(db, "salesReturnOrder", {+ id: salesReturnOrderId,+ companyId+ }),+ () =>+ many(db, "salesReturnOrderLine", {+ salesReturnOrderId,+ companyId+ }),+ () =>+ maybeSingle(db, "shipment", {+ companyId,+ id: existingShipmentId!+ })+ ]+ );++ if (!salesReturnOrder.data)+ throw new NotFoundError("Sales return order not found");+ if (salesReturnOrderLines.error)+ throw new Error(salesReturnOrderLines.error.message);+ // Goods can only go back out once they came in: the return must be+ // confirmed (To Receive) or already Completed — never Draft/Cancelled.+ if (!["To Receive", "Completed"].includes(salesReturnOrder.data.status))+ throw new Error(+ `Cannot create a shipment for a ${salesReturnOrder.data.status} return order`+ );++ const locationId =+ userLocationId ?? salesReturnOrder.data.locationId ?? null;+ if (!locationId) throw new Error("The return order has no location");++ const returnLines = salesReturnOrderLines.data.filter(+ (d) => d.disposition === "Return to Customer"+ );+ if (returnLines.length === 0)+ throw new Error('No lines are dispositioned "Return to Customer"');++ // Quantity already shipped back by earlier posted shipments+ const priorShipments = await many(+ db,+ "shipment",+ {+ sourceDocumentId: salesReturnOrderId,+ sourceDocument: "Sales Return Order",+ status: "Posted",+ companyId+ },+ { columns: ["id"] }+ );+ const priorShipmentIds = (priorShipments.data ?? []).map((d) => d.id);+ const shippedBackByLine = new Map<string, number>();+ if (priorShipmentIds.length > 0) {+ const priorLines = await many(+ db,+ "shipmentLine",+ { companyId, shipmentId: priorShipmentIds },+ { columns: ["lineId", "shippedQuantity"] }+ );+ for (const line of priorLines.data ?? []) {+ if (!line.lineId) continue;+ shippedBackByLine.set(+ line.lineId,+ (shippedBackByLine.get(line.lineId) ?? 0) ++ (line.shippedQuantity ?? 0)+ );+ }+ }++ const returnItemIds = returnLines+ .map((d) => d.itemId)+ .filter(Boolean) as string[];+ const items = await many(+ db,+ "item",+ { companyId, id: returnItemIds },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ // A supplied id that is not this company's shipment is a 404, not a+ // silent create-new.+ if (existingShipmentId && !shipment.data)+ throw new NotFoundError("Shipment not found");+ const hasShipment = !!shipment.data?.id;+ if (hasShipment && shipment.data!.status !== "Draft")+ throw new Error(`Cannot re-source a ${shipment.data!.status} shipment`);++ const shipmentLineItems = returnLines.reduce<ShipmentLineItem[]>(+ (acc, d) => {+ if (!d.itemId) return acc;+ const outstanding = Math.max(+ 0,+ (d.quantityReceived ?? 0) - (shippedBackByLine.get(d.id) ?? 0)+ );+ if (outstanding === 0) return acc;++ acc.push({+ lineId: d.id,+ itemId: d.itemId,+ locationId,+ requiresSerialTracking: serializedItems.has(d.itemId),+ requiresBatchTracking: batchItems.has(d.itemId),+ shippedQuantity: outstanding,+ outstandingQuantity: outstanding,+ orderQuantity: d.quantityReceived ?? 0,+ // No revenue on a rejected-claim return+ unitPrice: 0,+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",+ companyId,+ createdBy: userId+ });+ return acc;+ },+ []+ );++ if (shipmentLineItems.length === 0) {+ throw new Error("No quantity remains to ship back");+ }++ const result = await db.transaction().execute(async (trx) => {+ const shipmentId = await getNextSequence(trx, "shipment", companyId);++ let id: string;+ if (hasShipment) {+ id = shipment.data!.id;+ await trx+ .updateTable("shipment")+ .set({+ sourceDocument: "Sales Return Order",+ sourceDocumentId: salesReturnOrderId,+ sourceDocumentReadableId:+ salesReturnOrder.data.salesReturnOrderId,+ customerId: salesReturnOrder.data.customerId,+ locationId,+ updatedBy: userId+ })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const insertShipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId,+ sourceDocument: "Sales Return Order",+ sourceDocumentId: salesReturnOrderId,+ sourceDocumentReadableId:+ salesReturnOrder.data.salesReturnOrderId,+ customerId: salesReturnOrder.data.customerId,+ locationId,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ id = insertShipment[0]?.id ?? "";+ }++ await trx+ .deleteFrom("shipmentLine")+ .where("shipmentId", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .insertInto("shipmentLine")+ .values(+ shipmentLineItems.map((lineItem) => ({+ ...lineItem,+ shipmentId: id+ }))+ )+ .execute();++ return { id };+ });++ return result;+ }+ case "shipmentFromPurchaseReturnOrder": {+ // Supplier return shipment: open (not short-closed) return lines,+ // quantity minus already shipped. Quantities are inventory units.+ const {+ purchaseReturnOrderId,+ shipmentId: existingShipmentId,+ locationId: userLocationId+ } = payload;++ createDocumentLogger.info({+ function: "create",+ type,+ companyId,+ purchaseReturnOrderId,+ existingShipmentId,+ userId+ });++ const [purchaseReturnOrder, purchaseReturnOrderLines, shipment] =+ await inOrder([+ () =>+ single(db, "purchaseReturnOrder", {+ id: purchaseReturnOrderId,+ companyId+ }),+ () =>+ many(db, "purchaseReturnOrderLine", {+ purchaseReturnOrderId,+ companyId+ }),+ () =>+ maybeSingle(db, "shipment", {+ companyId,+ id: existingShipmentId!+ })+ ]);++ if (!purchaseReturnOrder.data)+ throw new NotFoundError("Purchase return order not found");+ if (purchaseReturnOrder.data.status !== "To Ship")+ throw new Error(+ `Cannot ship against a return order in ${purchaseReturnOrder.data.status} status`+ );+ if (purchaseReturnOrderLines.error)+ throw new Error(purchaseReturnOrderLines.error.message);++ const locationId =+ userLocationId ?? purchaseReturnOrder.data.locationId ?? null;+ if (!locationId) throw new Error("The return order has no location");++ const returnItemIds = purchaseReturnOrderLines.data+ .map((d) => d.itemId)+ .filter(Boolean) as string[];+ const items = await many(+ db,+ "item",+ { companyId, id: returnItemIds },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ // A supplied id that is not this company's shipment is a 404, not a+ // silent create-new.+ if (existingShipmentId && !shipment.data)+ throw new NotFoundError("Shipment not found");+ const hasShipment = !!shipment.data?.id;+ if (hasShipment && shipment.data!.status !== "Draft")+ throw new Error(`Cannot re-source a ${shipment.data!.status} shipment`);++ const shipmentLineItems = purchaseReturnOrderLines.data.reduce<+ ShipmentLineItem[]+ >((acc, d) => {+ if (!d.itemId || d.closedComplete) return acc;+ const outstanding = Math.max(+ 0,+ (d.quantity ?? 0) - (d.quantityShipped ?? 0)+ );+ if (outstanding === 0) return acc;++ acc.push({+ lineId: d.id,+ itemId: d.itemId,+ locationId,+ requiresSerialTracking: serializedItems.has(d.itemId),+ requiresBatchTracking: batchItems.has(d.itemId),+ shippedQuantity: outstanding,+ outstandingQuantity: outstanding,+ orderQuantity: d.quantity ?? 0,+ unitPrice: d.unitPrice ?? 0,+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",+ companyId,+ createdBy: userId+ });+ return acc;+ }, []);++ if (shipmentLineItems.length === 0) {+ throw new Error("No lines to ship");+ }++ // Carry the batches/serials picked on each return line onto the+ // shipment's tracked entities, so the shipment already knows what to+ // send back (post-shipment reads entities via attributes ->> Shipment).+ const returnLineIds = purchaseReturnOrderLines.data.map((l) => l.id);+ const lineTrackedEntities = await many<+ "purchaseReturnOrderLineTrackedEntity",+ Pick<+ rowsModule.Tables["purchaseReturnOrderLineTrackedEntity"]["Row"],+ "purchaseReturnOrderLineId"+ > & {+ trackedEntity: Pick<+ rowsModule.Tables["trackedEntity"]["Row"],+ "id" | "attributes"+ > | null;+ }+ >(+ db,+ "purchaseReturnOrderLineTrackedEntity",+ { purchaseReturnOrderLineId: returnLineIds, companyId },+ {+ columns: ["purchaseReturnOrderLineId"],+ embed: {+ trackedEntity: {+ table: "trackedEntity",+ via: "trackedEntityId",+ columns: ["id", "attributes"]+ }+ }+ }+ );+ if (lineTrackedEntities.error)+ throw new Error(lineTrackedEntities.error.message);++ const entitiesByReturnLine = new Map<+ string,+ { id: string; attributes: Record<string, unknown> | null }[]+ >();+ for (const row of lineTrackedEntities.data ?? []) {+ const entity = row.trackedEntity;+ if (!entity) continue;+ const list =+ entitiesByReturnLine.get(row.purchaseReturnOrderLineId) ?? [];+ list.push({+ id: entity.id,+ attributes: entity.attributes as Record<string, unknown> | null+ });+ entitiesByReturnLine.set(row.purchaseReturnOrderLineId, list);+ }++ // Re-source path: clear the shipment tag off any entity previously+ // stamped for this shipment before re-stamping the current selection.+ const staleEntities = hasShipment+ ? await many(+ db,+ "trackedEntity",+ {+ companyId,+ attributes: contains({ Shipment: shipment.data!.id })+ },+ { columns: ["id", "attributes"] }+ )+ : { data: [], error: null };+ if (staleEntities.error) throw new Error(staleEntities.error.message);++ const result = await db.transaction().execute(async (trx) => {+ const shipmentId = await getNextSequence(trx, "shipment", companyId);++ let id: string;+ if (hasShipment) {+ id = shipment.data!.id;+ await trx+ .updateTable("shipment")+ .set({+ sourceDocument: "Purchase Return Order",+ sourceDocumentId: purchaseReturnOrderId,+ sourceDocumentReadableId:+ purchaseReturnOrder.data.purchaseReturnOrderId,+ supplierId: purchaseReturnOrder.data.supplierId,+ locationId,+ updatedBy: userId+ })+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const insertShipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId,+ sourceDocument: "Purchase Return Order",+ sourceDocumentId: purchaseReturnOrderId,+ sourceDocumentReadableId:+ purchaseReturnOrder.data.purchaseReturnOrderId,+ supplierId: purchaseReturnOrder.data.supplierId,+ locationId,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ id = insertShipment[0]?.id ?? "";+ }++ await trx+ .deleteFrom("shipmentLine")+ .where("shipmentId", "=", id)+ .where("companyId", "=", companyId)+ .execute();++ const insertedLines = await trx+ .insertInto("shipmentLine")+ .values(+ shipmentLineItems.map((lineItem) => ({+ ...lineItem,+ shipmentId: id+ }))+ )+ .returning(["id", "lineId"])+ .execute();++ // Strip the shipment tag off entities left over from a prior source.+ for (const entity of staleEntities.data ?? []) {+ const attrs = {+ ...((entity.attributes as Record<string, unknown> | null) ?? {})+ };+ delete attrs.Shipment;+ delete attrs["Shipment Line"];+ delete attrs["Shipment Line Index"];+ await trx+ .updateTable("trackedEntity")+ .set({ attributes: attrs as Json })+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();+ }++ // Stamp each return line's picked entities onto its shipment line, so+ // the batch/serial flows through to posting. post-shipment splits a+ // batch when the shipped quantity is less than the entity's quantity.+ for (const shipmentLine of insertedLines) {+ const entities = shipmentLine.lineId+ ? entitiesByReturnLine.get(shipmentLine.lineId)+ : undefined;+ for (const entity of entities ?? []) {+ const attrs = {+ ...(entity.attributes ?? {}),+ Shipment: id,+ "Shipment Line": shipmentLine.id+ };+ await trx+ .updateTable("trackedEntity")+ .set({ attributes: attrs as Json })+ .where("id", "=", entity.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ return { id };+ });++ return result;+ }+ case "shipmentFromPurchaseOrder": {+ const {+ purchaseOrderId,+ shipmentId: existingShipmentId,+ locationId+ } = payload;++ createDocumentLogger.info({+ type,+ companyId,+ locationId,+ purchaseOrderId,+ existingShipmentId,+ userId+ });++ const [+ purchaseOrder,+ purchaseOrderLines,+ purchaseOrderDelivery,+ shipment+ ] = await inOrder([+ () => single(db, "purchaseOrder", { companyId, id: purchaseOrderId }),+ () =>+ many(db, "purchaseOrderLine", {+ companyId,+ purchaseOrderId,+ purchaseOrderLineType: [+ "Part",+ "Material",+ "Tool",+ "Fixture",+ "Consumable"+ ],+ locationId+ }),+ () =>+ maybeSingle(db, "purchaseOrderDelivery", {+ companyId,+ id: purchaseOrderId+ }),+ () =>+ maybeSingle(db, "shipment", { companyId, id: existingShipmentId! })+ ]);++ if (!purchaseOrder.data)+ throw new NotFoundError("Purchase order not found");+ if (purchaseOrderLines.error)+ throw new Error(purchaseOrderLines.error.message);++ const items = await many(+ db,+ "item",+ {+ companyId,+ id: purchaseOrderLines.data.map((d) => d.itemId) as string[]+ },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ // A supplied id that is not this company's shipment is a 404, not a+ // silent create-new.+ if (existingShipmentId && !shipment.data)+ throw new NotFoundError("Shipment not found");+ const hasShipment = !!shipment.data?.id;+ const isOutsideOperation =+ purchaseOrder.data.purchaseOrderType === "Outside Processing";++ const previouslyShippedQuantitiesByLine = (+ purchaseOrderLines.data ?? []+ ).reduce<Record<string, number>>((acc, d) => {+ if (d.id) acc[d.id] = d.quantityShipped ?? 0;+ return acc;+ }, {});++ let shipmentId = hasShipment ? shipment.data?.id! : "";+ let shipmentIdReadable = hasShipment ? shipment.data?.shipmentId! : "";++ await db.transaction().execute(async (trx) => {+ if (hasShipment) {+ // update existing shipment+ await trx+ .updateTable("shipment")+ .set({+ sourceDocument: "Purchase Order",+ sourceDocumentId: purchaseOrder.data.id,+ sourceDocumentReadableId: purchaseOrder.data.purchaseOrderId,+ supplierId: purchaseOrder.data.supplierId,+ supplierInteractionId: purchaseOrder.data.supplierInteractionId,+ shippingMethodId: purchaseOrderDelivery.data?.shippingMethodId,+ locationId: locationId,+ updatedBy: userId+ })+ .where("id", "=", shipmentId)+ .returning(["id", "shipmentId"])+ .where("companyId", "=", companyId)+ .execute();+ // delete existing shipment lines+ await trx+ .deleteFrom("shipmentLine")+ .where("shipmentId", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ shipmentIdReadable = await getNextSequence(+ trx,+ "shipment",+ companyId+ );++ const newShipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId: shipmentIdReadable,+ sourceDocument: "Purchase Order",+ sourceDocumentId: purchaseOrder.data.id,+ sourceDocumentReadableId: purchaseOrder.data.purchaseOrderId,+ externalDocumentId: purchaseOrder.data.supplierReference,+ supplierId: purchaseOrder.data.supplierId,+ supplierInteractionId: purchaseOrder.data.supplierInteractionId,+ shippingMethodId: purchaseOrderDelivery.data?.shippingMethodId,+ companyId: companyId,+ locationId: locationId,+ createdBy: userId+ })+ .returning(["id", "shipmentId"])+ .execute();++ shipmentId = newShipment?.[0]?.id!;+ shipmentIdReadable = newShipment?.[0]?.shipmentId!;+ }++ // Process each sales order line+ for await (const purchaseOrderLine of purchaseOrderLines.data) {+ if (+ !purchaseOrderLine.itemId ||+ !purchaseOrderLine.purchaseQuantity ||+ purchaseOrderLine.purchaseOrderLineType === "Service" ||+ purchaseOrderLine.purchaseOrderLineType === "G/L Account"+ ) {+ continue;+ }++ const isSerial = serializedItems.has(purchaseOrderLine.itemId);+ const isBatch = batchItems.has(purchaseOrderLine.itemId);++ const outstandingQuantity =+ (purchaseOrderLine.purchaseQuantity ?? 0) -+ (previouslyShippedQuantitiesByLine[purchaseOrderLine.id] ?? 0);++ const shippingAndTaxUnitCost =+ ((purchaseOrderLine.shippingCost ?? 0) /+ (purchaseOrderLine.purchaseQuantity ?? 0) ++ (purchaseOrderLine.unitPrice ?? 0)) *+ (1 + (purchaseOrderLine.taxPercent ?? 0));++ await trx+ .insertInto("shipmentLine")+ .values({+ shipmentId: shipmentId,+ lineId: purchaseOrderLine.id,+ companyId: companyId,+ itemId: purchaseOrderLine.itemId,+ orderQuantity: purchaseOrderLine.purchaseQuantity,+ outstandingQuantity: outstandingQuantity,+ shippedQuantity: outstandingQuantity ?? 0,+ requiresSerialTracking: isSerial && !isOutsideOperation,+ requiresBatchTracking: isBatch && !isOutsideOperation,+ unitPrice: shippingAndTaxUnitCost,+ unitOfMeasure:+ purchaseOrderLine.purchaseUnitOfMeasureCode ?? "EA",+ locationId: purchaseOrderLine.locationId,+ storageUnitId: purchaseOrderLine.storageUnitId,+ createdBy: userId ?? ""+ })+ .execute();+ }+ });++ return { id: shipmentId };+ }+ case "shipmentFromSalesOrder": {+ const {+ salesOrderId,+ shipmentId: existingShipmentId,+ locationId+ } = payload;++ createDocumentLogger.info({+ type,+ companyId,+ locationId,+ salesOrderId,+ existingShipmentId,+ userId+ });++ const [+ salesOrder,+ salesOrderLines,+ fixedAssetSoLines,+ salesOrderShipment,+ shipment,+ jobs+ ] = await inOrder([+ () => single(db, "salesOrder", { id: salesOrderId, companyId }),+ () =>+ many(db, "salesOrderLine", {+ companyId,+ salesOrderId,+ salesOrderLineType: [+ "Part",+ "Material",+ "Tool",+ "Fixture",+ "Consumable"+ ],+ locationId+ }),+ () =>+ many(+ db,+ "salesOrderLine",+ { companyId, salesOrderId, salesOrderLineType: "Fixed Asset" },+ {+ columns: [+ "id",+ "salesOrderLineType",+ "assetId",+ "saleQuantity",+ "quantitySent",+ "sentComplete"+ ]+ }+ ),+ () =>+ maybeSingle(db, "salesOrderShipment", {+ companyId,+ id: salesOrderId+ }),+ () =>+ maybeSingle(db, "shipment", { companyId, id: existingShipmentId! }),+ () =>+ many(db, "job", {+ companyId,+ salesOrderId,+ status: neq("Cancelled")+ })+ ]);++ if (!salesOrder.data) throw new NotFoundError("Sales order not found");+ if (salesOrderLines.error) throw new Error(salesOrderLines.error.message);++ const items = await many(+ db,+ "item",+ {+ companyId,+ id: salesOrderLines.data.map((d) => d.itemId) as string[]+ },+ { columns: ["id", "itemTrackingType"] }+ );+ const serializedItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Serial")+ .map((d) => d.id)+ );+ const batchItems = new Set(+ items.data+ ?.filter((d) => d.itemTrackingType === "Batch")+ .map((d) => d.id)+ );++ // A supplied id that is not this company's shipment is a 404, not a+ // silent create-new.+ if (existingShipmentId && !shipment.data)+ throw new NotFoundError("Shipment not found");+ const hasShipment = !!shipment.data?.id;++ // Group jobs by sales order line ID+ const jobsBySalesOrderLine = (jobs.data || []).reduce<+ Record<string, Database["public"]["Tables"]["job"]["Row"][]>+ >((acc, job) => {+ if (job.salesOrderLineId) {+ if (!acc[job.salesOrderLineId]) {+ acc[job.salesOrderLineId] = [];+ }+ acc[job.salesOrderLineId]!.push(job);+ }+ return acc;+ }, {});++ const previouslyShippedQuantitiesByLine = (+ salesOrderLines.data ?? []+ ).reduce<Record<string, number>>((acc, d) => {+ if (d.id) acc[d.id] = d.quantitySent ?? 0;+ return acc;+ }, {});++ let shipmentId = hasShipment ? shipment.data?.id! : "";+ let shipmentIdReadable = hasShipment ? shipment.data?.shipmentId! : "";++ await db.transaction().execute(async (trx) => {+ if (hasShipment) {+ // update existing shipment+ await trx+ .updateTable("shipment")+ .set({+ sourceDocument: "Sales Order",+ sourceDocumentId: salesOrder.data.id,+ sourceDocumentReadableId: salesOrder.data.salesOrderId,+ customerId: salesOrder.data.customerId,+ shippingMethodId: salesOrderShipment.data?.shippingMethodId,+ opportunityId: salesOrder.data.opportunityId,+ locationId: locationId,+ updatedBy: userId+ })+ .where("id", "=", shipmentId)+ .returning(["id", "shipmentId"])+ .where("companyId", "=", companyId)+ .execute();+ // delete existing shipment lines+ await trx+ .deleteFrom("shipmentLine")+ .where("shipmentId", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ shipmentIdReadable = await getNextSequence(+ trx,+ "shipment",+ companyId+ );++ const newShipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId: shipmentIdReadable,+ sourceDocument: "Sales Order",+ sourceDocumentId: salesOrder.data.id,+ sourceDocumentReadableId: salesOrder.data.salesOrderId,+ externalDocumentId: salesOrder.data.customerReference,+ shippingMethodId: salesOrderShipment.data?.shippingMethodId,+ customerId: salesOrder.data.customerId,+ opportunityId: salesOrder.data.opportunityId,+ companyId: companyId,+ locationId: locationId,+ createdBy: userId+ })+ .returning(["id", "shipmentId"])+ .execute();++ shipmentId = newShipment?.[0]?.id!;+ shipmentIdReadable = newShipment?.[0]?.shipmentId!;+ }++ const shipmentLineItems: ShipmentLineItem[] = [];++ // Process each sales order line+ for await (const salesOrderLine of salesOrderLines.data) {+ if (+ !salesOrderLine.itemId ||+ !salesOrderLine.saleQuantity ||+ salesOrderLine.salesOrderLineType === "Service"+ ) {+ continue;+ }++ const isSerial = serializedItems.has(salesOrderLine.itemId);+ const isBatch = batchItems.has(salesOrderLine.itemId);++ if (salesOrderLine.methodType === "Make to Order") {+ for await (const job of jobsBySalesOrderLine[salesOrderLine.id] ??+ []) {+ if (!salesOrderLine.itemId) return;++ const quantityToShip = Math.max(+ 0,+ (job.quantityComplete ?? 0) - (job.quantityShipped ?? 0)+ );++ if (!isSerial || (isSerial && quantityToShip > 0)) {+ const fulfillment = await trx+ .insertInto("fulfillment")+ .values({+ salesOrderLineId: salesOrderLine.id,+ type: "Job",+ jobId: job.id,+ quantity: quantityToShip,+ companyId: companyId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ const fulfillmentId = fulfillment?.[0]?.id;++ const shippingAndTaxUnitCost =+ (salesOrderLine.shippingCost / quantityToShip ++ (salesOrderLine.unitPrice ?? 0)) *+ (1 + salesOrderLine.taxPercent);++ const shipmentLine = await trx+ .insertInto("shipmentLine")+ .values({+ shipmentId: shipmentId,+ lineId: salesOrderLine.id,+ companyId: companyId,+ fulfillmentId,+ itemId: salesOrderLine.itemId,+ orderQuantity: salesOrderLine.saleQuantity,+ outstandingQuantity:+ salesOrderLine.quantityToSend ??+ salesOrderLine.saleQuantity,+ shippedQuantity: quantityToShip,+ requiresSerialTracking: isSerial,+ requiresBatchTracking: isBatch,+ unitPrice: shippingAndTaxUnitCost,+ unitOfMeasure: salesOrderLine.unitOfMeasureCode ?? "EA",+ createdBy: userId ?? ""+ })+ .returning(["id"])+ .execute();++ const shipmentLineId = shipmentLine?.[0]?.id;++ if (!shipmentLineId)+ throw new NotFoundError("Shipment line not found");++ if (isSerial || isBatch) {+ const jobMakeMethod = await trx+ .selectFrom("jobMakeMethod")+ .select(["id"])+ .where("jobId", "=", job.id)+ .where("parentMaterialId", "is", null)+ .executeTakeFirst();++ if (jobMakeMethod?.id) {+ const trackedEntities = await many(+ trx,+ "trackedEntity",+ {+ companyId,+ attributes: contains({+ "Job Make Method": jobMakeMethod.id+ })+ },+ { orderBy: ["createdAt", "readableId", "id"] }+ );++ let index = 0;+ for await (const trackedEntity of trackedEntities?.data ??+ []) {+ await trx+ .updateTable("trackedEntity")+ .set({+ attributes: {+ ...(trackedEntity.attributes as Record<+ string,+ unknown+ >),+ Shipment: shipmentId,+ "Shipment Line": shipmentLineId,+ "Shipment Line Index": index+ }+ })+ .where("id", "=", trackedEntity.id)+ .where("companyId", "=", companyId)+ .execute();+ index++;+ }+ }+ }+ }+ }+ } else {+ const outstandingQuantity =+ (salesOrderLine.saleQuantity ?? 0) -+ (previouslyShippedQuantitiesByLine[salesOrderLine.id] ?? 0);++ const shippingAndTaxUnitCost =+ (salesOrderLine.shippingCost /+ (salesOrderLine.saleQuantity ?? 0) ++ (salesOrderLine.unitPrice ?? 0)) *+ (1 + salesOrderLine.taxPercent);++ await trx+ .insertInto("shipmentLine")+ .values({+ shipmentId: shipmentId,+ lineId: salesOrderLine.id,+ companyId: companyId,+ itemId: salesOrderLine.itemId,+ orderQuantity: salesOrderLine.saleQuantity,+ outstandingQuantity: outstandingQuantity,+ shippedQuantity: outstandingQuantity ?? 0,+ requiresSerialTracking: isSerial,+ requiresBatchTracking: isBatch,+ unitPrice: shippingAndTaxUnitCost,+ unitOfMeasure: salesOrderLine.unitOfMeasureCode ?? "EA",+ locationId: salesOrderLine.locationId,+ storageUnitId: salesOrderLine.storageUnitId,+ createdBy: userId ?? ""+ })+ .execute();+ }+ }++ if (shipmentLineItems.length > 0) {+ // Insert all shipment lines+ await trx+ .insertInto("shipmentLine")+ .values(+ shipmentLineItems.map((line) => ({+ ...line,+ shipmentId: shipmentId,+ locationId+ }))+ )+ .execute();+ }++ const unshippedFaLines = (fixedAssetSoLines.data ?? []).filter(+ (d) => d.assetId && d.saleQuantity && !d.sentComplete+ );+ if (unshippedFaLines.length > 0) {+ await trx+ .deleteFrom("shipmentFixedAssetLine")+ .where("shipmentId", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ await trx+ .insertInto("shipmentFixedAssetLine")+ .values(+ unshippedFaLines.map((line) => ({+ shipmentId: shipmentId,+ salesOrderLineId: line.id,+ shipped: true,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }+ });++ return { id: shipmentId };+ }+ case "shipmentFromSalesOrderLine": {+ const {+ salesOrderLineId,+ shipmentId: existingShipmentId,+ locationId+ } = payload;++ createDocumentLogger.info({+ type,+ companyId,+ locationId,+ salesOrderLineId,+ existingShipmentId,+ userId+ });++ const salesOrderLine = await single(db, "salesOrderLine", {+ companyId,+ id: salesOrderLineId,+ locationId+ });++ if (!salesOrderLine.data || !salesOrderLine.data.itemId)+ throw new NotFoundError("Sales order line not found");+ // Services are never shipped+ if (salesOrderLine.data.salesOrderLineType === "Service")+ throw new Error("Service lines cannot be shipped");+ const salesOrderId = salesOrderLine.data.salesOrderId;++ const [salesOrder, salesOrderShipment, shipment, jobs] = await inOrder([+ () => single(db, "salesOrder", { companyId, id: salesOrderId }),+ () =>+ maybeSingle(db, "salesOrderShipment", {+ companyId,+ id: salesOrderId+ }),+ () =>+ maybeSingle(db, "shipment", { companyId, id: existingShipmentId! }),+ () =>+ many(db, "job", {+ companyId,+ salesOrderLineId,+ status: neq("Cancelled")+ })+ ]);++ if (!salesOrder.data) throw new NotFoundError("Sales order not found");++ const item = await single(+ db,+ "item",+ { companyId, id: salesOrderLine.data.itemId },+ { columns: ["id", "itemTrackingType"] }+ );++ if (!item.data) throw new NotFoundError("Item not found");++ const isSerial = item.data.itemTrackingType === "Serial";+ const isBatch = item.data.itemTrackingType === "Batch";++ // A supplied id that is not this company's shipment is a 404, not a+ // silent create-new.+ if (existingShipmentId && !shipment.data)+ throw new NotFoundError("Shipment not found");+ const hasShipment = !!shipment.data?.id;+ if (hasShipment && shipment.data!.status !== "Draft")+ throw new Error(`Cannot re-source a ${shipment.data!.status} shipment`);+ const previouslyShippedQuantity = salesOrderLine.data.quantitySent ?? 0;++ let shipmentId = hasShipment ? shipment.data?.id! : "";+ let shipmentIdReadable = hasShipment ? shipment.data?.shipmentId! : "";++ await db.transaction().execute(async (trx) => {+ if (hasShipment) {+ // update existing shipment+ await trx+ .updateTable("shipment")+ .set({+ sourceDocument: "Sales Order",+ sourceDocumentId: salesOrder.data.id,+ sourceDocumentReadableId: salesOrder.data.salesOrderId,+ locationId: locationId,+ updatedBy: userId+ })+ .where("id", "=", shipmentId)+ .returning(["id", "shipmentId"])+ .where("companyId", "=", companyId)+ .execute();+ // delete existing shipment lines+ await trx+ .deleteFrom("shipmentLine")+ .where("shipmentId", "=", shipmentId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ shipmentIdReadable = await getNextSequence(+ trx,+ "shipment",+ companyId+ );++ const newShipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId: shipmentIdReadable,+ sourceDocument: "Sales Order",+ sourceDocumentId: salesOrder.data.id,+ sourceDocumentReadableId: salesOrder.data.salesOrderId,+ externalDocumentId: salesOrder.data.customerReference,+ shippingMethodId: salesOrderShipment.data?.shippingMethodId,+ customerId: salesOrder.data.customerId,+ opportunityId: salesOrder.data.opportunityId,+ companyId: companyId,+ locationId: locationId,+ createdBy: userId+ })+ .returning(["id", "shipmentId"])+ .execute();++ shipmentId = newShipment?.[0]?.id!;+ shipmentIdReadable = newShipment?.[0]?.shipmentId!;+ }++ if (salesOrderLine.data.methodType === "Make to Order") {+ for await (const job of jobs.data ?? []) {+ if (!salesOrderLine.data.itemId) return;+ const quantityToShip = Math.max(+ 0,+ (job.quantityComplete ?? 0) - (job.quantityShipped ?? 0)+ );++ if (!isSerial || (isSerial && quantityToShip > 0)) {+ const fulfillment = await trx+ .insertInto("fulfillment")+ .values({+ salesOrderLineId: salesOrderLineId,+ type: "Job",+ jobId: job.id,+ quantity: quantityToShip,+ companyId: companyId,+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ const fulfillmentId = fulfillment?.[0]?.id;++ const shippingAndTaxUnitCost =+ (salesOrderLine.data.shippingCost / quantityToShip ++ (salesOrderLine.data.unitPrice ?? 0)) *+ (1 + salesOrderLine.data.taxPercent);++ const shipmentLine = await trx+ .insertInto("shipmentLine")+ .values({+ shipmentId: shipmentId,+ lineId: salesOrderLineId,+ companyId: companyId,+ fulfillmentId,+ itemId: salesOrderLine.data.itemId,+ orderQuantity: job.productionQuantity ?? 0,+ outstandingQuantity: Math.max(0, job.productionQuantity ?? 0),+ shippedQuantity: quantityToShip,+ requiresSerialTracking: isSerial,+ requiresBatchTracking: isBatch,+ unitPrice: shippingAndTaxUnitCost,+ unitOfMeasure: salesOrderLine.data.unitOfMeasureCode ?? "EA",+ createdBy: userId ?? ""+ })+ .returning(["id"])+ .execute();++ const shipmentLineId = shipmentLine?.[0]?.id;++ if (!shipmentLineId)+ throw new NotFoundError("Shipment line not found");++ if (isSerial || isBatch) {+ const jobMakeMethod = await trx+ .selectFrom("jobMakeMethod")+ .select(["id"])+ .where("jobId", "=", job.id)+ .where("parentMaterialId", "is", null)+ .executeTakeFirst();++ if (jobMakeMethod?.id) {+ const trackedEntities = await many(+ trx,+ "trackedEntity",+ {+ companyId,+ attributes: contains({+ "Job Make Method": jobMakeMethod.id+ })+ },+ { orderBy: ["createdAt", "readableId", "id"] }+ );++ let index = 0;+ for await (const trackedEntity of trackedEntities?.data ??+ []) {+ await trx+ .updateTable("trackedEntity")+ .set({+ attributes: {+ ...(trackedEntity.attributes as Record<+ string,+ unknown+ >),+ Shipment: shipmentId,+ "Shipment Line": shipmentLineId,+ "Shipment Line Index": index+ }+ })+ .where("id", "=", trackedEntity.id)+ .where("companyId", "=", companyId)+ .execute();+ index++;+ }+ }+ }+ }+ }+ } else {+ const outstandingQuantity = Math.max(+ 0,+ (salesOrderLine.data.saleQuantity ?? 0) - previouslyShippedQuantity+ );++ const shippingAndTaxUnitCost =+ (salesOrderLine.data.shippingCost /+ (salesOrderLine.data.saleQuantity ?? 0) ++ (salesOrderLine.data.unitPrice ?? 0)) *+ (1 + salesOrderLine.data.taxPercent);++ await trx+ .insertInto("shipmentLine")+ .values({+ shipmentId: shipmentId,+ lineId: salesOrderLineId,+ companyId: companyId,+ itemId: salesOrderLine.data.itemId!,+ orderQuantity: salesOrderLine.data.saleQuantity ?? 0,+ outstandingQuantity: outstandingQuantity,+ shippedQuantity: outstandingQuantity,+ requiresSerialTracking: isSerial,+ requiresBatchTracking: isBatch,+ unitPrice: shippingAndTaxUnitCost,+ unitOfMeasure: salesOrderLine.data.unitOfMeasureCode ?? "EA",+ locationId: salesOrderLine.data.locationId!,+ storageUnitId: salesOrderLine.data.storageUnitId!,+ createdBy: userId ?? ""+ })+ .execute();+ }+ });++ return { id: shipmentId };+ }+ case "shipmentLineSplit": {+ const { shipmentId, shipmentLineId, quantity, locationId } = payload;++ createDocumentLogger.info({+ type,+ locationId,+ shipmentId,+ shipmentLineId,+ quantity,+ userId+ });++ const [shipmentLine] = await inOrder([+ () => single(db, "shipmentLine", { companyId, id: shipmentLineId })+ ]);++ if (!shipmentLine.data)+ throw new NotFoundError("Shipment line not found");++ await db.transaction().execute(async (trx) => {+ const { id: _id, ...data } = shipmentLine.data;++ await trx+ .insertInto("shipmentLine")+ .values({+ ...data,+ orderQuantity: quantity,+ outstandingQuantity: quantity,+ shippedQuantity: quantity,+ createdBy: userId+ })+ .execute();++ await trx+ .updateTable("shipmentLine")+ .set({+ orderQuantity: shipmentLine.data.orderQuantity - quantity,+ outstandingQuantity:+ shipmentLine.data.outstandingQuantity - quantity,+ shippedQuantity: shipmentLine.data.shippedQuantity - quantity,+ updatedBy: userId+ })+ .where("id", "=", shipmentLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ return { id: shipmentLineId };+ }+ case "shipmentFromRentalAgreement": {+ // A rental delivery: one Draft shipment per agreement holds the+ // Pending units. A per-unit shortcut adds (or ticks) its unit on it.+ const { rentalAgreementId, rentalAgreementLineId } = payload;++ createDocumentLogger.info({+ function: "create",+ type,+ companyId,+ rentalAgreementId,+ rentalAgreementLineId,+ userId+ });++ return db.transaction().execute(async (trx) => {+ const agreement = await trx+ .selectFrom("rentalAgreement")+ .select([+ "id",+ "rentalAgreementId",+ "status",+ "customerId",+ "locationId"+ ])+ .where("id", "=", rentalAgreementId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!agreement) throw new NotFoundError("Rental agreement not found");+ if (agreement.status !== "Active") {+ throw new InvalidInputError(+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are delivered from an Active agreement`+ );+ }++ const draft = await trx+ .selectFrom("shipment")+ .select("id")+ .where("sourceDocument", "=", "Rental Agreement")+ .where("sourceDocumentId", "=", agreement.id)+ .where("status", "=", "Draft")+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();++ const onOpenShipments = await trx+ .selectFrom("shipmentFixedAssetLine as sfl")+ .innerJoin("shipment as s", (join) =>+ join+ .onRef("s.id", "=", "sfl.shipmentId")+ .onRef("s.companyId", "=", "sfl.companyId")+ )+ .select([+ "sfl.id",+ "sfl.shipmentId",+ "sfl.rentalAgreementLineId",+ "sfl.shipped"+ ])+ .where("s.sourceDocument", "=", "Rental Agreement")+ .where("s.sourceDocumentId", "=", agreement.id)+ .where("s.status", "in", ["Draft", "Pending"])+ .where("sfl.companyId", "=", companyId)+ .execute();++ let candidatesQuery = trx+ .selectFrom("rentalAgreementLine")+ .select(["id", "status"])+ .where("rentalAgreementId", "=", agreement.id)+ .where("companyId", "=", companyId)+ .where("status", "=", "Pending");+ if (rentalAgreementLineId) {+ candidatesQuery = candidatesQuery.where(+ "id",+ "=",+ rentalAgreementLineId+ );+ }+ const candidates = await candidatesQuery.orderBy("id").execute();+ if (rentalAgreementLineId && candidates.length === 0) {+ throw new InvalidInputError("Only a Pending unit can be delivered");+ }++ if (draft) {+ if (!rentalAgreementLineId) return { id: draft.id };+ const onDocument = onOpenShipments.find(+ (row) => row.rentalAgreementLineId === rentalAgreementLineId+ );+ if (onDocument && onDocument.shipmentId !== draft.id) {+ throw new InvalidInputError(+ "The unit is already on an open shipment"+ );+ }+ if (onDocument) {+ if (!onDocument.shipped) {+ await trx+ .updateTable("shipmentFixedAssetLine")+ .set({ shipped: true, updatedBy: userId })+ .where("id", "=", onDocument.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ return { id: draft.id };+ }+ await trx+ .insertInto("shipmentFixedAssetLine")+ .values({+ shipmentId: draft.id,+ rentalAgreementLineId,+ shipped: true,+ companyId,+ createdBy: userId+ })+ .execute();+ return { id: draft.id };+ }++ const onOpenDocument = new Set(+ onOpenShipments.map((row) => row.rentalAgreementLineId)+ );+ const units = candidates.filter((line) => !onOpenDocument.has(line.id));+ if (units.length === 0) {+ throw new InvalidInputError("No units to deliver");+ }++ const header = await trx+ .insertInto("shipment")+ .values({+ shipmentId: await getNextSequence(trx, "shipment", companyId),+ sourceDocument: "Rental Agreement",+ sourceDocumentId: agreement.id,+ sourceDocumentReadableId: agreement.rentalAgreementId,+ customerId: agreement.customerId,+ locationId: agreement.locationId,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ await trx+ .insertInto("shipmentFixedAssetLine")+ .values(+ units.map((line) => ({+ shipmentId: header.id,+ rentalAgreementLineId: line.id,+ shipped: true,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ return { id: header.id };+ });+ }+ case "receiptFromRentalAgreement": {+ // A rental return: one Draft receipt per agreement holds the units+ // that can come back — On Rent ticked, Pending unticked (spec Q8). A+ // per-unit shortcut adds (or ticks) its unit on it.+ const { rentalAgreementId, rentalAgreementLineId } = payload;++ createDocumentLogger.info({+ function: "create",+ type,+ companyId,+ rentalAgreementId,+ rentalAgreementLineId,+ userId+ });++ return db.transaction().execute(async (trx) => {+ const agreement = await trx+ .selectFrom("rentalAgreement")+ .select([+ "id",+ "rentalAgreementId",+ "status",+ "customerId",+ "locationId"+ ])+ .where("id", "=", rentalAgreementId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!agreement) throw new NotFoundError("Rental agreement not found");+ if (agreement.status !== "Active") {+ throw new InvalidInputError(+ `Rental agreement ${agreement.rentalAgreementId} is ${agreement.status}; units are returned from an Active agreement`+ );+ }++ const draft = await trx+ .selectFrom("receipt")+ .select("id")+ .where("sourceDocument", "=", "Rental Agreement")+ .where("sourceDocumentId", "=", agreement.id)+ .where("status", "=", "Draft")+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();++ // Only another open RECEIPT keeps a unit off this one: a Pending+ // unit may sit on an open shipment too, and the first to post wins.+ const onOpenReceipts = await trx+ .selectFrom("receiptFixedAssetLine as rfl")+ .innerJoin("receipt as r", (join) =>+ join+ .onRef("r.id", "=", "rfl.receiptId")+ .onRef("r.companyId", "=", "rfl.companyId")+ )+ .select([+ "rfl.id",+ "rfl.receiptId",+ "rfl.rentalAgreementLineId",+ "rfl.received"+ ])+ .where("r.sourceDocument", "=", "Rental Agreement")+ .where("r.sourceDocumentId", "=", agreement.id)+ .where("r.status", "in", ["Draft", "Pending"])+ .where("rfl.companyId", "=", companyId)+ .execute();++ let candidatesQuery = trx+ .selectFrom("rentalAgreementLine")+ .select(["id", "status"])+ .where("rentalAgreementId", "=", agreement.id)+ .where("companyId", "=", companyId)+ .where("status", "in", ["Pending", "On Rent"]);+ if (rentalAgreementLineId) {+ candidatesQuery = candidatesQuery.where(+ "id",+ "=",+ rentalAgreementLineId+ );+ }+ const candidates = await candidatesQuery.orderBy("id").execute();+ if (rentalAgreementLineId && candidates.length === 0) {+ throw new InvalidInputError(+ "Only a Pending or On Rent unit can be returned"+ );+ }++ if (draft) {+ if (!rentalAgreementLineId) return { id: draft.id };+ const onDocument = onOpenReceipts.find(+ (row) => row.rentalAgreementLineId === rentalAgreementLineId+ );+ if (onDocument && onDocument.receiptId !== draft.id) {+ throw new InvalidInputError(+ "The unit is already on an open receipt"+ );+ }+ if (onDocument) {+ if (!onDocument.received) {+ await trx+ .updateTable("receiptFixedAssetLine")+ .set({ received: true, updatedBy: userId })+ .where("id", "=", onDocument.id)+ .where("companyId", "=", companyId)+ .execute();+ }+ return { id: draft.id };+ }+ await trx+ .insertInto("receiptFixedAssetLine")+ .values({+ receiptId: draft.id,+ rentalAgreementLineId,+ received: true,+ companyId,+ createdBy: userId+ })+ .execute();+ return { id: draft.id };+ }++ const onOpenDocument = new Set(+ onOpenReceipts.map((row) => row.rentalAgreementLineId)+ );+ const units = candidates.filter((line) => !onOpenDocument.has(line.id));+ if (units.length === 0) {+ throw new InvalidInputError("No units to return");+ }++ const header = await trx+ .insertInto("receipt")+ .values({+ receiptId: await getNextSequence(trx, "receipt", companyId),+ sourceDocument: "Rental Agreement",+ sourceDocumentId: agreement.id,+ sourceDocumentReadableId: agreement.rentalAgreementId,+ locationId: agreement.locationId,+ status: "Draft",+ companyId,+ createdBy: userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ await trx+ .insertInto("receiptFixedAssetLine")+ .values(+ units.map((line) => ({+ receiptId: header.id,+ rentalAgreementLineId: line.id,+ // The shortcut names its unit, so it comes back ticked; a+ // whole-agreement receipt ticks only what is out on rent.+ received: rentalAgreementLineId+ ? true+ : line.status === "On Rent",+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ return { id: header.id };+ });+ }+ case "journalEntry": {+ let createdDocumentId;+ const id = await db.transaction().execute(async (trx) => {+ const journalEntryId = await getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const newJournalEntry = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ postingDate: datetime+ .today(await resolveCompanyTimeZone(trx, companyId))+ .toString(),+ companyId,+ sourceType: "Manual",+ status: "Draft",+ createdBy: userId+ })+ .returning(["id"])+ .execute();++ createdDocumentId = newJournalEntry?.[0]?.id;+ if (!createdDocumentId)+ throw new Error("Failed to create journal entry");+ return createdDocumentId;+ });++ return { id };+ }+ default:+ throw new InvalidInputError("Invalid document type");+ }+ }++ export type ReceiptLineItem = Omit<+ Database["public"]["Tables"]["receiptLine"]["Insert"],+ "id" | "receiptId" | "updatedBy" | "createdAt" | "updatedAt"+ >;++ export type ShipmentLineItem = Omit<+ Database["public"]["Tables"]["shipmentLine"]["Insert"],+ "id" | "shipmentId" | "updatedBy" | "createdAt" | "updatedAt"+ >;+ /**+ * Pure journal-line builders for moving value between inventory and the fixed+ * asset register — capitalising stock / WIP / CIP into an asset, and returning+ * an asset to stock at its net book value.+ *+ * A line's stored amount is natural-balance-signed the way `journalLine.amount`+ * is: on an Asset account `debit("asset", x)` is +x and `credit("asset", x)` is+ * −x. Every account is class Asset except the offset of `buildOffsetLines`+ * (and an entered cost's credit), which is signed by its own class. Each+ * amount is rounded to the internal scale before it is placed on a line, and+ * every builder refuses to return an unbalanced set of lines.+ */++ export type PostingLine = {+ accountId: string;+ description: string;+ amount: number;+ };++ export type AssetAccounts = {+ assetAccountId: string;+ accumulatedDepreciationAccountId: string;+ };++ /** A finite input, rounded to the internal scale the ledger stores. */+ function ledgerAmount(value: number, label: string): number {+ if (!Number.isFinite(value)) throw new Error(`${label} must be finite`);+ return round(value);+ }++ // Every line here sits on an Asset-class account, so the stored amounts are+ // already signed debits (+ debit, − credit) and a balanced journal sums to 0.+ function assertAssetLinesBalance(lines: PostingLine[], label: string): void {+ const signedDebitTotal = round(+ lines.reduce((sum, line) => sum + line.amount, 0)+ );+ assertBalanced(signedDebitTotal, 0, EPSILON, label);+ }++ /** A stored, natural-balance-signed amount as a signed debit. */+ function asSignedDebit(type: AccountType, amount: number): number {+ return amount * debit(type, 1);+ }++ /**+ * Capitalise `cost` into a fixed asset: Dr the asset account, Cr the account+ * the value came from — a stock account (Finished Goods / Raw Materials), WIP,+ * or CIP — under `creditDescription`. `creditAccountType` is that account's+ * class (default asset): an entered cost is credited to whatever account it+ * was spent from — Retained Earnings is Equity, so its credit is stored +x.+ */+ export function buildCapitalizationLines(args: {+ cost: number;+ assetAccountId: string;+ creditAccountId: string;+ creditDescription: string;+ creditAccountType?: AccountType;+ }): PostingLine[] {+ const cost = ledgerAmount(args.cost, "Asset cost");+ // A cost that rounds to nothing at ledger precision has nothing to post.+ if (cost <= 0) throw new Error("Asset cost must be positive");++ return buildOffsetLines({+ amount: cost,+ accountId: args.assetAccountId,+ description: "Fixed Asset Acquisition",+ offsetAccountId: args.creditAccountId,+ offsetDescription: args.creditDescription,+ offsetAccountType: args.creditAccountType ?? "asset",+ label: "Asset capitalization journal"+ });+ }++ /**+ * Raise (`amount` > 0) or lower (`amount` < 0) an Asset-class account against+ * an offset account of any class: Dr asset / Cr offset to raise, the reverse+ * to lower. Each line is signed by its own account's natural balance, and the+ * pair is checked as debits = credits.+ */+ export function buildOffsetLines(args: {+ amount: number;+ accountId: string;+ description: string;+ offsetAccountId: string;+ offsetDescription: string;+ offsetAccountType: AccountType;+ label: string;+ }): PostingLine[] {+ const amount = ledgerAmount(args.amount, args.label);+ if (amount === 0) throw new Error(`${args.label} has nothing to post`);+ const raise = amount > 0;+ const size = Math.abs(amount);+ const lines: PostingLine[] = [+ {+ accountId: args.accountId,+ description: args.description,+ amount: raise ? debit("asset", size) : credit("asset", size)+ },+ {+ accountId: args.offsetAccountId,+ description: args.offsetDescription,+ amount: raise+ ? credit(args.offsetAccountType, size)+ : debit(args.offsetAccountType, size)+ }+ ];+ const [assetLine, offsetLine] = lines as [PostingLine, PostingLine];+ assertBalanced(+ round(+ asSignedDebit("asset", assetLine.amount) ++ asSignedDebit(args.offsetAccountType, offsetLine.amount)+ ),+ 0,+ EPSILON,+ args.label+ );+ return lines;+ }++ /**+ * Return a fixed asset to inventory at its net book value: Dr inventory for+ * `cost − accumulatedDepreciation`, Dr accumulated depreciation to clear it+ * (omitted when nothing has been depreciated), Cr the asset account at cost.+ */+ export function buildReturnToInventoryLines(args: {+ cost: number;+ accumulatedDepreciation: number;+ inventoryAccountId: string;+ inventoryDescription: string;+ accounts: AssetAccounts;+ }): PostingLine[] {+ const cost = ledgerAmount(args.cost, "Asset cost");+ const accumulatedDepreciation = ledgerAmount(+ args.accumulatedDepreciation,+ "Accumulated depreciation"+ );+ if (cost <= 0) throw new Error("Asset cost must be positive");+ if (accumulatedDepreciation < 0) {+ throw new Error("Accumulated depreciation must not be negative");+ }+ if (accumulatedDepreciation > cost) {+ throw new Error("Accumulated depreciation exceeds asset cost");+ }+ const netBookValue = round(cost - accumulatedDepreciation);++ const lines: PostingLine[] = [+ {+ accountId: args.inventoryAccountId,+ description: args.inventoryDescription,+ amount: debit("asset", netBookValue)+ }+ ];+ if (accumulatedDepreciation !== 0) {+ lines.push({+ accountId: args.accounts.accumulatedDepreciationAccountId,+ description: "Accumulated Depreciation",+ amount: debit("asset", accumulatedDepreciation)+ });+ }+ lines.push({+ accountId: args.accounts.assetAccountId,+ description: "Fixed Asset Cost",+ amount: credit("asset", cost)+ });+ assertAssetLinesBalance(lines, "Asset return to inventory journal");+ return lines;+ }+ export interface CostLayer {+ costLedgerId: string;+ quantityConsumed: number;+ unitCost: number;+ }++ export interface COGSResult {+ unitCost: number;+ totalCost: number;+ layersConsumed: CostLayer[];+ }++ export async function calculateCOGS(+ trx: Transaction<DB>,+ {+ itemId,+ quantity,+ companyId,+ trackedEntityIds+ }: {+ itemId: string;+ quantity: number;+ companyId: string;+ // The serial units leaving, when the caller knows them: each is relieved+ // from the layer booked for it (specific identification) before the+ // FIFO / LIFO layers (`orderLayersForConsumption`).+ trackedEntityIds?: readonly string[];+ }+ ): Promise<COGSResult> {+ const itemCost = await trx+ .selectFrom("itemCost")+ .selectAll()+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirstOrThrow();++ const costingMethod = itemCost.costingMethod;++ switch (costingMethod) {+ case "Standard": {+ const standardCost = Number(itemCost.standardCost ?? 0);+ return {+ unitCost: standardCost,+ totalCost: standardCost * quantity,+ layersConsumed: []+ };+ }++ case "Average": {+ const unitCost = Number(itemCost.unitCost ?? 0);+ return {+ unitCost,+ totalCost: unitCost * quantity,+ layersConsumed: []+ };+ }++ case "FIFO":+ case "LIFO": {+ // The item's open layers, oldest first, and their open adjustment+ // children. Locked for this transaction: two concurrent consumers+ // would otherwise both read the same remainingQuantity and consume the+ // layer twice (lost update).+ const openLayers = trx+ .selectFrom("costLedger")+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .where("remainingQuantity", ">", 0)+ .where(isCostLayer);+ const layers = await openLayers+ .select([+ "id",+ "quantity",+ "cost",+ "remainingQuantity",+ "trackedEntityId"+ ])+ .orderBy("postingDate", "asc")+ .orderBy("createdAt", "asc")+ .forUpdate()+ .execute();+ const children = await trx+ .selectFrom("costLedger")+ .select([+ "id",+ "appliesToCostLedgerId",+ "quantity",+ "cost",+ "remainingQuantity"+ ])+ .where("companyId", "=", companyId)+ .where("appliesToCostLedgerId", "in", openLayers.select("id"))+ .where("remainingQuantity", ">", 0)+ .orderBy("createdAt", "asc")+ .forUpdate()+ .execute();+ const childrenByLayer = Map.groupBy(+ children,+ (child) => child.appliesToCostLedgerId+ );++ const relief = relieveLayers(+ layers.map((layer) => ({+ id: layer.id,+ quantity: Number(layer.quantity),+ cost: Number(layer.cost),+ remainingQuantity: Number(layer.remainingQuantity),+ trackedEntityId: layer.trackedEntityId,+ children: (childrenByLayer.get(layer.id) ?? []).map((child) => ({+ id: child.id,+ quantity: Number(child.quantity),+ cost: Number(child.cost),+ remainingQuantity: Number(child.remainingQuantity)+ }))+ })),+ costingMethod,+ { quantity, trackedEntityIds: trackedEntityIds ?? [] },+ // Negative inventory: a quantity no layer covers.+ Number(itemCost.unitCost ?? 0)+ );++ if (relief.remaining.size > 0) {+ await sql`+ UPDATE "costLedger" AS c+ SET "remainingQuantity" = v."remaining"+ FROM (VALUES ${sql.join(+ [...relief.remaining].map(+ ([id, remaining]) => sql`(${id}, ${remaining}::numeric)`+ )+ )}) AS v("id", "remaining")+ WHERE c."id" = v."id" AND c."companyId" = ${companyId}+ `.execute(trx);+ }++ return {+ unitCost: quantity > 0 ? relief.totalCost / quantity : 0,+ totalCost: relief.totalCost,+ layersConsumed: relief.layersConsumed.map((layer) => ({+ costLedgerId: layer.layerId,+ quantityConsumed: layer.quantity,+ unitCost: layer.unitCost+ }))+ };+ }++ default:+ throw new Error(`Unsupported costing method: ${costingMethod}`);+ }+ }+ /**+ * Serializes every writer of one company's contract positions. A movement is+ * computed from the position as read, so two writers interleaving on one line+ * would both draw on the same pool. Transaction-scoped: released at commit.+ */+ export async function lockContractPositions(+ trx: KyselyTx,+ companyId: string+ ): Promise<void> {+ await sql`SELECT pg_advisory_xact_lock(hashtext(${`contract-position:${companyId}`}))`.execute(+ trx+ );+ }++ /** Each line's position — the sum of its ledger entries — in one grouped+ * read. A line with no entries is the empty position. */+ export async function loadContractPositions(+ db: Kysely<KyselyDatabase> | KyselyTx,+ companyId: string,+ lineIds: string[]+ ): Promise<Map<string, ContractPosition>> {+ const positions = new Map<string, ContractPosition>();+ const ids = [...new Set(lineIds)];+ for (const id of ids) positions.set(id, { ...EMPTY_POSITION });+ if (ids.length === 0) return positions;+ const rows = await db+ .selectFrom("customerContractLedgerEntry")+ .select([+ "customerContractLineId",+ sql<number>`COALESCE(SUM("deferredAmount"), 0)`.as("deferredAmount"),+ sql<number>`COALESCE(SUM("deferredBase"), 0)`.as("deferredBase"),+ sql<number>`COALESCE(SUM("assetAmount"), 0)`.as("assetAmount"),+ sql<number>`COALESCE(SUM("assetBase"), 0)`.as("assetBase")+ ])+ .where("companyId", "=", companyId)+ .where("customerContractLineId", "in", ids)+ .groupBy("customerContractLineId")+ .execute();+ for (const row of rows) {+ positions.set(row.customerContractLineId, {+ deferredAmount: Number(row.deferredAmount),+ deferredBase: Number(row.deferredBase),+ assetAmount: Number(row.assetAmount),+ assetBase: Number(row.assetBase)+ });+ }+ return positions;+ }++ export function samePosition(a: ContractPosition, b: ContractPosition) {+ return (+ equals(a.deferredAmount, b.deferredAmount) &&+ equals(a.deferredBase, b.deferredBase) &&+ equals(a.assetAmount, b.assetAmount) &&+ equals(a.assetBase, b.assetBase)+ );+ }++ /** A signed credit (negative = debit) as the stored natural-balance amount of+ * an account of `accountClass`. */+ export function signedCreditAmount(accountClass: string, amount: number) {+ const type = accountTypeFromClass(accountClass);+ return amount >= 0 ? credit(type, amount) : debit(type, -amount);+ }+ /**+ * The dimension a charge or reimbursement line's cost center and project+ * post under: the oldest active Cost Center and Project dimension of the+ * company group, or null when the group has none. One read for both.+ */+ export async function costCenterAndProjectDimensions(+ trx: Kysely<DB>,+ companyGroupId: string | null+ ): Promise<{ costCenter: string | null; project: string | null }> {+ // A company in no group has no dimensions.+ if (!companyGroupId) return { costCenter: null, project: null };+ const dimensions = await trx+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("companyGroupId", "=", companyGroupId)+ .where("active", "=", true)+ .where("entityType", "in", ["CostCenter", "Project"])+ .orderBy("createdAt")+ .orderBy("id")+ .execute();+ return {+ costCenter:+ dimensions.find((dimension) => dimension.entityType === "CostCenter")+ ?.id ?? null,+ project:+ dimensions.find((dimension) => dimension.entityType === "Project")?.id ??+ null+ };+ }+ // The tracked entities an item's outgoing ledger rows name — the ids to pass+ // calculateCOGS as `trackedEntityIds`. Batch ids come along harmlessly: only+ // serial layers are ever stamped, so a batch id matches no layer.+ export function leavingTrackedEntityIds(+ ledgerRows: readonly {+ itemId?: string | null;+ trackedEntityId?: string | null;+ quantity?: number | null;+ }[],+ itemId: string+ ): string[] {+ const leaving = new Set<string>();+ for (const row of ledgerRows) {+ if (+ row.itemId === itemId &&+ row.trackedEntityId &&+ (row.quantity ?? 0) < 0+ ) {+ leaving.add(row.trackedEntityId);+ }+ }+ return [...leaving];+ }+ /** A currency's settlement precision for this company: the group's+ * `currency.decimalPlaces`, never a literal. Billed amounts (rental billing+ * periods, lease payment rows) are rounded to it. */+ export async function currencyDecimals(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ currencyCode: string+ ): Promise<number> {+ const currency = await trx+ .selectFrom("currency")+ .innerJoin("company", "company.companyGroupId", "currency.companyGroupId")+ .select("currency.decimalPlaces")+ .where("company.id", "=", companyId)+ .where("currency.code", "=", currencyCode)+ .executeTakeFirst();+ if (!currency || currency.decimalPlaces === null) {+ throw new InvalidInputError(+ `Currency ${currencyCode} is not set up for this company`+ );+ }+ return currency.decimalPlaces;+ }+ export const INVENTORY_VOID_BEFORE_CUTOVER_ERROR =+ "This document is from before your accounting cutover. Record a return or an inventory adjustment instead.";++ export const SALES_INVOICE_VOID_BEFORE_CUTOVER_ERROR =+ "This invoice is from before your accounting cutover. Issue a credit memo instead.";++ export const PURCHASE_INVOICE_VOID_BEFORE_CUTOVER_ERROR =+ "This invoice is from before your accounting cutover. Record a debit memo instead.";++ export const CHARGE_VOID_BEFORE_CUTOVER_ERROR =+ "This charge is from before your accounting cutover. Record a journal entry to correct it instead.";++ export const REIMBURSEMENT_VOID_BEFORE_CUTOVER_ERROR =+ "This reimbursement is from before your accounting cutover. Record a journal entry to correct it instead.";++ export const STOCK_CORRECTION_BEFORE_CUTOVER_ERROR =+ "This movement is from before your accounting cutover. Record an inventory adjustment instead.";++ export const TIME_ENTRY_BEFORE_CUTOVER_ERROR =+ "This time entry was posted before your accounting cutover. Record a journal entry to correct it instead.";++ /**+ * Throws `message` when the document's posting date is before the company's+ * cutover. Call it before any write. A company with no cutover, or a document+ * with no posting date, passes.+ */+ export async function refuseVoidBeforeCutover(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ postingDate: string | null | undefined,+ message: string+ ): Promise<void> {+ if (!postingDate) return;+ const cutoverDate = await readAccountingCutoverDate(db, companyId);+ if (isBeforeCutover(postingDate, cutoverDate)) {+ throw new InvalidInputError(message);+ }+ }++ /**+ * Refuses a rebuilt void line on Migration Clearing. Only the opening journal+ * and the trial balance post there; a void that did would move the proof+ * that the opening ties out.+ */+ export function assertNoMigrationClearing(+ lines: { accountId: string | null }[],+ migrationClearingAccountId: string | null+ ): void {+ if (+ migrationClearingAccountId &&+ lines.some((line) => line.accountId === migrationClearingAccountId)+ ) {+ throw new Error("A void never posts to the Migration Clearing account.");+ }+ }+ type DocumentType = Database["public"]["Enums"]["journalLineDocumentType"];++ /** What narrows the lines. Every field set must match; an empty list matches+ * nothing. */+ export type DocumentJournalLineFilter = {+ documentId?: string;+ documentType?: DocumentType | readonly DocumentType[];+ documentLineReference?: readonly string[];+ journalId?: readonly string[];+ journalLineReference?: readonly string[];+ accrual?: boolean;+ };++ export async function documentJournalLines(+ db: Kysely<KyselyDatabase> | Transaction<KyselyDatabase>,+ companyId: string,+ filter: DocumentJournalLineFilter+ ): Promise<Selectable<KyselyDatabase["journalLine"]>[]> {+ const lists = [+ filter.documentLineReference,+ filter.journalId,+ filter.journalLineReference+ ];+ if (lists.some((list) => list !== undefined && list.length === 0)) {+ return [];+ }+ let query = db+ .selectFrom("journalLine")+ .innerJoin("journal", (join) =>+ join+ .onRef("journal.id", "=", "journalLine.journalId")+ .onRef("journal.companyId", "=", "journalLine.companyId")+ )+ .selectAll("journalLine")+ .where("journalLine.companyId", "=", companyId)+ .where("journal.status", "in", [...DOCUMENT_JOURNAL_STATUSES]);+ if (filter.documentId !== undefined) {+ query = query.where("journalLine.documentId", "=", filter.documentId);+ }+ if (typeof filter.documentType === "string") {+ query = query.where("journalLine.documentType", "=", filter.documentType);+ } else if (filter.documentType !== undefined) {+ query = query.where("journalLine.documentType", "in", [+ ...filter.documentType+ ]);+ }+ if (filter.documentLineReference !== undefined) {+ query = query.where("journalLine.documentLineReference", "in", [+ ...filter.documentLineReference+ ]);+ }+ if (filter.journalId !== undefined) {+ query = query.where("journalLine.journalId", "in", [...filter.journalId]);+ }+ if (filter.journalLineReference !== undefined) {+ query = query.where("journalLine.journalLineReference", "in", [+ ...filter.journalLineReference+ ]);+ }+ if (filter.accrual !== undefined) {+ query = query.where("journalLine.accrual", "=", filter.accrual);+ }+ return query.execute();+ }+ /**+ * Keeps Draft revenue recognition runs in step with a Planned schedule row a+ * document is about to delete or shrink. A run line copies its row's amount+ * when the run is proposed and posting uses that copy, so a credit memo that+ * trimmed a held deferral left the run recognizing the old amount, and a void+ * or memo that deleted one tripped the line's ON DELETE RESTRICT foreign key.+ * Only a Draft run can hold a Planned row (posting flips both), so this never+ * touches a posted run. A run left with no lines is deleted — it could not+ * post. Call it in the document's transaction, BEFORE the schedule write.+ */+ export async function syncDraftRecognitionRuns(+ trx: KyselyTx,+ args: {+ companyId: string;+ userId: string;+ deletedScheduleIds?: string[];+ reduced?: { id: string; amount: number }[];+ }+ ): Promise<void> {+ const { companyId, userId, deletedScheduleIds = [], reduced = [] } = args;++ if (deletedScheduleIds.length > 0) {+ const released = await trx+ .deleteFrom("revenueRecognitionRunLine")+ .where("companyId", "=", companyId)+ .where("scheduleId", "in", deletedScheduleIds)+ .returning("runId")+ .execute();+ const runIds = [...new Set(released.map((line) => line.runId))];+ if (runIds.length > 0) {+ await trx+ .deleteFrom("revenueRecognitionRun")+ .where("companyId", "=", companyId)+ .where("status", "=", "Draft")+ .where("id", "in", runIds)+ .where(({ not, exists, selectFrom }) =>+ not(+ exists(+ selectFrom("revenueRecognitionRunLine as l")+ .select("l.id")+ .whereRef("l.runId", "=", "revenueRecognitionRun.id")+ .where("l.companyId", "=", companyId)+ )+ )+ )+ .execute();+ }+ }++ if (reduced.length > 0) {+ await trx+ .updateTable("revenueRecognitionRunLine")+ .set({+ amount: sql<number>`CASE "scheduleId" ${sql.join(+ reduced.map(+ ({ id, amount }) => sql`WHEN ${id} THEN ${amount}::numeric`+ ),+ sql` `+ )} END`,+ updatedBy: userId+ })+ .where("companyId", "=", companyId)+ .where(+ "scheduleId",+ "in",+ reduced.map(({ id }) => id)+ )+ .execute();+ }+ }+ type FixedAssetUpdate = Database["public"]["Tables"]["fixedAsset"]["Update"];++ type Write = (trx: Kysely<KyselyDatabase>) => Promise<unknown>;++ /** Fixed-asset writes decided while the journal is built, applied inside the+ * posting transaction so a failed post leaves the asset register untouched. */+ export class FixedAssetWrites {+ private patches = new Map<string, FixedAssetUpdate>();+ private writes: Write[] = [];++ /** Later lines of one document see what earlier lines staged. */+ overlay<T extends object>(assetId: string, row: T): T {+ return Object.assign(row, this.patches.get(assetId));+ }++ patch(assetId: string, set: FixedAssetUpdate): void {+ this.patches.set(assetId, { ...this.patches.get(assetId), ...set });+ }++ defer(write: Write): void {+ this.writes.push(write);+ }++ async apply(trx: Kysely<KyselyDatabase>, companyId: string): Promise<void> {+ for (const [id, set] of this.patches) {+ await updateRows(trx, "fixedAsset", set, { id, companyId });+ }+ for (const write of this.writes) await write(trx);+ }+ }+ const MONTH_NUMBER: Record<string, number> = {+ January: 1,+ February: 2,+ March: 3,+ April: 4,+ May: 5,+ June: 6,+ July: 7,+ August: 8,+ September: 9,+ October: 10,+ November: 11,+ December: 12+ };++ type PeriodMode = "historical" | "historical-with-shift" | "current";++ function closedPeriodError(mode: PeriodMode, closed: boolean): Error {+ if (mode === "historical") {+ return new Error(+ closed+ ? "The original movement's accounting period is closed — its movements can no longer be corrected."+ : "The original movement's accounting period is locked. Unlock it before posting a correction."+ );+ }+ return new Error(+ closed+ ? "Accounting period is closed. Reopen it before posting."+ : "Accounting period is locked. Unlock it before posting operational documents."+ );+ }++ /** Resolve a posting date and lock its period on the caller's transaction.+ * Historical card imports may shift to the next open period; corrections keep+ * their original date. Only current-period posting changes the Active period,+ * and only when the period contains the company's today: a posting dated in+ * another month (a catch-up run, a back-dated document) leaves it alone.+ */+ export async function resolveAccountingPeriod(+ db: Kysely<DB>,+ companyId: string,+ requestedDate: string,+ mode: PeriodMode+ ): Promise<{ id: string; postingDate: string }> {+ // Reuse a transaction instead of borrowing a second pool connection. All+ // reads observe the same transaction.+ if (!db.isTransaction) {+ return db+ .transaction()+ .execute((trx) =>+ resolveAccountingPeriod(trx, companyId, requestedDate, mode)+ );+ }++ const periods = db+ .selectFrom("accountingPeriod")+ .select([+ "id",+ // Keep calendar values as ISO text, never passing through a JavaScript+ // Date.+ sql<string>`"startDate"::text`.as("startDate"),+ sql<string>`"endDate"::text`.as("endDate"),+ "status",+ "closeStatus",+ "closedAt"+ ])+ .where("companyId", "=", companyId);+ let period = await periods+ .where("startDate", "<=", requestedDate)+ .where("endDate", ">=", requestedDate)+ .orderBy("startDate")+ .orderBy("id")+ .forUpdate()+ .executeTakeFirst();++ const isClosed =+ period &&+ (period.closeStatus === "Locked" ||+ period.closeStatus === "Closed" ||+ period.closedAt !== null);+ if (isClosed && mode === "historical-with-shift") {+ period = await periods+ .where("startDate", ">", requestedDate)+ .where("closeStatus", "=", "Open")+ .where("closedAt", "is", null)+ .orderBy("startDate")+ .orderBy("id")+ .forUpdate()+ .executeTakeFirst();+ if (!period) {+ throw new Error(+ "Accounting period is locked or closed; no open successor exists"+ );+ }+ } else if (period && isClosed) {+ throw closedPeriodError(+ mode,+ period.closeStatus === "Closed" || period.closedAt !== null+ );+ }++ if (!period) {+ const date = parseDate(requestedDate);+ const fiscalSettings = await db+ .selectFrom("fiscalYearSettings")+ .select("startMonth")+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const startMonth = fiscalSettings?.startMonth+ ? (MONTH_NUMBER[fiscalSettings.startMonth] ?? 1)+ : 1;+ const fiscalYear =+ startMonth === 1 || date.month < startMonth ? date.year : date.year + 1;+ const periodNumber = ((date.month - startMonth + 12) % 12) + 1;+ // Create inactive, then activate below: this also preserves one active+ // period while simultaneous first-time callers converge on the same row.+ await db+ .insertInto("accountingPeriod")+ .values({+ startDate: startOfMonth(date).toString(),+ endDate: endOfMonth(date).toString(),+ fiscalYear,+ periodNumber,+ status: "Inactive",+ closeStatus: "Open",+ companyId,+ createdBy: "system"+ })+ .onConflict((oc) =>+ oc.columns(["companyId", "fiscalYear", "periodNumber"]).doNothing()+ )+ .execute();+ period = await periods+ .where("fiscalYear", "=", fiscalYear)+ .where("periodNumber", "=", periodNumber)+ .forUpdate()+ .executeTakeFirstOrThrow();+ if (+ period.closeStatus === "Locked" ||+ period.closeStatus === "Closed" ||+ period.closedAt !== null+ ) {+ throw closedPeriodError(+ mode,+ period.closeStatus === "Closed" || period.closedAt !== null+ );+ }+ }++ if (mode === "current" && period.status !== "Active") {+ const today = datetime+ .today(await resolveCompanyTimeZone(db, companyId))+ .toString();+ if (period.startDate <= today && period.endDate >= today) {+ await db+ .updateTable("accountingPeriod")+ .set({ status: "Inactive" })+ .where("companyId", "=", companyId)+ .where("status", "=", "Active")+ .execute();+ await db+ .updateTable("accountingPeriod")+ .set({ status: "Active" })+ .where("companyId", "=", companyId)+ .where("id", "=", period.id)+ .execute();+ }+ }+ return {+ id: period.id,+ postingDate:+ mode === "historical-with-shift" && period.startDate > requestedDate+ ? period.startDate+ : requestedDate+ };+ }++ /** Original-period corrections retain the existing public calling contract. */+ export async function getAccountingPeriodForDate(+ companyId: string,+ db: Kysely<DB>,+ date: string+ ) {+ return (await resolveAccountingPeriod(db, companyId, date, "historical")).id;+ }++ /** Pass the same business day used by the caller's journal and ledger rows. */+ export async function getCurrentAccountingPeriod(+ companyId: string,+ db: Kysely<DB>,+ forDate?: string+ ) {+ const date =+ forDate ??+ datetime.today(await resolveCompanyTimeZone(db, companyId)).toString();+ return (await resolveAccountingPeriod(db, companyId, date, "current")).id;+ }+ /** The company's posting accounts. Pass `db` (or `trx`); a Supabase client still works. */+ export async function getDefaultPostingGroup(+ client: AnyPostgresClient,+ companyId: string+ ) {+ if (isKysely(client)) {+ return await single(client, "accountDefault", { companyId });+ }+ return await client+ .from("accountDefault")+ .select("*")+ .eq("companyId", companyId)+ .single();+ }++ // Buy → Raw Materials; Make / Buy and Make → Finished Goods. The rule is a+ // stable property of the item so the debit side (receipt/job completion) and+ // the credit side (shipment/issue/invoice) always hit the same account.+ export function resolveInventoryAccount(+ replenishmentSystem:+ | Database["public"]["Enums"]["itemReplenishmentSystem"]+ | null,+ accountDefaults: {+ rawMaterialsAccount: string;+ finishedGoodsAccount: string;+ }+ ): { account: string; description: string } {+ return replenishmentSystem === "Make" ||+ replenishmentSystem === "Buy and Make"+ ? {+ account: accountDefaults.finishedGoodsAccount,+ description: "Finished Goods Account"+ }+ : {+ account: accountDefaults.rawMaterialsAccount,+ description: "Raw Materials Account"+ };+ }+ /** A journal line's dimension values, by entity type: the shape a pure+ * posting builder returns and the legacy backfill writes as is. */+ export type JournalLineDimensionValues = Partial<+ Record<Database["public"]["Enums"]["dimensionEntityType"], string | null>+ >;++ /**+ * The `journalLineDimension` rows of inserted lines: `journalLineIds[i]` is+ * the id of `lines[i]`. A value whose entity type has no active dimension+ * (`dimensionIdByEntity`) writes none. Rows follow each line's key order.+ */+ export function journalLineDimensionRows({+ journalLineIds,+ lines,+ dimensionIdByEntity,+ companyId+ }: {+ journalLineIds: string[];+ lines: { dimensions: JournalLineDimensionValues }[];+ dimensionIdByEntity: ReadonlyMap<string, string>;+ companyId: string;+ }) {+ return journalLineIds.flatMap((journalLineId, index) =>+ Object.entries(lines[index]?.dimensions ?? {}).flatMap(+ ([entityType, valueId]) => {+ const dimensionId = dimensionIdByEntity.get(entityType);+ return dimensionId && valueId+ ? [{ journalLineId, dimensionId, valueId, companyId }]+ : [];+ }+ )+ );+ }+ /**+ * Allocate native journal-line ids before a bulk insert. Callers can then keep+ * related rows bound to the intended line without depending on PostgreSQL's+ * unspecified INSERT ... RETURNING row order.+ */+ export async function allocateJournalLineIds(+ trx: Transaction<KyselyDatabase>,+ count: number+ ): Promise<string[]> {+ if (!Number.isSafeInteger(count) || count < 0) {+ throw new Error("Journal line id count must be a non-negative integer");+ }+ if (count === 0) return [];++ const allocated = await sql<{ id: string; position: number }>`+ SELECT id('jl') AS id, position::integer AS position+ FROM generate_series(1, ${count}) WITH ORDINALITY AS requested(_, position)+ ORDER BY position+ `.execute(trx);+ if (allocated.rows.length !== count) {+ throw new Error("Failed to allocate journal line ids");+ }+ return allocated.rows.map((row) => row.id);+ }+ type Enums = Database["public"]["Enums"];++ /** The lease terms a payment row is cut from. */+ export type LeasePaymentCutTerms = {+ commencementDate: string;+ /** Null is open-ended: pass `through`. */+ endDate: string | null;+ /** A row due before it was paid outside Carbon: it is Skipped. */+ invoiceFromDate: string;+ paymentFrequency: Enums["leasePaymentFrequency"];+ paymentTiming: Enums["rentalBillingTiming"];+ annualEscalationPercent: number;+ };++ /** The leased asset (`leaseLine`) whose rows are cut. */+ export type LeasePaymentCutAsset = {+ id: string;+ /** The payment at commencement. */+ paymentAmount: number;+ purchaseOptionAmount: number | null;+ purchaseOptionReasonablyCertain: boolean;+ };++ export type CutLeasePaymentRow = LeasePaymentRowInput & {+ leaseLineId: string;+ status: Extract<Enums["leasePaymentStatus"], "Pending" | "Skipped">;+ };++ /**+ * One asset's payment rows, cut from the COMMENCEMENT so the escalation steps+ * up on its anniversaries and a lease from the 29th–31st keeps its clamped+ * months (`generateLeasePayments`: a short last period prorated by days; the+ * purchase option on the end date, only when it is reasonably certain). A row+ * due before `invoiceFromDate` was paid outside Carbon and is `Skipped`; a row+ * of 0 is never cut.+ *+ * - `through` — an open-ended lease: the last date a period may start on+ * (`openEndedLeaseHorizon`).+ * - `after` — only the periods that start after it (the rows an open-ended+ * lease already has end there, edited or not).+ * - `from` — Modify: only the rows from lease month `month` on, where the+ * asset pays `paymentAtStart` (`remainingLeasePayments`, the math the+ * Modify preview shares): its commencement payment is derived from it,+ * and a period that started before the month (the frequency changed) is+ * cut down to its days from there.+ *+ * Returns the commencement payment the rows are cut at, which Modify stores+ * on the asset.+ */+ export function cutLeasePaymentRows(args: {+ lease: LeasePaymentCutTerms;+ asset: LeasePaymentCutAsset;+ decimals: number;+ through?: string;+ after?: string | null;+ from?: { month: number; paymentAtStart: number };+ }): { commencementPayment: number; rows: CutLeasePaymentRow[] } {+ const { lease, asset, decimals, from } = args;+ const purchaseOptionAmount = asset.purchaseOptionReasonablyCertain+ ? (asset.purchaseOptionAmount ?? 0)+ : 0;+ let cut: { commencementPayment: number; rows: LeasePaymentRowInput[] };+ if (from) {+ if (!lease.endDate) {+ throw new Error("Only a lease with an end date is cut from a month");+ }+ cut = remainingLeasePayments({+ commencementDate: lease.commencementDate,+ fromMonth: from.month,+ endDate: lease.endDate,+ paymentAtStart: from.paymentAtStart,+ frequency: lease.paymentFrequency,+ timing: lease.paymentTiming,+ annualEscalationPercent: lease.annualEscalationPercent,+ purchaseOptionAmount,+ decimals+ });+ } else {+ cut = {+ commencementPayment: asset.paymentAmount,+ rows: generateLeasePayments({+ commencementDate: lease.commencementDate,+ endDate: lease.endDate,+ through: args.through,+ paymentAmount: asset.paymentAmount,+ frequency: lease.paymentFrequency,+ timing: lease.paymentTiming,+ annualEscalationPercent: lease.annualEscalationPercent,+ purchaseOptionAmount,+ decimals+ })+ };+ }++ const rows = cut.rows+ .filter(+ (row) => row.amount > 0 && (!args.after || row.periodStart > args.after)+ )+ .map(+ (row): CutLeasePaymentRow => ({+ ...row,+ leaseLineId: asset.id,+ status: row.dueDate < lease.invoiceFromDate ? "Skipped" : "Pending"+ })+ );++ return { commencementPayment: round(cut.commencementPayment), rows };+ }+ // The account an entered cost is credited to: where that value was booked+ // when it was spent (an expense this year, Retained Earnings for an earlier+ // one). Any active posting account of the company group.+ export async function getOffsetAccount(+ db: Kysely<DB>,+ companyId: string,+ accountId: string | null | undefined+ ): Promise<{ id: string; type: AccountType }> {+ if (!accountId) {+ throw new InvalidInputError(+ "Choose the account the cost was booked to when it was spent"+ );+ }+ const account = await db+ .selectFrom("account")+ .innerJoin("company", "company.companyGroupId", "account.companyGroupId")+ .select(["account.id", "account.class"])+ .where("account.id", "=", accountId)+ .where("company.id", "=", companyId)+ .where("account.active", "=", true)+ .where("account.isGroup", "=", false)+ .executeTakeFirst();+ if (!account || !isAccountClass(account.class)) {+ throw new InvalidInputError(+ "The offset account must be an active posting account"+ );+ }+ // The credit is signed by the account's own class (Retained Earnings is+ // Equity), not as the inventory account it replaces.+ return { id: account.id, type: accountTypeFromClass(account.class) };+ }+ type PartyDimension = { id: string; entityType: string };++ /** The company group's active party dimensions, for `partyDimensionValuesFrom`. */+ export function loadPartyDimensions(+ trx: Transaction<KyselyDatabase>,+ companyGroupId: string,+ entityTypes: ("CustomerType" | "Customer" | "SupplierType" | "Supplier")[] = [+ "CustomerType",+ "Customer",+ "SupplierType",+ "Supplier"+ ]+ ): Promise<PartyDimension[]> {+ return trx+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("companyGroupId", "=", companyGroupId)+ .where("active", "=", true)+ .where("entityType", "in", entityTypes)+ .execute();+ }++ /** `partyDimensionValues` over dimensions already read. */+ export function partyDimensionValuesFrom(+ dimensions: PartyDimension[],+ args: { isAR: boolean; partyId: string; typeId: string | null }+ ): { dimensionId: string; valueId: string }[] {+ const { isAR, partyId, typeId } = args;+ const partyType = isAR ? "Customer" : "Supplier";+ return dimensions+ .filter((dimension) =>+ isAR+ ? dimension.entityType === "CustomerType" ||+ dimension.entityType === "Customer"+ : dimension.entityType === "SupplierType" ||+ dimension.entityType === "Supplier"+ )+ .flatMap((dimension) => {+ const valueId = dimension.entityType === partyType ? partyId : typeId;+ return valueId ? [{ dimensionId: dimension.id, valueId }] : [];+ });+ }++ /**+ * The party dimensions of a payment or memo journal: Customer and+ * CustomerType for a customer, Supplier and SupplierType for a supplier.+ * Every line of the journal carries each of them.+ */+ export async function partyDimensionValues(+ trx: Transaction<KyselyDatabase>,+ args: {+ companyGroupId: string;+ isAR: boolean;+ partyId: string;+ typeId: string | null;+ }+ ): Promise<{ dimensionId: string; valueId: string }[]> {+ const { companyGroupId, isAR } = args;+ const dimensions = await loadPartyDimensions(+ trx,+ companyGroupId,+ isAR ? ["CustomerType", "Customer"] : ["SupplierType", "Supplier"]+ );+ return partyDimensionValuesFrom(dimensions, args);+ }+ type ItemLedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];++ type CostLedgerInsert = Database["public"]["Tables"]["costLedger"]["Insert"];++ type JournalLineInsert = Database["public"]["Tables"]["journalLine"]["Insert"];++ type JournalLineDimensionInsert =+ Database["public"]["Tables"]["journalLineDimension"]["Insert"];++ type ItemLedgerDocumentType =+ Database["public"]["Enums"]["itemLedgerDocumentType"];++ type JournalLineDocumentType =+ Database["public"]["Enums"]["journalLineDocumentType"];++ // itemLedgerDocumentType values that also exist on journalLineDocumentType.+ // The journal line falls back to 'Inventory Adjustment' for ledger documentType+ // values the journal enum doesn't carry (e.g. 'Sales Invoice', 'Direct+ // Transfer', 'Posted Assembly') — inserting those would fail the enum cast.+ export const JOURNAL_LINE_SAFE_DOCUMENT_TYPES: ReadonlySet<string> = new Set([+ "Sales Shipment",+ "Purchase Receipt",+ "Purchase Invoice",+ "Transfer Shipment",+ "Job Consumption",+ "Job Receipt",+ "Batch Split",+ "Maintenance Consumption",+ "Inventory Count",+ "Non-Conformance",+ "Inbound Inspection",+ "Scrap",+ "Asset Transfer"+ ]);++ export function toJournalLineDocumentType(+ documentType: ItemLedgerDocumentType | null | undefined+ ): JournalLineDocumentType {+ return (+ documentType && JOURNAL_LINE_SAFE_DOCUMENT_TYPES.has(documentType)+ ? documentType+ : "Inventory Adjustment"+ ) as JournalLineDocumentType;+ }++ // The item ledger row for a movement — the stock movement itself, written+ // before anything that references it. `quantity` is SIGNED (positive for an+ // increase, negative for a decrease) and is the only field with arithmetic on+ // it. Every caller goes through here so a column added to the movement lands+ // on the single-record path and the bulk importer at once.+ export function buildItemLedgerRow(args: {+ postingDate: string;+ entryType: Database["public"]["Enums"]["itemLedgerType"];+ documentType?: ItemLedgerDocumentType | null;+ documentId?: string | null;+ correctionOfItemLedgerId?: string | null;+ itemId: string;+ locationId: string | null;+ storageUnitId: string | null;+ trackedEntityId: string | null;+ quantity: number;+ comment?: string | null;+ scrapReasonId?: string | null;+ companyId: string;+ createdBy: string;+ }): ItemLedgerInsert {+ return {+ postingDate: args.postingDate,+ entryType: args.entryType,+ documentType: args.documentType ?? null,+ documentId: args.documentId ?? null,+ correctionOfItemLedgerId: args.correctionOfItemLedgerId ?? null,+ itemId: args.itemId,+ locationId: args.locationId,+ storageUnitId: args.storageUnitId,+ trackedEntityId: args.trackedEntityId,+ quantity: round(args.quantity),+ comment: args.comment ?? null,+ scrapReasonId: args.scrapReasonId ?? null,+ companyId: args.companyId,+ createdBy: args.createdBy+ };+ }++ // One cost-ledger row for a movement. `quantity` and `cost` are SIGNED —+ // negative for a decrease (the relief of carrying value), positive for an+ // increase. A decrease leaves nothing to consume later, so its layer opens+ // with remainingQuantity 0; an increase opens a layer for its full quantity.+ export function buildCostLedgerRow(args: {+ entryType: Database["public"]["Enums"]["itemLedgerType"];+ documentType?: ItemLedgerDocumentType | null;+ documentId: string;+ itemId: string;+ quantity: number;+ cost: number;+ postingDate: string;+ // A serial unit's own layer (specific identification); null for FIFO/LIFO.+ trackedEntityId?: string | null;+ companyId: string;+ }): CostLedgerInsert {+ const quantity = round(args.quantity);+ return {+ itemLedgerType: args.entryType,+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: args.documentType ?? null,+ documentId: args.documentId,+ itemId: args.itemId,+ quantity,+ cost: round(args.cost),+ remainingQuantity: quantity > 0 ? quantity : 0,+ postingDate: args.postingDate,+ trackedEntityId: args.trackedEntityId ?? null,+ companyId: args.companyId+ };+ }++ // The balanced pair for a movement that carries value: the inventory account+ // against the offset (variance / scrap) account. `cost` and `quantity` are+ // ABSOLUTE; `isGain` picks which side each account takes.+ export function buildAdjustmentJournalLines(args: {+ journalId: string;+ documentId: string;+ documentType?: ItemLedgerDocumentType | null;+ journalLineReference: string;+ isGain: boolean;+ cost: number;+ quantity: number;+ replenishmentSystem:+ | Database["public"]["Enums"]["itemReplenishmentSystem"]+ | null;+ accountDefaults: {+ rawMaterialsAccount: string;+ finishedGoodsAccount: string;+ inventoryAdjustmentVarianceAccount: string;+ };+ offsetAccount?: string | null;+ offsetDescription?: string;+ companyId: string;+ }): [JournalLineInsert, JournalLineInsert] {+ const inventoryAccount = resolveInventoryAccount(+ args.replenishmentSystem,+ args.accountDefaults+ );+ const documentType = toJournalLineDocumentType(args.documentType);+ const quantity = round(args.quantity);+ const shared = {+ journalId: args.journalId,+ quantity,+ documentType,+ documentId: args.documentId,+ journalLineReference: args.journalLineReference,+ companyId: args.companyId+ };+ return [+ {+ ...shared,+ accountId: inventoryAccount.account,+ description: inventoryAccount.description,+ amount: round(+ args.isGain ? debit("asset", args.cost) : credit("asset", args.cost)+ )+ },+ {+ ...shared,+ accountId:+ args.offsetAccount ??+ args.accountDefaults.inventoryAdjustmentVarianceAccount,+ description: args.offsetDescription ?? "Inventory Adjustment",+ amount: round(+ args.isGain ? credit("expense", args.cost) : debit("expense", args.cost)+ )+ }+ ];+ }++ // Dimension tags (post-shipment precedent): every line of the entry gets the+ // movement's Item / ItemPostingGroup / Location, for whichever dimensions are+ // active on the company group, plus any caller-supplied extras.+ export function buildJournalLineDimensions(args: {+ journalLineIds: string[];+ dimensions: Record<string, string>;+ itemId: string;+ itemPostingGroupId?: string | null;+ locationId: string | null;+ extraDimensions?: Array<{ entityType: string; valueId: string }>;+ companyId: string;+ }): JournalLineDimensionInsert[] {+ const dimensionValues: Array<[string, string | null | undefined]> = [+ ["Item", args.itemId],+ ["ItemPostingGroup", args.itemPostingGroupId],+ ["Location", args.locationId],+ ...(args.extraDimensions ?? []).map(+ (d) => [d.entityType, d.valueId] as [string, string]+ )+ ];+ return args.journalLineIds.flatMap((journalLineId) =>+ dimensionValues+ .filter(([entityType, valueId]) => args.dimensions[entityType] && valueId)+ .map(([entityType, valueId]) => ({+ journalLineId,+ dimensionId: args.dimensions[entityType]!,+ valueId: valueId as string,+ companyId: args.companyId+ }))+ );+ }++ export interface PlannedIncrease {+ /** The layer's unit cost, as `computeCurrentUnitCost` would return it. */+ unitCost: number;+ /** quantity × unitCost, unrounded — `buildCostLedgerRow` rounds it. */+ cost: number;+ }++ // Successive increases for ONE item, in the order they will be written.+ //+ // Booking them one at a time re-reads the item's open cost layers before every+ // row, so row n+1 sees the layer row n just wrote. This replays that read in+ // memory from a SINGLE starting snapshot, which is what lets the caller write+ // the whole file in a few statements instead of a query per row.+ //+ // Why the replay and not one hoisted unit cost per item:+ //+ // - Standard and Average ignore the layers entirely (`computeCurrentUnitCost`+ // returns standardCost / itemCost.unitCost), so every row of an item gets+ // the same unit cost. The replay reproduces that for free.+ // - FIFO and LIFO take the remaining-quantity-weighted average of the open+ // layers. Adding a layer of quantity q at exactly that average u contributes+ // value q·u against quantity q, so the average is unchanged: (V + q·u) /+ // (R + q) = (u·R + q·u) / (R + q) = u. In EXACT arithmetic the cost is+ // therefore hoistable. It is not hoistable as written, because the layer is+ // stored as round(q·u, 5) (`buildCostLedgerRow`): row n+1 reads the rounded+ // cost back and divides by q, so the average drifts by up to half a unit of+ // the 5th decimal per row — and the drift is scaled up by the next row's+ // quantity. A 1-unit row at 1/3 stores 0.33333; a following 1000-unit row+ // then books 333.33, not 333.33333. Replaying the rounded layer keeps the+ // batch path byte-identical to the per-row path instead of "close".+ // - The fallback branch (no open layers → itemCost.unitCost) is covered by the+ // same replay: the first row opens a layer at that fallback cost, and every+ // later row averages over it.+ //+ // Rows whose quantity rounds to 0 open no layer the next row can see (the+ // open-layer query filters remainingQuantity > 0), so they are skipped here+ // exactly as the query would skip them.+ export function planIncreaseUnitCosts(+ itemCost: AdjustmentItemCost,+ openLayers: OpenCostLayer[],+ quantities: number[]+ ): PlannedIncrease[] {+ const layers = [...openLayers];+ return quantities.map((quantity) => {+ const unitCost = computeCurrentUnitCost(itemCost, layers);+ // Build the layer through the same builder the caller will insert with,+ // and read the stored values back off it — the replay must see what the+ // database would have handed the next row, not a second derivation of it.+ // Only quantity / remainingQuantity / cost are read, so the identity+ // fields are placeholders.+ const row = buildCostLedgerRow({+ entryType: "Positive Adjmt.",+ documentType: null,+ documentId: "",+ itemId: "",+ quantity,+ cost: quantity * unitCost,+ postingDate: "",+ companyId: ""+ });+ if ((row.remainingQuantity ?? 0) > 0) {+ // New layers carry no applied adjustment children.+ layers.push({+ quantity: row.quantity as number,+ remainingQuantity: row.remainingQuantity as number,+ cost: row.cost as number,+ appliedChildCost: 0+ });+ }+ return { unitCost, cost: quantity * unitCost };+ });+ }++ // Whether a movement carries value at all — `bookAdjustment`'s early return:+ // a Non-Inventory item or a zero-quantity movement books the ledger row alone,+ // with no cost layer and no journal.+ export function carriesAdjustmentValue(+ quantity: number,+ itemTrackingType: string | null+ ): boolean {+ return quantity !== 0 && itemTrackingType !== "Non-Inventory";+ }++ export interface StockRowPlanInput {+ itemId: string;+ quantity: number;+ itemTrackingType: string | null;+ }++ export interface StockRowPlan {+ /** false ⇒ ledger row only: no cost layer, no journal line. */+ carriesValue: boolean;+ /** The layer's cost, unrounded; 0 when the row carries no value. */+ cost: number;+ /** Whether this row contributes a journal line pair. */+ postsJournal: boolean;+ }++ // The whole-file plan the bulk opening-stock importer writes from, one entry+ // per source row in source order.+ //+ // This is the batching itself, kept pure and away from the transaction: group+ // the valued rows by item, replay each item's cost layers once+ // (`planIncreaseUnitCosts`), scatter the per-item costs back onto the rows+ // they came from, and decide which rows post to the GL. `bookAdjustment` makes+ // the same three decisions one movement at a time; getting the scatter or the+ // journal filter wrong here is what would put a wrong cost on every row, so it+ // is a function with a test rather than a loop inside a transaction.+ export function planStockRows(args: {+ rows: StockRowPlanInput[];+ itemCosts: ReadonlyMap<string, AdjustmentItemCost>;+ openLayersByItem: ReadonlyMap<string, OpenCostLayer[]>;+ }): StockRowPlan[] {+ const plans: StockRowPlan[] = args.rows.map((row) => ({+ carriesValue: carriesAdjustmentValue(row.quantity, row.itemTrackingType),+ cost: 0,+ postsJournal: false+ }));++ const rowIndexesByItem = new Map<string, number[]>();+ args.rows.forEach((row, rowIndex) => {+ if (!plans[rowIndex]!.carriesValue) return;+ const indexes = rowIndexesByItem.get(row.itemId) ?? [];+ indexes.push(rowIndex);+ rowIndexesByItem.set(row.itemId, indexes);+ });++ for (const [itemId, rowIndexes] of rowIndexesByItem) {+ const itemCost = args.itemCosts.get(itemId);+ if (!itemCost) {+ throw new Error(`No item cost for item ${itemId}`);+ }+ const increases = planIncreaseUnitCosts(+ itemCost,+ args.openLayersByItem.get(itemId) ?? [],+ rowIndexes.map((rowIndex) => args.rows[rowIndex]!.quantity)+ );+ rowIndexes.forEach((rowIndex, n) => {+ const cost = increases[n]!.cost;+ plans[rowIndex]!.cost = cost;+ // A zero-value movement posts no journal — `bookAdjustment`'s+ // `!accounting || cost === 0` guard, per row.+ plans[rowIndex]!.postsJournal = cost !== 0;+ });+ }++ return plans;+ }+ export interface AdjustmentItemCost {+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"];+ unitCost: number | null;+ standardCost: number | null;+ }++ export interface OpenCostLayer {+ quantity: number;+ remainingQuantity: number;+ cost: number;+ appliedChildCost: number;+ }++ // Current carrying unit cost for a POSITIVE adjustment's new layer / journal+ // value. Mirrors the valuation RPC's carrying CTE: FIFO/LIFO use the+ // weighted-average effective cost of open layers (including applied+ // invoice-vs-receipt children); Average/Standard come straight from itemCost.+ export function computeCurrentUnitCost(+ itemCost: AdjustmentItemCost,+ openLayers: OpenCostLayer[]+ ): number {+ switch (itemCost.costingMethod) {+ case "Standard":+ return Number(itemCost.standardCost ?? 0);+ case "Average":+ return Number(itemCost.unitCost ?? 0);+ case "FIFO":+ case "LIFO": {+ let remaining = 0;+ let value = 0;+ for (const layer of openLayers) {+ const quantity = Number(layer.quantity);+ const layerRemaining = Number(layer.remainingQuantity);+ if (quantity <= 0 || layerRemaining <= 0) continue;+ const effectiveUnitCost =+ (Number(layer.cost) + Number(layer.appliedChildCost)) / quantity;+ remaining += layerRemaining;+ value += layerRemaining * effectiveUnitCost;+ }+ if (remaining <= 0) return Number(itemCost.unitCost ?? 0);+ return value / remaining;+ }+ default:+ return Number(itemCost.unitCost ?? 0);+ }+ }+ export interface BookAdjustmentArgs {+ ledger: {+ postingDate: string; // yyyy-MM-dd+ itemId: string;+ // SIGNED delta: > 0 for Positive Adjmt., < 0 for Negative Adjmt.+ quantity: number;+ locationId: string | null;+ storageUnitId: string | null;+ trackedEntityId: string | null;+ entryType: "Positive Adjmt." | "Negative Adjmt.";+ // itemLedgerDocumentType — manual adjustments stay NULL (ledger rows keep+ // today's shape; 'Inventory Adjustment' exists only on journalLineDocumentType).+ // Non-Conformance / Inbound Inspection tag NCR-disposition & inspection-reject+ // write-offs (these also flow to the journal line's documentType). The full+ // enum is accepted because stock-movement corrections copy the ORIGINAL+ // movement's documentType so document-scoped movement views keep including+ // the fix.+ documentType?: Database["public"]["Enums"]["itemLedgerDocumentType"] | null;+ documentId?: string | null;+ correctionOfItemLedgerId?: string | null;+ comment?: string | null;+ // Reason for scrap/unscrap movements (documentType 'Scrap'); NULL for+ // every other adjustment. MES production scrap keeps its reason on+ // productionQuantity.scrapReasonId.+ scrapReasonId?: string | null;+ companyId: string;+ createdBy: string;+ };+ item: {+ itemTrackingType: string | null;+ replenishmentSystem:+ | Database["public"]["Enums"]["itemReplenishmentSystem"]+ | null;+ itemPostingGroupId?: string | null;+ };+ itemCost: AdjustmentItemCost;+ // null ⇒ no journal: ledger + cost layers only (asset transfers and rental+ // returns value the movement inside a journal of their own)+ accounting: {+ // Provisional before the company's accounting cutover, Posted after it+ // (journalPostingStatus). A Provisional journal has no accounting period.+ postingStatus: AutomaticJournalStatus;+ accountingPeriodId: string | null;+ accountDefaults: {+ rawMaterialsAccount: string;+ finishedGoodsAccount: string;+ inventoryAdjustmentVarianceAccount: string;+ };+ // Offset (non-inventory) side of the balanced pair. Defaults to+ // inventoryAdjustmentVarianceAccount; NCR-disposition / inspection-reject+ // write-offs pass the company's scrapAccount so cost of quality is separable+ // on the P&L.+ offsetAccount?: string | null;+ offsetDescription?: string;+ // journal.sourceType for a header this call creates (default+ // 'Inventory Adjustment'). Ignored when getJournalId supplies a shared journal.+ sourceType?: Database["public"]["Enums"]["journalEntrySourceType"];+ description: string;+ userId: string;+ // active dimensions for the company group, entityType → dimension id+ // (Item / ItemPostingGroup / Location are consulted) — journal lines get+ // journalLineDimension tags for whichever are configured+ dimensions?: Record<string, string>;+ // Additional journalLineDimension tags beyond Item/ItemPostingGroup/+ // Location (ScrapReason / WorkCenter / Employee for scrap postings).+ // entityType must be a dimensionEntityType value present in `dimensions`;+ // valueId is the referenced entity id (polymorphic, no FK).+ extraDimensions?: Array<{ entityType: string; valueId: string }>;+ // When set, lines append to this shared journal instead of the core+ // creating one journal per movement — inventory counts post ONE journal+ // per count with a line pair per variance. Lazy (called only when a+ // movement writes a pair: one with value, or any outbound one) so a run+ // of zero-cost increases never creates an empty journal.+ getJournalId?: () => Promise<string>;+ } | null;+ // storage-unit-transfer legs move stock between bins without changing its+ // value: ledger row only — no cost layers, no journal+ skipValuation?: boolean;+ // Book an INCREASE's new cost layer at this unit cost instead of+ // computeCurrentUnitCost — Unscrap reverses at the original scrapped cost+ // (Oracle Return-from-Scrap precedent). Ignored for decreases, which always+ // relieve via calculateCOGS.+ fixedUnitCost?: number;+ }++ export interface BookAdjustmentResult {+ itemLedgerId: string;+ journalId: string | null;+ cost: number;+ }++ export interface CreateAdjustmentJournalArgs {+ companyId: string;+ // null for a Provisional journal: it has no accounting period+ accountingPeriodId: string | null;+ status: AutomaticJournalStatus;+ description: string;+ postingDate: string;+ userId: string;+ sourceType?: Database["public"]["Enums"]["journalEntrySourceType"];+ }++ // One journal header for adjustment postings ('Inventory Adjustment' source,+ // Provisional before the accounting cutover, Posted after it). Manual adjustments create one per movement; inventory+ // counts share ONE journal per count post via accounting.getJournalId.+ export async function createAdjustmentJournal(+ trx: Transaction<DB>,+ args: CreateAdjustmentJournalArgs+ ): Promise<string> {+ const journalEntryId = await getNextSequence(+ trx,+ "journalEntry",+ args.companyId+ );+ const journal = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId: args.accountingPeriodId,+ description: args.description,+ postingDate: args.postingDate,+ companyId: args.companyId,+ sourceType: args.sourceType ?? "Inventory Adjustment",+ status: args.status,+ postedAt: datetime.timestamp(),+ postedBy: args.userId,+ createdBy: args.userId+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ return journal.id;+ }++ // The open cost layers an INCREASE values itself against, per item. Same+ // filters as calculateCOGS so both sides of the math agree: positive+ // remaining quantity, not an adjustment child, and not a 'Purchase Order'+ // planning artifact. Applied adjustment children (invoice-vs-receipt price+ // corrections) are folded into each layer's `appliedChildCost`.+ //+ // Takes a LIST of items so the bulk importer reads every item it is about to+ // post in a couple of queries instead of two per row. `bookAdjustment` passes+ // one.+ const CHILD_LAYER_CHUNK_SIZE = 500;++ export async function loadOpenCostLayers(+ trx: Transaction<DB>,+ args: { itemIds: string[]; companyId: string }+ ): Promise<Map<string, OpenCostLayer[]>> {+ const byItem = new Map<string, OpenCostLayer[]>();+ if (args.itemIds.length === 0) return byItem;++ const openLayers = await trx+ .selectFrom("costLedger")+ .select(["id", "itemId", "quantity", "remainingQuantity", "cost"])+ .where("itemId", "in", args.itemIds)+ .where("companyId", "=", args.companyId)+ .where("remainingQuantity", ">", 0)+ .where("adjustment", "=", false)+ .where("appliesToCostLedgerId", "is", null)+ .where((eb) =>+ eb.or([+ eb("documentType", "is", null),+ eb("documentType", "!=", "Purchase Order")+ ])+ )+ .execute();+ if (openLayers.length === 0) return byItem;++ // The child lookup is chunked over the LAYER ids, not the item ids: open+ // layers are receipts not yet consumed, so their count is data-dependent and+ // unbounded. The bulk importer reaches here with every referenced item's+ // layers at once, and a single `in (...)` over them would exceed Postgres'+ // 65535 bind parameters on a large file against well-stocked items.+ const appliedChildCostByLayer = new Map<string, number>();+ const layerIds = openLayers.map((layer) => layer.id);+ for (let i = 0; i < layerIds.length; i += CHILD_LAYER_CHUNK_SIZE) {+ const children = await trx+ .selectFrom("costLedger")+ .select(["appliesToCostLedgerId", "cost"])+ .where(+ "appliesToCostLedgerId",+ "in",+ layerIds.slice(i, i + CHILD_LAYER_CHUNK_SIZE)+ )+ .where("companyId", "=", args.companyId)+ .execute();+ for (const child of children) {+ const key = child.appliesToCostLedgerId as string;+ appliedChildCostByLayer.set(+ key,+ (appliedChildCostByLayer.get(key) ?? 0) + Number(child.cost)+ );+ }+ }++ for (const layer of openLayers) {+ const itemId = layer.itemId as string;+ const list = byItem.get(itemId) ?? [];+ list.push({+ quantity: Number(layer.quantity),+ remainingQuantity: Number(layer.remainingQuantity),+ cost: Number(layer.cost),+ appliedChildCost: appliedChildCostByLayer.get(layer.id) ?? 0+ });+ byItem.set(itemId, list);+ }+ return byItem;+ }++ // Book one adjustment movement inside the caller's transaction: the item+ // ledger row, then its valuation (`valueMovement`). Tracked-entity mutations+ // are the caller's responsibility.+ export async function bookAdjustment(+ trx: Transaction<DB>,+ args: BookAdjustmentArgs+ ): Promise<BookAdjustmentResult> {+ const { ledger, item, itemCost, accounting, skipValuation } = args;++ const inserted = await trx+ .insertInto("itemLedger")+ .values(+ buildItemLedgerRow({+ postingDate: ledger.postingDate,+ entryType: ledger.entryType,+ documentType: ledger.documentType,+ documentId: ledger.documentId,+ correctionOfItemLedgerId: ledger.correctionOfItemLedgerId,+ itemId: ledger.itemId,+ locationId: ledger.locationId,+ storageUnitId: ledger.storageUnitId,+ trackedEntityId: ledger.trackedEntityId,+ quantity: ledger.quantity,+ comment: ledger.comment,+ scrapReasonId: ledger.scrapReasonId,+ companyId: ledger.companyId,+ createdBy: ledger.createdBy+ })+ )+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (skipValuation) {+ return { itemLedgerId: inserted.id, journalId: null, cost: 0 };+ }++ const { journalId, cost } = await valueMovement(trx, {+ movement: {+ postingDate: ledger.postingDate,+ itemId: ledger.itemId,+ quantity: ledger.quantity,+ locationId: ledger.locationId,+ entryType: ledger.entryType,+ documentType: ledger.documentType,+ documentId: ledger.documentId ?? inserted.id,+ trackedEntityId: ledger.trackedEntityId,+ companyId: ledger.companyId+ },+ item,+ itemCost,+ accounting,+ fixedUnitCost: args.fixedUnitCost+ });++ return { itemLedgerId: inserted.id, journalId, cost };+ }++ export interface ValueMovementArgs {+ movement: {+ postingDate: string; // yyyy-MM-dd+ itemId: string;+ // SIGNED: < 0 relieves cost layers, > 0 opens one+ quantity: number;+ locationId: string | null;+ entryType: Database["public"]["Enums"]["itemLedgerType"];+ documentType?: Database["public"]["Enums"]["itemLedgerDocumentType"] | null;+ // costLedger.documentId and journalLine.documentId+ documentId: string;+ // The moved unit or batch; only a serial unit's is used for costing.+ trackedEntityId?: string | null;+ companyId: string;+ };+ item: BookAdjustmentArgs["item"];+ itemCost: AdjustmentItemCost;+ accounting: BookAdjustmentArgs["accounting"];+ fixedUnitCost?: number;+ }++ // Value a stock movement whose item ledger row the caller has already written:+ // cost-layer maintenance (consume via calculateCOGS on decreases, open a layer+ // at current cost — or `fixedUnitCost` — on increases) and, when the caller+ // passes `accounting`, a balanced journal of the inventory account against+ // the offset account: for every decrease, and for an increase with value. `bookAdjustment` is this plus the ledger+ // row; maintenance consumption calls it directly because its ledger rows are+ // written alongside tracked-entity splits.+ export async function valueMovement(+ trx: Transaction<DB>,+ args: ValueMovementArgs+ ): Promise<{ journalId: string | null; cost: number }> {+ const { movement, item, itemCost, accounting } = args;+ const { companyId, documentId } = movement;++ if (!carriesAdjustmentValue(movement.quantity, item.itemTrackingType)) {+ return { journalId: null, cost: 0 };+ }++ const absQuantity = Math.abs(movement.quantity);+ // A serial unit's movement is costed by specific identification: an+ // increase books a layer that belongs to the unit, and a decrease relieves+ // that layer first (calculateCOGS / cost-layer-order.ts). A batch entity is+ // split and re-pointed as it moves, so its layers stay FIFO / LIFO.+ const serialId =+ item.itemTrackingType === "Serial"+ ? (movement.trackedEntityId ?? null)+ : null;+ let cost = 0;++ if (movement.quantity < 0) {+ // Decrease: relieve carrying value exactly as shipments do — consume+ // layers (FIFO/LIFO) / current cost (Average/Standard).+ const cogs = await calculateCOGS(trx, {+ itemId: movement.itemId,+ quantity: absQuantity,+ companyId,+ trackedEntityIds: serialId ? [serialId] : []+ });+ cost = cogs.totalCost;++ await trx+ .insertInto("costLedger")+ .values(+ buildCostLedgerRow({+ entryType: movement.entryType,+ documentType: movement.documentType,+ documentId,+ itemId: movement.itemId,+ quantity: -absQuantity,+ cost: -cogs.totalCost,+ postingDate: movement.postingDate,+ trackedEntityId: serialId,+ companyId+ })+ )+ .execute();+ } else if (args.fixedUnitCost != null) {+ // Increase at a caller-fixed unit cost: Unscrap restores stock at the+ // ORIGINAL scrapped cost so a scrap→unscrap round trip nets zero P&L.+ cost = absQuantity * args.fixedUnitCost;++ await trx+ .insertInto("costLedger")+ .values(+ buildCostLedgerRow({+ entryType: movement.entryType,+ documentType: movement.documentType,+ documentId,+ itemId: movement.itemId,+ quantity: absQuantity,+ cost,+ postingDate: movement.postingDate,+ trackedEntityId: serialId,+ companyId+ })+ )+ .execute();+ } else {+ // Increase: create a layer at the item's current carrying cost.+ const openLayers = await loadOpenCostLayers(trx, {+ itemIds: [movement.itemId],+ companyId+ });+ const unitCost = computeCurrentUnitCost(+ itemCost,+ openLayers.get(movement.itemId) ?? []+ );+ cost = absQuantity * unitCost;++ await trx+ .insertInto("costLedger")+ .values(+ buildCostLedgerRow({+ entryType: movement.entryType,+ documentType: movement.documentType,+ documentId,+ itemId: movement.itemId,+ quantity: absQuantity,+ cost,+ postingDate: movement.postingDate,+ trackedEntityId: serialId,+ companyId+ })+ )+ .execute();+ }++ // An inbound movement at no value posts no journal (nothing to tie out).+ // An outbound one always writes its pair, at zero too: every outbound cost+ // row carries a pair, because the accounting enable's re-cost may give it+ // a cost and adjusts the pair it finds. With no pair, and another journal+ // of the document that day, neither the legacy backfill (which skips a+ // document-day that has a journal) nor the re-cost could book the cost.+ if (!accounting || (cost === 0 && movement.quantity > 0)) {+ return { journalId: null, cost };+ }++ const journalId = accounting.getJournalId+ ? await accounting.getJournalId()+ : await createAdjustmentJournal(trx, {+ companyId,+ accountingPeriodId: accounting.accountingPeriodId,+ status: accounting.postingStatus,+ description: accounting.description,+ postingDate: movement.postingDate,+ userId: accounting.userId,+ sourceType: accounting.sourceType+ });++ const [inventoryLine, offsetLine] = buildAdjustmentJournalLines({+ journalId,+ documentId,+ documentType: movement.documentType,+ journalLineReference: nanoid(),+ isGain: movement.quantity > 0,+ cost,+ quantity: absQuantity,+ replenishmentSystem: item.replenishmentSystem,+ accountDefaults: accounting.accountDefaults,+ offsetAccount: accounting.offsetAccount,+ offsetDescription: accounting.offsetDescription,+ companyId+ });+ const journalLines = await trx+ .insertInto("journalLine")+ .values([inventoryLine, offsetLine])+ .returning(["id"])+ .execute();++ const journalLineDimensionInserts = buildJournalLineDimensions({+ journalLineIds: journalLines.map((line) => line.id),+ dimensions: accounting.dimensions ?? {},+ itemId: movement.itemId,+ itemPostingGroupId: item.itemPostingGroupId,+ locationId: movement.locationId,+ extraDimensions: accounting.extraDimensions,+ companyId+ });+ if (journalLineDimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(journalLineDimensionInserts)+ .execute();+ }++ return { journalId, cost };+ }+ type PostableTable =+ | "receipt"+ | "shipment"+ | "purchaseInvoice"+ | "salesInvoice";++ /** Call BEFORE the posting function's `try`: its failure handler resets the+ * document to Draft, which must not happen to one that is already posted. */+ export async function assertPostable(+ db: Kysely<KyselyDatabase>,+ table: PostableTable,+ id: string,+ companyId: string+ ): Promise<void> {+ const document = await db+ .selectFrom(table)+ .select(["status"])+ .where("id", "=", id)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (document && !["Draft", "Pending"].includes(document.status ?? "")) {+ throw new ServerFnError(+ `Cannot post: it is already ${document.status}`,+ 409+ );+ }+ }+ // Manual accounting work (recognition runs here) runs only after the+ // company's accounting cutover: before it, journals are Provisional and count+ // nowhere (.ai/specs/implemented/2026-10-08-accounting-cutover.md section 1). The ERP+ // service functions refuse the same work with the same message.+ export const ACCOUNTING_NOT_STARTED =+ "Set up accounting before you post journals, runs or period closes.";++ export async function assertAccountingCutover(+ db: Kysely<KyselyDatabase> | Transaction<KyselyDatabase>,+ companyId: string+ ) {+ if (!(await readAccountingCutoverDate(db, companyId))) {+ throw new InvalidInputError(ACCOUNTING_NOT_STARTED);+ }+ }+ type AccountDefaults = Database["public"]["Tables"]["accountDefault"]["Row"];++ /**+ * The optional defaults a sales invoice line may stand in for, with the class+ * each one must have. A stand-in line is signed for that class, so the enable+ * can re-point it without changing its amount.+ */+ export const STAND_IN_CLASS = {+ leaseRevenueAccount: "Revenue",+ netInvestmentInLeasesAccount: "Asset",+ salesShippingRevenueAccount: "Revenue"+ } as const satisfies Partial<Record<OptionalDefaultRole, string>>;++ export type StandInRole = keyof typeof STAND_IN_CLASS;++ /** The prefix of a placeholder id. Never an account id: those come from id('…'). */+ export const STAND_IN_PREFIX = "stand-in:";++ /** The stand-in bookkeeping of one sales invoice posting. */+ export function salesInvoiceStandIns(+ defaults: Pick<AccountDefaults, StandInRole | "retainedEarningsAccount">,+ postingStatus: AutomaticJournalStatus+ ) {+ const roles = new Map<string, StandInRole>();++ /** The account a line takes for `role`: the default when it is set; a+ * placeholder before the cutover; null after it. */+ const defaultId = (role: StandInRole): string | null => {+ if (defaults[role]) return defaults[role];+ if (postingStatus === "Posted") return null;+ const resolved = resolveDefaultAccount(defaults, role, postingStatus);+ if (!resolved.accountDefaultRole) return resolved.accountId;+ const placeholder = `${STAND_IN_PREFIX}${role}`;+ roles.set(placeholder, role);+ return placeholder;+ };++ const isPlaceholder = (id: string) => roles.has(id);++ /** The account id a row stores: Retained Earnings for a placeholder. */+ const storedAccountId = (id: string) =>+ roles.has(id) ? defaults.retainedEarningsAccount : id;++ /** A journal line as stored: a placeholder becomes Retained Earnings and+ * the line names the default it stands in for. */+ const storedLine = <T extends { accountId?: string | null }>(line: T) =>+ line.accountId && roles.has(line.accountId)+ ? {+ ...line,+ accountId: defaults.retainedEarningsAccount,+ accountDefaultRole: roles.get(line.accountId)!+ }+ : line;++ /** One account per placeholder, of the class its default must have. */+ const placeholderAccounts = (companyGroupId: string): SalesPostingAccount[] =>+ [...roles].map(([placeholder, role]) => ({+ id: placeholder,+ class: STAND_IN_CLASS[role],+ active: true,+ isGroup: false,+ companyGroupId+ }));++ return {+ defaultId,+ isPlaceholder,+ storedAccountId,+ storedLine,+ placeholderAccounts+ };+ }+ // What ONE serial unit would leave stock at right now, without consuming+ // anything: the same arithmetic calculateCOGS runs for a quantity of one —+ // Standard at the standard cost, Average at the unit cost, FIFO / LIFO from+ // the unit's own layer first (cost-layer-order.ts), then the unstamped layers,+ // each with its price-correction children, falling back to the item's unit+ // cost when no layer is left. Pure, so a whole item's units are valued from+ // one read of its layers.++ export type UnitCostLayer = {+ id: string;+ trackedEntityId: string | null;+ quantity: number;+ cost: number;+ remainingQuantity: number;+ };++ export type UnitCostChild = {+ quantity: number;+ cost: number;+ remainingQuantity: number;+ };++ export type UnitCostBasis = {+ costingMethod: Database["public"]["Enums"]["itemCostingMethod"];+ unitCost: number | null;+ standardCost: number | null;+ };++ export function serialUnitCost(args: {+ itemCost: UnitCostBasis;+ // Open layers already in FIFO / LIFO order, as calculateCOGS reads them.+ layers: UnitCostLayer[];+ // Open price-correction children per layer id, oldest first.+ childrenByLayer: ReadonlyMap<string, UnitCostChild[]>;+ trackedEntityId: string;+ }): number {+ const { itemCost } = args;+ switch (itemCost.costingMethod) {+ case "Standard":+ return Number(itemCost.standardCost ?? 0);+ case "Average":+ return Number(itemCost.unitCost ?? 0);+ case "FIFO":+ case "LIFO": {+ let remaining = 1;+ let total = 0;+ const ordered = orderLayersForConsumption(args.layers, [+ args.trackedEntityId+ ]);+ for (const layer of ordered) {+ if (remaining <= 0) break;+ const layerRemaining = Number(layer.remainingQuantity);+ if (layerRemaining <= 0) continue;+ const layerUnitCost =+ Number(layer.quantity) > 0+ ? Number(layer.cost) / Number(layer.quantity)+ : 0;+ const taken = Math.min(remaining, layerRemaining);+ total += taken * layerUnitCost;+ remaining -= taken;++ let unapplied = taken;+ for (const child of args.childrenByLayer.get(layer.id) ?? []) {+ if (unapplied <= 0) break;+ const childRemaining = Number(child.remainingQuantity);+ const perUnitBump =+ Number(child.quantity) > 0+ ? Number(child.cost) / Number(child.quantity)+ : 0;+ const applied = Math.min(childRemaining, unapplied);+ total += applied * perUnitBump;+ unapplied -= applied;+ }+ }+ if (remaining > 0) total += remaining * Number(itemCost.unitCost ?? 0);+ return total;+ }+ default:+ throw new Error(`Unsupported costing method: ${itemCost.costingMethod}`);+ }+ }+ export async function getStorageUnitId(+ trx: Transaction<DB>,+ itemId: string,+ locationId: string,+ storageUnitId?: string+ ): Promise<string | undefined> {+ if (storageUnitId) return storageUnitId;++ const pickMethod = await trx+ .selectFrom("pickMethod")+ .where("itemId", "=", itemId)+ .where("locationId", "=", locationId)+ .select("defaultStorageUnitId")+ .executeTakeFirst();++ if (pickMethod?.defaultStorageUnitId) return pickMethod.defaultStorageUnitId;++ const storageUnitWithHighestQuantity =+ await getStorageUnitWithHighestQuantity(trx, itemId, locationId);++ return storageUnitWithHighestQuantity ?? undefined;+ }++ /**+ * Where each tracked entity holds stock, and how much, per location (see+ * `resolveTrackedEntityBins`: `null` is the unassigned bin). The lookup returns+ * `undefined` for an entity with no positive bin at that location.+ */+ export async function getTrackedEntityBins(+ db: Kysely<DB>,+ args: { trackedEntityIds: string[]; locationIds: string[]; companyId: string }+ ): Promise<+ (trackedEntityId: string, locationId: string) => TrackedEntityBin | undefined+ > {+ if (args.trackedEntityIds.length === 0 || args.locationIds.length === 0) {+ return () => undefined;+ }++ const rows = await db+ .selectFrom("itemLedger")+ .where("trackedEntityId", "in", args.trackedEntityIds)+ .where("locationId", "in", args.locationIds)+ .where("companyId", "=", args.companyId)+ .select(["trackedEntityId", "locationId", "storageUnitId", "quantity"])+ .execute();++ const binsByLocation = new Map<string, Map<string, TrackedEntityBin>>();+ for (const locationId of args.locationIds) {+ binsByLocation.set(+ locationId,+ resolveTrackedEntityBins(rows.filter((r) => r.locationId === locationId))+ );+ }+ return (trackedEntityId, locationId) =>+ binsByLocation.get(locationId)?.get(trackedEntityId);+ }++ /** A tracked entity's on-hand in one bin; `null` is the unassigned bin. */+ export async function getTrackedEntityOnHandInBin(+ trx: Transaction<DB>,+ args: {+ trackedEntityId: string;+ locationId: string;+ storageUnitId: string | null;+ companyId: string;+ }+ ): Promise<number> {+ const row = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", args.trackedEntityId)+ .where("locationId", "=", args.locationId)+ .where("storageUnitId", "is not distinct from", args.storageUnitId)+ .where("companyId", "=", args.companyId)+ .select((eb) => eb.fn.sum<number>("quantity").as("onHand"))+ .executeTakeFirst();+ return Number(row?.onHand ?? 0);+ }++ // Utility function to get the storage unit with the highest quantity+ export async function getStorageUnitWithHighestQuantity(+ trx: Transaction<DB>,+ itemId: string,+ locationId: string+ ): Promise<string | null> {+ const storageUnitWithHighestQuantity = await trx+ .selectFrom("itemLedger")+ .where("itemId", "=", itemId)+ .where("locationId", "=", locationId)+ .where("storageUnitId", "is not", null)+ .groupBy("storageUnitId")+ .select([+ "storageUnitId",+ (eb) => eb.fn.sum("quantity").as("totalQuantity")+ ])+ .having((eb) => eb.fn.sum("quantity"), ">", 0)+ .orderBy("totalQuantity", "desc")+ .executeTakeFirst();++ return storageUnitWithHighestQuantity?.storageUnitId ?? null;+ }++ // Utility function to update pickMethod defaultStorageUnitId if this is the only non-null storage unit+ export async function updatePickMethodDefaultStorageUnitIfNeeded(+ trx: Transaction<DB>,+ itemId: string,+ locationId: string | null | undefined,+ storageUnitId: string | null | undefined,+ companyId: string,+ userId: string+ ): Promise<void> {+ // Only proceed if storageUnitId and locationId are not null+ if (!storageUnitId || !locationId) return;++ // Check if there are other non-null storage units for this item/location+ const otherStorageUnits = await trx+ .selectFrom("itemLedger")+ .where("itemId", "=", itemId)+ .where("locationId", "=", locationId)+ .where("storageUnitId", "is not", null)+ .where("storageUnitId", "!=", storageUnitId)+ .select("storageUnitId")+ .executeTakeFirst();++ // If there are no other non-null storage units, update or insert pickMethod+ if (!otherStorageUnits) {+ const existingPickMethod = await trx+ .selectFrom("pickMethod")+ .where("itemId", "=", itemId)+ .where("locationId", "=", locationId)+ .where("companyId", "=", companyId)+ .select("defaultStorageUnitId")+ .executeTakeFirst();++ if (existingPickMethod) {+ // Update existing pickMethod+ await trx+ .updateTable("pickMethod")+ .set({+ defaultStorageUnitId: storageUnitId,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("itemId", "=", itemId)+ .where("locationId", "=", locationId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ // Insert new pickMethod+ await trx+ .insertInto("pickMethod")+ .values({+ itemId,+ locationId,+ defaultStorageUnitId: storageUnitId,+ companyId,+ createdBy: userId,+ createdAt: datetime.timestamp()+ })+ .execute();+ }+ }+ }+ export type SupplierPartPriceConverter = {+ /** The currency a supplier part's price is in (NULL = base). */+ currencyOf: (partCurrencyCode: string | null) => string;+ /** A price per purchase unit in the DOCUMENT's currency, in the part's. */+ toPartCurrency: (price: number, partCurrencyCode: string | null) => number;+ };++ /**+ * Converts prices learned from a purchase document (a supplier quote, order or+ * invoice) into the currency of the supplier part that records them. A part+ * keeps the currency it was set up in; a price in that same currency is copied+ * exactly, any other crosses through base at the document's own rate and the+ * part currency's CURRENT rate. A missing rate raises (`get_exchange_rate`)+ * rather than recording the price at par.+ *+ * A NULL document or part currency is the company base currency. Rates are+ * loaded once, for every part currency the caller will convert into.+ */+ export async function getSupplierPartPriceConverter(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ document: { currencyCode: string | null; exchangeRate: number },+ partCurrencyCodes: (string | null)[]+ ): Promise<SupplierPartPriceConverter> {+ const company = await db+ .selectFrom("company")+ .select("baseCurrencyCode")+ .where("id", "=", companyId)+ .executeTakeFirstOrThrow();+ const baseCurrencyCode = company.baseCurrencyCode;++ const currencyOf = (code: string | null) =>+ supplierPartCurrency(code, baseCurrencyCode);+ const from: CurrencyRate = {+ currencyCode: currencyOf(document.currencyCode),+ exchangeRate: document.exchangeRate+ };++ const codes = [+ ...new Set(+ partCurrencyCodes+ .map(currencyOf)+ .filter((code) => code !== from.currencyCode)+ )+ ];++ const rates = new Map<string, number>();+ if (codes.length > 0) {+ const { rows } = await sql<{ code: string; rate: number }>`+ SELECT code, get_exchange_rate(${companyId}, code) AS rate+ FROM unnest(${codes}::text[]) AS code+ `.execute(db);+ for (const row of rows) rates.set(row.code, Number(row.rate));+ }++ return {+ currencyOf,+ toPartCurrency: (price, partCurrencyCode) => {+ const currencyCode = currencyOf(partCurrencyCode);+ return convertUnitPrice(price, from, {+ currencyCode,+ exchangeRate:+ currencyCode === from.currencyCode+ ? from.exchangeRate+ : rates.get(currencyCode)!+ });+ }+ };+ }+ type JournalLine = Selectable<KyselyDatabase["journalLine"]>;++ /**+ * Voids a journal with a negated copy: a new journal dated `date` (in the+ * period `periodMode` resolves for it once the company has a cutover; a+ * Provisional journal has none), each original line negated with its+ * documents, account default role and dimensions. The caller checks the+ * original's provenance and passes its lines. Returns the copy's id.+ *+ * Used by the charge, reimbursement and lease voids.+ */+ export async function insertNegatedJournal(+ trx: Transaction<KyselyDatabase>,+ args: {+ companyId: string;+ userId: string;+ originalLines: JournalLine[];+ description: string;+ sourceType: Database["public"]["Enums"]["journalEntrySourceType"];+ postingStatus: AutomaticJournalStatus;+ date: string;+ periodMode: "current" | "historical-with-shift";+ postedAt: string;+ }+ ): Promise<string> {+ const { companyId, userId, originalLines } = args;+ const period =+ args.postingStatus === "Posted"+ ? await resolveAccountingPeriod(+ trx,+ companyId,+ args.date,+ args.periodMode+ )+ : null;+ const reversal = await trx+ .insertInto("journal")+ .values({+ journalEntryId: await getNextSequence(trx, "journalEntry", companyId),+ accountingPeriodId: period?.id ?? null,+ description: args.description,+ postingDate: period?.postingDate ?? args.date,+ companyId,+ sourceType: args.sourceType,+ status: args.postingStatus,+ postedAt: args.postedAt,+ postedBy: userId,+ createdBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ if (originalLines.length === 0) return reversal.id;++ const reversalLineIds = await allocateJournalLineIds(+ trx,+ originalLines.length+ );+ await trx+ .insertInto("journalLine")+ .values(+ originalLines.map((line, index) => ({+ id: reversalLineIds[index],+ journalId: reversal.id,+ accountId: line.accountId,+ amount: -Number(line.amount),+ quantity: line.quantity,+ description: `VOID: ${line.description ?? ""}`,+ documentType: line.documentType,+ documentId: line.documentId,+ documentLineReference: line.documentLineReference,+ journalLineReference: line.journalLineReference,+ accountDefaultRole: line.accountDefaultRole,+ companyId+ }))+ )+ .execute();++ const dimensions = await trx+ .selectFrom("journalLineDimension")+ .select(["journalLineId", "dimensionId", "valueId"])+ .where("companyId", "=", companyId)+ .where(+ "journalLineId",+ "in",+ originalLines.map((line) => line.id)+ )+ .execute();+ if (dimensions.length > 0) {+ const reversalByOriginal = new Map(+ originalLines.map((line, index) => [line.id, reversalLineIds[index]])+ );+ await trx+ .insertInto("journalLineDimension")+ .values(+ dimensions.map((dimension) => {+ const journalLineId = reversalByOriginal.get(dimension.journalLineId);+ if (!journalLineId) {+ throw new Error("Failed to map a reversed journal line");+ }+ return { ...dimension, journalLineId, companyId };+ })+ )+ .execute();+ }+ return reversal.id;+ }+ // Record ids in an input come straight from the caller and prove nothing about+ // tenancy: a permission check authorizes the CALLER for companyId, not the ids it+ // sends. Several of these ids are only ever written as references into the+ // caller's own rows (a ledger's locationId, an activity's trackedEntityId), and+ // their single-column FKs accept a row from any company, so nothing downstream+ // refuses a foreign id. Re-read them under companyId before writing.++ type CompanyRecordTable =+ | "inspection"+ | "inspectionSample"+ | "jobOperationStep"+ | "location"+ | "nonConformance"+ | "productionEvent"+ | "purchaseOrder"+ | "scrapReason"+ | "storageUnit"+ | "trackedEntity"+ | "workCenter";++ /**+ * Throws `NotFoundError` unless every provided id is a row of `table` in+ * `companyId`. Null / undefined / duplicate ids are ignored, so optional input+ * fields stay optional. One query per call — collect the ids first.+ */+ export async function assertCompanyRecords(+ db: Kysely<KyselyDatabase>,+ table: CompanyRecordTable,+ ids: Iterable<string | null | undefined>,+ companyId: string,+ label: string+ ): Promise<void> {+ const unique = [+ ...new Set([...ids].filter((id): id is string => typeof id === "string"))+ ];+ if (unique.length === 0) return;++ const rows = await db+ .selectFrom(table)+ .select("id")+ .where("id", "in", unique)+ .where("companyId", "=", companyId)+ .execute();++ if (rows.length !== unique.length) {+ throw new NotFoundError(`${label} not found`);+ }+ }+ export type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";++ /** An operator's request to consume or move expired material anyway. */+ export type ExpiryOverride = { allowed: boolean; reason: string | null };++ /**+ * The company's expired-entity policy (`companySettings.inventoryShelfLife`).+ * `Block` when unset, so the safe behavior is the default.+ */+ export async function getExpiredEntityPolicy(+ db: Kysely<KyselyDatabase>,+ companyId: string+ ): Promise<ExpiredEntityPolicy> {+ const row = await db+ .selectFrom("companySettings")+ .select("inventoryShelfLife")+ .where("id", "=", companyId)+ .executeTakeFirst();+ const settings = row?.inventoryShelfLife as {+ expiredEntityPolicy?: ExpiredEntityPolicy;+ } | null;+ return settings?.expiredEntityPolicy ?? "Block";+ }++ /** The entities that expired before `today`; an unparseable date never counts. */+ export function expiredEntities<E extends { expirationDate: string | null }>(+ entities: E[],+ today: CalendarDate+ ): E[] {+ return entities.filter(({ expirationDate }) => {+ if (!expirationDate) return false;+ try {+ return parseDate(expirationDate).compare(today) < 0;+ } catch {+ return false;+ }+ });+ }++ /**+ * What the policy does with expired material: `warn` under `Warn`, `allow`+ * under `BlockWithOverride` when the override carries a reason, else `block`.+ */+ export function expiryVerdict(+ policy: ExpiredEntityPolicy,+ override: ExpiryOverride+ ): "warn" | "allow" | "block" {+ if (policy === "Warn") return "warn";+ if (+ policy === "BlockWithOverride" &&+ override.allowed &&+ (override.reason?.trim().length ?? 0) > 0+ ) {+ return "allow";+ }+ return "block";+ }+ /**+ * `"attributes" @> {…}`: the containment form the `trackedEntity` GIN index+ * serves. `attributes->>'Key' = value` reads the same rows but cannot use the+ * index, so it walks every tracked entity of the company.+ */+ export function attributesContain(values: Record<string, string>) {+ return sql<boolean>`"attributes" @> ${JSON.stringify(values)}::jsonb`;+ }+ /**+ * Who stands behind a posting's client: the service role (the system), an API+ * key (checked against its scopes) or the signed-in user (checked against the+ * user's claims). Never derive it from input.+ */+ export type PostingCaller =+ | { type: "system" }+ | { type: "apiKey"; apiKey: string }+ | { type: "user" };++ /**+ * The client's key decides the caller. A user's token must be `userId`'s,+ * since the permissions are read for that user. Never replace this with a flag+ * the caller passes: /api/v1 fills unknown parameters from the body.+ */+ export function postingCaller(+ client: SupabaseClient<Database>,+ userId: string+ ): PostingCaller {+ const { supabaseKey, headers = {} } = client as unknown as {+ supabaseKey?: string;+ headers?: Record<string, string>;+ };+ const apiKey = headers["carbon-key"];+ if (apiKey) return { type: "apiKey", apiKey };+ if (SUPABASE_SERVICE_ROLE_KEY && supabaseKey === SUPABASE_SERVICE_ROLE_KEY) {+ return { type: "system" };+ }+ if (bearerSubject(headers.Authorization) !== userId) {+ throw new ForbiddenError("userId does not match the signed-in user");+ }+ return { type: "user" };+ }++ /** The `sub` of a `Bearer` JWT, unverified. The token comes from this+ * process's own session, or from an MES internal call that forwards it under+ * its signature (caller mode). Either way the authority is the `userId` that+ * session or signature vouches for: this only checks that the token names the+ * same user. */+ function bearerSubject(authorization: string | undefined): string | undefined {+ const payload = authorization?.replace(/^Bearer\s+/i, "").split(".")[1];+ if (!payload) return undefined;+ try {+ return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")).sub;+ } catch {+ return undefined;+ }+ }++ /** Refuses a caller who does not hold `required` in the company. */+ export async function authorizePostingCaller(+ {+ db,+ companyId,+ userId+ }: Pick<PostingHandles, "db" | "companyId" | "userId">,+ caller: PostingCaller,+ required: Permissions+ ): Promise<void> {+ if (caller.type === "system") return;+ if (required === "system") {+ throw new ForbiddenError("Only server-side callers may run this");+ }+ if (caller.type === "apiKey") {+ return authorizeApiKey(db, companyId, caller.apiKey, required);+ }+ const { rows } = await sql<{+ claims: Record<string, unknown> | null;+ }>`SELECT get_claims(${userId}, ${companyId}) AS claims`.execute(db);+ const claims = rows[0]?.claims ?? {};+ // A portal account holds a few view permissions, so the list alone would admit it.+ if (claims.role === "customer" || claims.role === "supplier") {+ throw new ForbiddenError();+ }+ if (!hasPermissions(permissionsFromClaims(claims), companyId, required)) {+ throw new ForbiddenError();+ }+ }++ /** A key of this company, unexpired, whose scopes (`<module>_<action>` →+ * company ids, shaped like claims) cover `required`. Rate limiting stays with+ * the route that authenticated the key. */+ async function authorizeApiKey(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ apiKey: string,+ required: RequiredPermissions+ ): Promise<void> {+ const key = await db+ .selectFrom("apiKey")+ .select("scopes")+ .where(+ "keyHash",+ "=",+ sql<string>`encode(sha256(convert_to(${apiKey}, 'UTF8')), 'hex')`+ )+ .where("companyId", "=", companyId)+ .where((eb) =>+ eb.or([+ eb("expiresAt", "is", null),+ eb("expiresAt", ">", sql<string>`now()`)+ ])+ )+ .executeTakeFirst();+ if (!key) throw new ForbiddenError("Invalid API key");+ if (Object.keys(required).length === 0) return;+ const scopes = permissionsFromClaims(+ (key.scopes ?? {}) as Record<string, unknown>+ );+ if (!hasPermissions(scopes, companyId, required)) {+ throw new ForbiddenError("API key lacks required permissions");+ }+ }diff --cc apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 37f3b8c372,08fa44727c..07aa826e6f--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@@ -1,1563 -1,1618 +1,1618 @@@{- "totalTools": 1557,- "modules": 15,+ "totalTools": 1612,+ "modules": 14,"tools": [- {"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},- {"name":"account_getAccount","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"8adb0e14ee10","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getAllAttributeCategories","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e93d76f694fe","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getAttributeCategoryWithValues","classification":"READ","paramCount":1,"schema":"34d65afdb82e","response":"32112b6759f8","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getAttributes","classification":"READ","paramCount":1,"schema":"f69289b8004c","response":"e93d76f694fe","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getCurrentUser","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ddc730821e71","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getNotificationPreferences","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0486649779fc","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getPrivateAttributes","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e93d76f694fe","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_getPublicAttributes","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e93d76f694fe","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_updateAvatar","classification":"WRITE","paramCount":1,"schema":"a2f2d0de3049","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_updatePublicAccount","classification":"WRITE","paramCount":5,"schema":"1995f647bdcf","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"account_upsertNotificationPreference","classification":"WRITE","paramCount":3,"schema":"4bf056fb8af6","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},- {"name":"account_upsertUserAttributeValue","classification":"WRITE","paramCount":4,"schema":"ed5ec8d6e08d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"none","paginates":false},- {"name":"accounting_closePeriodWithChecklist","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+updatedBy+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_completeCloseTask","classification":"WRITE","paramCount":2,"schema":"5d2e9a90637b","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_createFiscalYearPeriods","classification":"WRITE","paramCount":1,"schema":"de7d8726d5e4","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},- {"name":"accounting_createIntercompanyTransaction","classification":"WRITE","paramCount":8,"schema":"9c3c11f4059c","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},- {"name":"accounting_createJournalEntry","classification":"WRITE","paramCount":5,"schema":"64ec8566cc56","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},- {"name":"accounting_deleteAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"ecb746f60913","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteAccountingPeriod","classification":"DESTRUCTIVE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteCostCenter","classification":"DESTRUCTIVE","paramCount":1,"schema":"f8a3e6fec03f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteDepreciationRun","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteDimension","classification":"DESTRUCTIVE","paramCount":1,"schema":"96e5d0fb89ae","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteExchangeRateOverride","classification":"DESTRUCTIVE","paramCount":1,"schema":"cc2bce783cc5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteFixedAsset","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteFixedAssetClass","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteJournalEntry","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deletePaymentTerm","classification":"DESTRUCTIVE","paramCount":1,"schema":"5386fbcf056f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_deleteProject","classification":"DESTRUCTIVE","paramCount":1,"schema":"8e1d73142851","response":"3797626bd17e","injectAuth":"companyId","permission":"accounting:delete","paginates":false,"context":"updatedBy=userId"},- {"name":"accounting_deleteReportView","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"accounting_generateEliminations","classification":"WRITE","paramCount":1,"schema":"6205bcefb9ed","response":"cddf8275afa1","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},- {"name":"accounting_getAccount","classification":"READ","paramCount":1,"schema":"ecb746f60913","response":"9d6890743f52","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountingPeriodDeletability","classification":"READ","paramCount":1,"schema":"7e5905ac5974","response":"fdd16df03940","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountingPeriods","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"bd245bd0358c","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountingSyncTieOut","classification":"READ","paramCount":3,"schema":"4feda8437359","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountingSyncTieOutCell","classification":"READ","paramCount":1,"schema":"1a84bfebf9e9","response":"a5febf12f4bd","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"8ad7f551d78b","response":"faf531dd8b9a","injectAuth":"companyId","permission":"accounting:view","paginates":true},- {"name":"accounting_getAccountLedgerSummary","classification":"READ","paramCount":3,"schema":"aad65f7c3f63","response":"0a28a92b28ff","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountPeriodSeries","classification":"READ","paramCount":2,"schema":"d5db2abee293","response":"2c75339d9fde","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccounts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"84821cb96b68","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getAccountsInScope","classification":"READ","paramCount":2,"schema":"44ea072844d3","response":"4c52cef1b6ab","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountsList","classification":"READ","paramCount":3,"schema":"7592bd05f71d","response":"05b2ffc4c3d4","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getActiveDimensionsWithValues","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"1bfc101ae1de","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAssetDepreciationHistory","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"00c2fc9fdb8b","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getBaseCurrency","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"11af3b92d80f","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getBaseCurrencyDecimalPlaces","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"cddf8275afa1","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getChartOfAccounts","classification":"READ","paramCount":3,"schema":"b3b2e96654e5","response":"f561243f144b","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCompaniesInGroup","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"032bba337af7","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getConsolidatedBalances","classification":"READ","paramCount":4,"schema":"966a7b50605d","response":"a74dd3597c00","injectAuth":"companyId","permission":"accounting:view","paginates":false,"context":"eliminationClient=client"},- {"name":"accounting_getConsolidatedPeriodSeries","classification":"READ","paramCount":3,"schema":"2e20e5d2d7f5","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false,"context":"eliminationClient=client"},- {"name":"accounting_getCostCenter","classification":"READ","paramCount":1,"schema":"f8a3e6fec03f","response":"f7b898d20847","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCostCenters","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a27593ffa2de","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getCostCentersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCostCentersTree","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b4505b9334e6","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCurrencies","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"1d6055ff487c","injectAuth":"companyId","permission":"accounting:view","paginates":false,"defaults":"always"},- {"name":"accounting_getCurrenciesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"01628a6ebd21","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCurrency","classification":"READ","paramCount":1,"schema":"0e98c276626d","response":"6d5bae3dafd5","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCurrencyByCode","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"300e136d14d0","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getCurrentAccountingPeriod","classification":"READ","paramCount":1,"schema":"2f19cae7bae1","response":"923d00cf55d7","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDefaultAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8460f8427611","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDeferredRevenueWaterfall","classification":"READ","paramCount":1,"schema":"c860433efc00","response":"6ba817c304ae","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDepreciationRun","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"22ccbb1556ab","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDepreciationRunLines","classification":"READ","paramCount":1,"schema":"e83946bf5ea7","response":"9c31ce726755","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDepreciationRuns","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"829d729e81c9","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getDimension","classification":"READ","paramCount":1,"schema":"96e5d0fb89ae","response":"e869e1d37e76","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDimensionPivot","classification":"READ","paramCount":6,"schema":"4dc617d84588","response":"c7069f830357","injectAuth":"companyGroupId+companyId","permission":"accounting:view","paginates":false,"defaults":"always"},- {"name":"accounting_getDimensionPivotLines","classification":"READ","paramCount":17,"schema":"6f74597ffe85","response":"100f0689af3e","injectAuth":"companyGroupId+companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDimensions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"9beb5210c60e","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getExchangeRate","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"cddf8275afa1","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getExchangeRateHistory","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"ab784d246338","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getExchangeRates","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7089bfe7df7a","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFinancialStatementBalances","classification":"READ","paramCount":3,"schema":"267691af8c66","response":"f561243f144b","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFinancialStatementPeriodSeries","classification":"READ","paramCount":3,"schema":"27a6e6386ed2","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFiscalCalendarCommitted","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"854b90f7a9d3","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFiscalYearSettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3a18729ffcd7","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAsset","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"faea7eb49dc8","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetCipCosts","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"03707172e0ba","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetClass","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"8442dd4440a1","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetClasses","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"03a52bf94953","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getFixedAssetClassesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"123f9f4a60f8","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetDisposal","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"4b37a6513b87","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssets","classification":"READ","paramCount":4,"schema":"98a82364580e","response":"1352052a4d0e","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getFixedAssetsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0c62226f500a","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetsListForSale","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0c62226f500a","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetTransfers","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"e88320352e28","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssetUsageLogs","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"517f4c28c365","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFleetAssets","classification":"READ","paramCount":4,"schema":"e83739fdf2bc","response":"8735b01a7188","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getGroupAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a9a2c5be8164","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getIntercompanyBalance","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f2f76b33a3df","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getIntercompanyEliminationLines","classification":"READ","paramCount":1,"schema":"b9efe4d053a7","response":"eb31d414081e","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getIntercompanyTransactions","classification":"READ","paramCount":3,"schema":"db142abe3913","response":"2c3abae21f4b","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getJournalEntries","classification":"READ","paramCount":4,"schema":"85098b9cb044","response":"80e3b322d07f","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f3fc6aeda32d","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getJournalLineDimensions","classification":"READ","paramCount":1,"schema":"4a6413e2bb5a","response":"b731368c1d3c","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getJournalSyncCompleteness","classification":"READ","paramCount":3,"schema":"6eb0a36bbd4b","response":"58d45b19b00c","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getLeaseLiabilities","classification":"READ","paramCount":3,"schema":"a9d65afee96d","response":"none","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getLeaseNetInvestment","classification":"READ","paramCount":1,"schema":"c860433efc00","response":"93c82b571cea","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getOrCreateAccountingPeriod","classification":"WRITE","paramCount":2,"schema":"ced53a5f76ed","response":"00404e686415","injectAuth":"companyId","permission":"accounting:update","paginates":false},- {"name":"accounting_getPaymentTerm","classification":"READ","paramCount":1,"schema":"5386fbcf056f","response":"f7f39c0d662f","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getPaymentTerms","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7e3500d5e372","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getPaymentTermsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getPeriodCloseChecklist","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"032d2a02eff5","injectAuth":"companyGroupId+companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_getPeriodCloseReadiness","classification":"READ","paramCount":1,"schema":"7e5905ac5974","response":"d8b254beff31","injectAuth":"companyGroupId+companyId+userId","permission":"accounting:view","paginates":false},- {"name":"accounting_getPeriodCloseTaskDefinitions","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"273a27083497","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getPeriodExternalGlSyncReadiness","classification":"READ","paramCount":2,"schema":"265827be4a3e","response":"0963c785f5ca","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getPeriodRunRelatedItems","classification":"READ","paramCount":2,"schema":"533dc47fe01c","response":"311f6360747c","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getProject","classification":"READ","paramCount":1,"schema":"8e1d73142851","response":"b9294ccc5a24","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getProjects","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"48b654f2a9fa","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getPurchaseLinePivot","classification":"READ","paramCount":4,"schema":"53729b2674ee","response":"c7069f830357","injectAuth":"companyId","permission":"accounting:view","paginates":false,"defaults":"always"},- {"name":"accounting_getPurchaseLinePivotLines","classification":"READ","paramCount":10,"schema":"d23c9f2398a4","response":"a12b8efe2d62","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRentalUtilization","classification":"READ","paramCount":3,"schema":"696a375a604f","response":"80fa6e3c40ad","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getReportPins","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3536c9c9a314","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getReportViews","classification":"READ","paramCount":1,"schema":"f60ae5d8a496","response":"7f6aad3009db","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRevenueRecognitionRun","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"fb8cbba30867","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRevenueRecognitionRunLines","classification":"READ","paramCount":1,"schema":"8245d2d4cee4","response":"beb79b629050","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRevenueRecognitionRuns","classification":"READ","paramCount":2,"schema":"cde27bc67b4d","response":"cfdb7948ea0a","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getRevenueSchedules","classification":"READ","paramCount":4,"schema":"a9a93466d158","response":"029139d6955a","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},- {"name":"accounting_getScrapAccountIds","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"681004346c78","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getTrialBalance","classification":"READ","paramCount":2,"schema":"3eb7f553b21b","response":"e782cb2b76dc","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getUnderConstructionAssets","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b6f3d669374f","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getWorkCenterCapitalCost","classification":"READ","paramCount":1,"schema":"7f43ff7a4fc5","response":"e74388b72851","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_insertDepreciationRun","classification":"DESTRUCTIVE","paramCount":3,"schema":"9d4a1dd5e184","response":"70d7ca41be81","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},- {"name":"accounting_insertFixedAsset","classification":"WRITE","paramCount":18,"schema":"c3e581918995","response":"e0e9c463a967","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},- {"name":"accounting_invokeAssetTransfer","classification":"WRITE","paramCount":1,"schema":"1b261cefaeea","response":"c84f5bab4f4d","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_lockAccountingPeriod","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_postJournalEntry","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId","permission":"accounting:update","paginates":false},- {"name":"accounting_returnFixedAssetToService","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_reverseJournalEntry","classification":"WRITE","paramCount":2,"schema":"d25804b3560c","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_runIntercompanyMatching","classification":"WRITE","paramCount":0,"schema":"efddc7bd8bbc","response":"c07d47c6ac75","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_saveJournalEntryWithLines","classification":"DESTRUCTIVE","paramCount":4,"schema":"c1d59a9ba1ff","response":"8394fbabd845","injectAuth":"companyGroupId+companyId","permission":"accounting:update","paginates":false},- {"name":"accounting_saveJournalLineDimensions","classification":"DESTRUCTIVE","paramCount":2,"schema":"7982c7b53f63","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:update","paginates":false},- {"name":"accounting_setFixedAssetOutOfService","classification":"WRITE","paramCount":3,"schema":"5e6414b4286b","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_skipCloseTask","classification":"WRITE","paramCount":2,"schema":"8d4ab2b60f5f","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_translateCompanyBalances","classification":"WRITE","paramCount":4,"schema":"ba889d393571","response":"be5b093fb6e6","injectAuth":"companyId","permission":"accounting:update","paginates":false},- {"name":"accounting_unlockAccountingPeriod","classification":"WRITE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},- {"name":"accounting_updateDefaultAccounts","classification":"WRITE","paramCount":65,"schema":"82c94cd371e9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_updateFiscalYearSettings","classification":"WRITE","paramCount":2,"schema":"b13ac9bf329b","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_updateFixedAsset","classification":"WRITE","paramCount":17,"schema":"9f8fa39b1799","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"accounting:update","paginates":false},- {"name":"accounting_upsertAccount","classification":"WRITE","paramCount":10,"schema":"0b4871d25164","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"accounting_upsertCostCenter","classification":"WRITE","paramCount":5,"schema":"cb41a65d1346","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"accounting_upsertCurrency","classification":"WRITE","paramCount":5,"schema":"8b35738390cc","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"accounting_upsertDimension","classification":"DESTRUCTIVE","paramCount":2,"schema":"820eea627efe","response":"660c8bead643","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"accounting_upsertExchangeRateOverride","classification":"WRITE","paramCount":2,"schema":"4576f689f2fa","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertFixedAssetClass","classification":"WRITE","paramCount":1,"schema":"1b7fede70b27","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"accounting_upsertPaymentTerm","classification":"WRITE","paramCount":7,"schema":"857007388d52","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"accounting_upsertProject","classification":"WRITE","paramCount":3,"schema":"8bcec28be313","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"accounting_upsertReportPin","classification":"WRITE","paramCount":2,"schema":"28ab82d5033e","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create+update","paginates":false},- {"name":"accounting_upsertReportView","classification":"WRITE","paramCount":1,"schema":"394fe1eaa481","response":"b8ded59f5c56","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"documents_createDocumentUploadUrl","classification":"WRITE","paramCount":3,"schema":"9034f525c97e","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create","paginates":false},- {"name":"documents_deleteDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:delete","paginates":false},- {"name":"documents_getDocument","classification":"READ","paramCount":1,"schema":"e7617eb689c8","response":"88539143f954","injectAuth":"companyId","permission":"documents:view","paginates":false},- {"name":"documents_getDocumentExtensions","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a07a74ca3dd1","injectAuth":"companyId","permission":"documents:view","paginates":false},- {"name":"documents_getDocumentLabels","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7e2eeb0066ab","injectAuth":"companyId","permission":"documents:view","paginates":false},- {"name":"documents_getDocuments","classification":"READ","paramCount":6,"schema":"8f9f1309d9dd","response":"806ff23e9acc","injectAuth":"companyId","permission":"documents:view","paginates":true,"defaults":"always"},- {"name":"documents_insertDocumentExtraction","classification":"WRITE","paramCount":4,"schema":"790f2b883984","response":"d181256b2684","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create","paginates":false},- {"name":"documents_insertUploadedDocument","classification":"WRITE","paramCount":5,"schema":"d82e74374bd6","response":"697b262639cd","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create","paginates":false},- {"name":"documents_moveDocumentToTrash","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"documents:update","paginates":false},- {"name":"documents_restoreDocument","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:update","paginates":false},- {"name":"documents_updateDocumentFavorite","classification":"DESTRUCTIVE","paramCount":2,"schema":"85769b943e30","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"documents:update","paginates":false},- {"name":"documents_updateDocumentLabels","classification":"DESTRUCTIVE","paramCount":2,"schema":"0adc09fa2bb3","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"documents:update","paginates":false},- {"name":"documents_upsertDocument","classification":"WRITE","paramCount":11,"schema":"7b71f5ddd67a","response":"697b262639cd","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_cancelOpenPickingListsForJob","classification":"WRITE","paramCount":1,"schema":"4999bd4be598","response":"844f8eedb019","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},- {"name":"inventory_correctStockMovement","classification":"WRITE","paramCount":3,"schema":"fb389b0474f2","response":"baa524ddff70","injectAuth":"companyId","permission":"inventory:update","paginates":false},- {"name":"inventory_createInventoryReconciliationJournal","classification":"WRITE","paramCount":1,"schema":"00e9099a963a","response":"a9f23ceb9dc1","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},- {"name":"inventory_deleteBatchProperty","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteInventoryCount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteKanban","classification":"DESTRUCTIVE","paramCount":1,"schema":"369f807bc840","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deletePickingList","classification":"DESTRUCTIVE","paramCount":1,"schema":"0a4ec3e7319b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteReceipt","classification":"DESTRUCTIVE","paramCount":1,"schema":"e00a9764517d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteReceiptLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"17337505bb69","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteShipment","classification":"DESTRUCTIVE","paramCount":1,"schema":"2e39a760a5ca","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteShipmentLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"84320a09c1ac","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteShippingMethod","classification":"DESTRUCTIVE","paramCount":1,"schema":"493e990b5f3d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStockTransfer","classification":"DESTRUCTIVE","paramCount":1,"schema":"38111ae0fa2a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStockTransferLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"0bbd6a946791","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStorageTypeWithCascade","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"210a2a62676d","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStorageUnit","classification":"DESTRUCTIVE","paramCount":1,"schema":"c728bf7e5b37","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStorageUnitCascade","classification":"DESTRUCTIVE","paramCount":1,"schema":"c728bf7e5b37","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteWarehouseTransfer","classification":"DESTRUCTIVE","paramCount":1,"schema":"d51f098ead24","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteWarehouseTransferLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"d99fddf5e39e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_expandStorageUnitIdsWithDescendants","classification":"WRITE","paramCount":1,"schema":"f413382980a7","response":"681004346c78","injectAuth":"companyId","permission":"inventory:update","paginates":false},- {"name":"inventory_generateInventoryCountLines","classification":"DESTRUCTIVE","paramCount":4,"schema":"7cf62698d5f8","response":"cddf8275afa1","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_generatePickingList","classification":"DESTRUCTIVE","paramCount":4,"schema":"412bd8dbff31","response":"81802516b555","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_getAvailableTrackedEntities","classification":"READ","paramCount":6,"schema":"6a561d222e27","response":"723554a256de","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getBatchNumbersForItem","classification":"READ","paramCount":2,"schema":"786c6e7af03b","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getBatchProperties","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"9a2b986c906d","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getDefaultStorageUnitForJob","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"174e29b899b9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getDefaultStorageUnitOrStorageUnitWithHighestQuantity","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"174e29b899b9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getEffectiveWorkCenterId","classification":"READ","paramCount":1,"schema":"c728bf7e5b37","response":"00404e686415","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryCount","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"b707251b11c4","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryCountLines","classification":"READ","paramCount":2,"schema":"65abbb307e1c","response":"e4219573b12b","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getInventoryCountLineSummary","classification":"READ","paramCount":1,"schema":"e354150046fe","response":"7a06e37fcf2a","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryCountMovements","classification":"READ","paramCount":1,"schema":"e354150046fe","response":"eba78a8fe017","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryCounts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"43536f2bda72","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getInventoryItems","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"5baddb3a890c","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getInventoryItemsCount","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"8394fbabd845","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getInventoryValuation","classification":"READ","paramCount":2,"schema":"288f0d29701b","response":"4005e935f8f1","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getInventoryValuationTieOut","classification":"READ","paramCount":1,"schema":"cb789596bf56","response":"20aee38c95a3","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getItemLedgerActivity","classification":"READ","paramCount":5,"schema":"b898b72c5939","response":"07a99b26121b","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getItemLedgerBalance","classification":"READ","paramCount":3,"schema":"33e76470e057","response":"cddf8275afa1","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getItemLedgerPage","classification":"READ","paramCount":4,"schema":"7ef5489d0abf","response":"07a99b26121b","injectAuth":"companyId","permission":"inventory:view","paginates":true},- {"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"2fd5e28a7273","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getKanbanProjectedQuantities","classification":"READ","paramCount":1,"schema":"eb1d8d941f5f","response":"98903cc375ce","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"87bc6f56aff6","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"none","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"b3ab0a2018d9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListRecommendations","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"24283057a15d","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingListRelatedItems","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"74c025dd5c02","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickingLists","classification":"READ","paramCount":6,"schema":"c17334a443b6","response":"2112d9a1ea1d","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getPickingSchedule","classification":"READ","paramCount":2,"schema":"b3a9deeaf0d0","response":"19467666efcd","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPickOrder","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"7fa0311f0d0a","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getPicksByJobMaterial","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"b53992cb5f0c","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceipt","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"b7c00288df9c","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceiptFiles","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"5483e69d7515","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceiptLines","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"15b7b17f7652","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceiptLineTracking","classification":"READ","paramCount":1,"schema":"17337505bb69","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceiptRelatedItems","classification":"READ","paramCount":2,"schema":"bc54dac2bca6","response":"0f4d8e489d1b","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getReceipts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4aa48aba067d","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getReceiptTracking","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getRentalReceiptLines","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"2e9dfef414a9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getRentalShipmentLines","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"1ab616adb2e0","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getSerialNumbersForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShelfLifeForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"4c5d680d898e","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipment","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"cf99c31d666e","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentFiles","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"5483e69d7515","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentLines","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"1b1f740f30c6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentLinesWithDetails","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"c158915aa9b9","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentLineTracking","classification":"READ","paramCount":1,"schema":"84320a09c1ac","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipmentRelatedItems","classification":"READ","paramCount":2,"schema":"f81a81d39efa","response":"0e975679737c","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShipments","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"92c56e0fa40a","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getShipmentTracking","classification":"READ","paramCount":1,"schema":"2e39a760a5ca","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShippingMethod","classification":"READ","paramCount":1,"schema":"493e990b5f3d","response":"65413dd34c52","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShippingMethods","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"104aa0df039d","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getShippingMethodsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getShippingTermsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockMovementEffectiveQuantity","classification":"READ","paramCount":1,"schema":"a40494d32d29","response":"2e1967d88231","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockMovements","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"eba78a8fe017","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStockTransfer","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"69c0eeefc47c","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockTransferLine","classification":"READ","paramCount":1,"schema":"0bbd6a946791","response":"a34287fc1477","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockTransferLines","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"bcb01288cc29","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStockTransfers","classification":"READ","paramCount":4,"schema":"acb88488ed54","response":"a0e62ff2e059","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStockTransferTracking","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"20f8627b948f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageType","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4bbb50609deb","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"28837d034643","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStorageTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageTypeUsage","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnit","classification":"READ","paramCount":1,"schema":"c728bf7e5b37","response":"a5bf237a9aeb","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitChildren","classification":"READ","paramCount":1,"schema":"06f6e8f8f9f5","response":"7eea15677f40","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitDescendants","classification":"READ","paramCount":1,"schema":"c728bf7e5b37","response":"3bae190e2656","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitParentIdsWithChildren","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"681004346c78","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitRoots","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"7eea15677f40","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStorageUnits","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"7eea15677f40","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getStorageUnitsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitsListForLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitsTreeForLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"ecdf2c570468","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitSubtrees","classification":"READ","paramCount":3,"schema":"c5258b49b1b9","response":"10e6a05f40e5","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitTree","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"3bae190e2656","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getTrackedEntities","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_getTrackedEntitiesByMakeMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getTrackedEntitiesByOperationId","classification":"READ","paramCount":1,"schema":"c407a9edb930","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getTrackedEntity","classification":"READ","paramCount":1,"schema":"5d58d420052a","response":"d485710baf81","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getTrackedEntityExpirations","classification":"READ","paramCount":1,"schema":"2d3f4e6f5875","response":"fff84b1ee888","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getUnresolvedPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"ce45e49e333f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransfer","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"2234f62ec519","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransferLine","classification":"READ","paramCount":2,"schema":"31f24bda931b","response":"945dc2c1255f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransferLines","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"8a92aaed64aa","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransferRelatedItems","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"4f08c7c15b92","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransfers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"66ec9f5f0ca8","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},- {"name":"inventory_insertInventoryCount","classification":"WRITE","paramCount":6,"schema":"f9ea90011f9a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_insertManualInventoryAdjustment","classification":"WRITE","paramCount":12,"schema":"dc3fda774cf4","response":"baa524ddff70","injectAuth":"companyId+createdBy","permission":"inventory:create","paginates":false},- {"name":"inventory_insertStockTransfer","classification":"DESTRUCTIVE","paramCount":4,"schema":"623ca286b237","response":"910187eb9b58","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_insertWarehouseTransfer","classification":"WRITE","paramCount":9,"schema":"b92377ee6a4f","response":"8e9431d157a2","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_mergeTrackedEntities","classification":"WRITE","paramCount":2,"schema":"b12fee74a91e","response":"none","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},- {"name":"inventory_pickPickingListLine","classification":"WRITE","paramCount":3,"schema":"0371c6fecc9c","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},- {"name":"inventory_reconcileReceiptSerialEntities","classification":"DESTRUCTIVE","paramCount":2,"schema":"317d393d5b4a","response":"none","injectAuth":"companyId","permission":"inventory:update","paginates":false},- {"name":"inventory_searchStorageUnitsWithAncestors","classification":"READ","paramCount":2,"schema":"bf8906da76a5","response":"1ef4111538b5","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_setPickingListLineTrackedEntity","classification":"WRITE","paramCount":5,"schema":"a628dabab831","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"inventory:update","paginates":false},- {"name":"inventory_updateBatchPropertyOrder","classification":"WRITE","paramCount":3,"schema":"ed0f513719d1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},- {"name":"inventory_updateInventoryCountLine","classification":"WRITE","paramCount":3,"schema":"d0dcc5796dc7","response":"ae8f99e1d130","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},- {"name":"inventory_updateInventoryCountStatus","classification":"WRITE","paramCount":3,"schema":"7b6f2e6e7731","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},- {"name":"inventory_updatePickingListStatus","classification":"WRITE","paramCount":2,"schema":"27fb9b18332a","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false,"context":"updatedBy=userId"},- {"name":"inventory_updateStockTransferStatus","classification":"WRITE","paramCount":4,"schema":"e201e5617e35","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},- {"name":"inventory_updateTrackedEntityExpiry","classification":"WRITE","paramCount":4,"schema":"ebdc5286d20c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"inventory:update","paginates":false},- {"name":"inventory_updateWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"a809aeb69e6d","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},- {"name":"inventory_updateWarehouseTransferStatus","classification":"WRITE","paramCount":2,"schema":"70cb7f36b2a6","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false,"context":"updatedBy=userId"},- {"name":"inventory_upsertBatchProperty","classification":"WRITE","paramCount":6,"schema":"6fcfef7093ed","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"inventory:create+update","paginates":false},- {"name":"inventory_upsertKanban","classification":"WRITE","paramCount":15,"schema":"bda2d2c1b9ff","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"inventory_upsertPickingList","classification":"WRITE","paramCount":7,"schema":"dbe65909f79e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_upsertReceipt","classification":"WRITE","paramCount":9,"schema":"fd0848682b0b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_upsertShipment","classification":"WRITE","paramCount":10,"schema":"efe95221a775","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_upsertShippingMethod","classification":"WRITE","paramCount":6,"schema":"6d157a6086d0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_upsertStockTransferLine","classification":"WRITE","paramCount":9,"schema":"9d7761b29bb0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_upsertStorageType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_upsertStorageUnit","classification":"WRITE","paramCount":8,"schema":"31c5351820e4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},- {"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},- {"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"none","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"7e387955a4f8","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"ec9aaaf82857","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"ec9aaaf82857","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_createSalesInvoiceFromShipment","classification":"WRITE","paramCount":1,"schema":"2e39a760a5ca","response":"ec9aaaf82857","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_deleteMemo","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},- {"name":"invoicing_deletePayment","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"invoicing:delete","paginates":false},- {"name":"invoicing_getApAging","classification":"READ","paramCount":2,"schema":"9db366ef805c","response":"eca97da3238d","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getApOpenBySupplier","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"cfaa2af435c0","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getApTieOut","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"194f80599d96","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getArAging","classification":"READ","paramCount":2,"schema":"9db366ef805c","response":"10729e9f1c72","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getArOpenByCustomer","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"8cd731dddf0d","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getArTieOut","classification":"READ","paramCount":1,"schema":"00e9099a963a","response":"194f80599d96","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getAvailableCreditsForParty","classification":"READ","paramCount":3,"schema":"cc95c9088447","response":"f8e7a5443d43","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getAvailableOnAccountCredit","classification":"READ","paramCount":1,"schema":"2bfa7d907171","response":"cddf8275afa1","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getAvailableOnAccountCreditSources","classification":"READ","paramCount":2,"schema":"b09149f439eb","response":"ec53cb4aa76b","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getCharge","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4d45de90549b","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getCharges","classification":"READ","paramCount":5,"schema":"3b1a78f3ef00","response":"a1c047af8dd8","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getCompanyHasOpenCredits","classification":"READ","paramCount":1,"schema":"ffed91643c1d","response":"7cb541e84f22","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getInvoiceSettlements","classification":"READ","paramCount":1,"schema":"bd163ca304cd","response":"5483e69d7515","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getInvoiceSettlementsForInvoice","classification":"READ","paramCount":2,"schema":"9d6509fa2229","response":"a334c4e05d56","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getMemo","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"98fffe52edef","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getMemoApplications","classification":"READ","paramCount":1,"schema":"188417093a55","response":"8b54c25de723","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getMemos","classification":"READ","paramCount":7,"schema":"8f6810d90c81","response":"f38bef4be63d","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","paramCount":2,"schema":"da8678ca28c2","response":"a16080b3cb31","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getOpenReimbursementsForEmployee","classification":"READ","paramCount":2,"schema":"8c83e701c013","response":"84fe5db303b4","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","paramCount":2,"schema":"2d555b8aaf06","response":"a16080b3cb31","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPayment","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"300aea1db7cb","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPaymentCurrencyConfiguration","classification":"READ","paramCount":1,"schema":"cc2bce783cc5","response":"35b15cbf37ce","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPayments","classification":"READ","paramCount":8,"schema":"fc068ce64697","response":"e786785f266d","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getPurchaseInvoice","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"656b64f44b73","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPurchaseInvoiceDelivery","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"57af27aeef3b","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPurchaseInvoiceLine","classification":"READ","paramCount":1,"schema":"af656ed8709f","response":"3592330c8f34","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPurchaseInvoiceLines","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"f8ce78976cce","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getPurchaseInvoices","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"e14efcf49a89","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getReimbursement","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"c1191896ef6c","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getReimbursementRelatedItems","classification":"READ","paramCount":1,"schema":"1440dbb5599d","response":"b44573ee4608","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getReimbursements","classification":"READ","paramCount":5,"schema":"45f5b7cdee07","response":"9bad0fb8b063","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getSalesInvoice","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"9cd55ec5019e","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getSalesInvoiceCustomerDetails","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"d592e414f201","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getSalesInvoiceLine","classification":"READ","paramCount":1,"schema":"352db7d38a15","response":"b6cb6eeff636","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getSalesInvoiceLines","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"5b10b31c425e","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getSalesInvoices","classification":"READ","paramCount":4,"schema":"03a6ebc93561","response":"5b1a09dc9fa5","injectAuth":"companyId","permission":"invoicing:view","paginates":true,"defaults":"always"},- {"name":"invoicing_getSalesInvoiceShipment","classification":"READ","paramCount":1,"schema":"9e382a0affeb","response":"47c40e51a6e4","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_getStagedCreditsForPayment","classification":"READ","paramCount":2,"schema":"d67008f41829","response":"5a23b05562f4","injectAuth":"companyId","permission":"invoicing:view","paginates":false},- {"name":"invoicing_insertPurchaseInvoice","classification":"DESTRUCTIVE","paramCount":15,"schema":"15dc8b208ca1","response":"24b4b1602470","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_insertSalesInvoice","classification":"DESTRUCTIVE","paramCount":14,"schema":"56c402cfa5a8","response":"24b4b1602470","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},- {"name":"invoicing_replaceInvoiceSettlements","classification":"DESTRUCTIVE","paramCount":2,"schema":"66ab03790336","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false,"defaults":"always"},- {"name":"invoicing_updatePurchaseInvoice","classification":"WRITE","paramCount":15,"schema":"304bf354aa67","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updatePurchaseInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updatePurchaseInvoiceLineOrder","classification":"WRITE","paramCount":2,"schema":"a1679a3eb9b5","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updateReimbursement","classification":"WRITE","paramCount":8,"schema":"ff96110da3d7","response":"def495be96e6","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updateSalesInvoice","classification":"WRITE","paramCount":15,"schema":"71a9939b9245","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updateSalesInvoiceExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_updateSalesInvoiceLineOrder","classification":"WRITE","paramCount":2,"schema":"a1679a3eb9b5","response":"none","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_upsertMemo","classification":"WRITE","paramCount":12,"schema":"0369e0154c99","response":"1e0d0fa1a854","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"invoicing_upsertPayment","classification":"WRITE","paramCount":16,"schema":"f8f2180d8a3b","response":"1a922c685a61","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"invoicing_upsertPurchaseInvoiceDelivery","classification":"WRITE","paramCount":8,"schema":"02d98a1b8952","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"invoicing_upsertPurchaseInvoiceLine","classification":"WRITE","paramCount":25,"schema":"e11776875976","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"invoicing_upsertReimbursementLines","classification":"DESTRUCTIVE","paramCount":2,"schema":"96f11ef83729","response":"cddf8275afa1","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false},- {"name":"invoicing_upsertSalesInvoiceLine","classification":"WRITE","paramCount":24,"schema":"7cc1d479ebe7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"invoicing_upsertSalesInvoiceShipment","classification":"WRITE","paramCount":9,"schema":"9e9d7e8b568d","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"invoicing:update","paginates":false},- {"name":"items_activateMethodVersion","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"ec9aaaf82857","injectAuth":"companyId+userId","permission":"parts:update","paginates":false},- {"name":"items_addChangeNoticeAffectedItem","classification":"DESTRUCTIVE","paramCount":5,"schema":"183209667024","response":"3cc309ba4541","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},- {"name":"items_assertMethodOperationIsDraft","classification":"WRITE","paramCount":1,"schema":"c407a9edb930","response":"none","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_cascadeItemTrackingType","classification":"WRITE","paramCount":2,"schema":"cb7a14748215","response":"none","injectAuth":"companyId+userId","permission":"parts:update","paginates":false},- {"name":"items_copyItem","classification":"WRITE","paramCount":8,"schema":"9c8674273b59","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},- {"name":"items_copyMakeMethod","classification":"WRITE","paramCount":8,"schema":"9c8674273b59","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create","paginates":false},- {"name":"items_createItemDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"6dcd390c3681","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},- {"name":"items_createRevision","classification":"WRITE","paramCount":3,"schema":"59340adc1219","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},- {"name":"items_deleteChangeNotice","classification":"DESTRUCTIVE","paramCount":1,"schema":"29578070edb2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteChangeNoticeAction","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteChangeNoticeRequiredAction","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteChangeNoticeType","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteConfigurationParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteConfigurationParameterGroup","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteConfigurationRule","classification":"DESTRUCTIVE","paramCount":2,"schema":"4eaf102cddd9","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteItemCustomerPart","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteItemPostingGroup","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialDimension","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialFinish","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialForm","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialGrade","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialSubstance","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMaterialType","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMethodMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMethodOperationParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMethodOperationStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMethodOperationStepSlide","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteMethodOperationTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteSupplierPart","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_deleteUnitOfMeasure","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:delete","paginates":false},- {"name":"items_diffMethod","classification":"READ","paramCount":1,"schema":"2531dd68049b","response":"fab3ac9dac53","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_duplicateMethodOperationStep","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},- {"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"none","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeDiff","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"4da0de080834","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeRequiredAction","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a76ce814b1b8","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeRequiredActions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4c8439fedd7e","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getChangeNoticeRequiredActionsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNotices","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ef2c88bb20cc","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getChangeNoticesForNonConformance","classification":"READ","paramCount":1,"schema":"a78c6c21c084","response":"47b99abee3a5","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeType","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"d15ce193a0df","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getChangeNoticeTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4d341af72c49","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getChangeNoticeTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getConfigurationParameters","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c36ad21b447b","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getConfigurationRules","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"530f6f787ce7","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getConsumable","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"105e334bcf5b","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getConsumables","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"9302fcd8ff2d","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getConsumablesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getDemandForecastSources","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"4ef1c000e70f","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItem","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"87a9b87208d5","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemChangeNoticeData","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"a9f8d291a4dd","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemCost","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"38fa8e41fdd1","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemCostHistory","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"792b7c55b52e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemCustomerPart","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4c6e08919580","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemCustomerParts","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"458a8cdb47f2","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"20b38721b145","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemFiles","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"ffefd03548aa","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemManufacturing","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f399bb7eda67","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemMpnsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3ff28fd20707","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemPlanning","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"435390ae7550","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemPostingGroup","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"d38ff3570b60","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemPostingGroups","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"5019b8dab137","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getItemPostingGroupsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemQuantities","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"9fc7a6c9f2e3","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemReplenishment","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"f399bb7eda67","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemShelfLife","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"a406f3a83a89","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemStockQuantitiesByLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"96915ea19193","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemStorageUnitQuantities","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"880fa3aa7279","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemSupersededBy","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"8e2ea57c0664","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemSupersession","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"0c693c4f3dcb","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemSupersessionsForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"e06b6534cfe9","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemSupply","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"696523b54f52","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemUnitSalePrice","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"7281903c959e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getJobMaterialUsageForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"67faac8214ed","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMakeMethodById","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"cb9ae031b551","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMakeMethods","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"6cdfe33178ce","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterial","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"fce6ec47472d","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialDimension","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"5a634d31e2f3","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialDimensionList","classification":"READ","paramCount":2,"schema":"f614c4ca7d64","response":"b72364e0a391","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialDimensions","classification":"READ","paramCount":4,"schema":"9136faf13c9c","response":"98486ac80bcc","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialFinish","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"07a225161151","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialFinishes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"04cf1f4f7909","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialFinishList","classification":"READ","paramCount":1,"schema":"069f6f1436cd","response":"b57774d02b4d","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialForm","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f69bdbb31d76","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialForms","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ca926bd97ca1","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialFormsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a59b0ccd150e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialGrade","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"07a225161151","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialGradeList","classification":"READ","paramCount":1,"schema":"069f6f1436cd","response":"b57774d02b4d","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialGrades","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"04cf1f4f7909","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterials","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"5a10e7f3c854","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialSubstance","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f69bdbb31d76","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialSubstances","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ca926bd97ca1","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialSubstancesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a59b0ccd150e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialType","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"0cc848ca86e3","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialTypeList","classification":"READ","paramCount":2,"schema":"babec8528804","response":"c3dfbc0fdf89","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMaterialTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"cbbbd5d9c38d","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialUsedIn","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"5bc3cafcb138","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodMaterial","classification":"READ","paramCount":1,"schema":"5aa329400da2","response":"4f986471aaee","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodMaterials","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"16cb0357007c","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMethodMaterialsByMakeMethod","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"ed99eb62f33c","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodOperations","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"44cb9313b74c","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMethodOperationsByMakeMethodId","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"4ec7d6bf5468","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodTree","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"18cc03a418b4","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getMethodTreeArray","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"6481a47cef6d","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getNextRevision","classification":"READ","paramCount":1,"schema":"96527a3bce32","response":"00404e686415","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getOpenJobMaterials","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"3df5c33eb3a4","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getOpenProductionOrders","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"0de1519216f7","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getOpenPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"c53a83bc1272","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getOpenSalesOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"ee9244a3a03b","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPart","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getParts","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"b134f22017b9","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getPartsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPartUsedIn","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"e205f0dd9382","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPickMethod","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"781e7f3fc24f","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPickMethods","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"f1260811ebd4","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getRecipeProcessIdsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"681004346c78","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getService","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getServices","classification":"READ","paramCount":5,"schema":"4b3bc8e78cef","response":"0bc4d668f038","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getServicesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupersessionChain","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"57cd7c34e332","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPartPriceBreaks","classification":"READ","paramCount":1,"schema":"0b5fc4acf371","response":"f4acc38f3c75","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPartPricing","classification":"READ","paramCount":3,"schema":"12f5a9bff481","response":"6cefe4692145","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierParts","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"77be6c5a4141","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPartsBySupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"8acf1878d779","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPriceBreaksForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"dc0d300695e0","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getTool","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getTools","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"2b6244653ec7","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getToolsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getTopLevelProductsForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"b56efd7a527e","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getUnitOfMeasure","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"124234df769c","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getUnitOfMeasures","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e19fb7f07a6a","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getUnitOfMeasuresList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"1333b6f93ca5","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getUnitOfMeasureUsage","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"bf91be568e5a","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_insertChangeNotice","classification":"WRITE","paramCount":12,"schema":"c534f032ec75","response":"9645fed81b3e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create","paginates":false},- {"name":"items_lookupBuyPrice","classification":"READ","paramCount":3,"schema":"c440ca0b7efc","response":"cddf8275afa1","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_matchItemIdByText","classification":"READ","paramCount":1,"schema":"f2e9aceb3e6b","response":"174e29b899b9","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_removeChangeNoticeAffectedItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_resolveItemIdFromExtractedText","classification":"WRITE","paramCount":2,"schema":"a36b576f2400","response":"174e29b899b9","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_setChangeNoticeActionTasks","classification":"DESTRUCTIVE","paramCount":2,"schema":"0a99ac2dd23d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"name":"items_setMethodMaterialStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"9a5230c97e72","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_setMethodOperationToolStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"3912df9a58b9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateChangeNotice","classification":"WRITE","paramCount":13,"schema":"a99b6ea4de95","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateChangeNoticeActionOrder","classification":"WRITE","paramCount":2,"schema":"cab02bf4c21b","response":"none","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateChangeNoticeActionStatus","classification":"WRITE","paramCount":2,"schema":"122c17a83964","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"name":"items_updateChangeNoticeAffectedItemChangeType","classification":"WRITE","paramCount":2,"schema":"a694b3096020","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"name":"items_updateChangeNoticeAffectedItemCutover","classification":"WRITE","paramCount":4,"schema":"a06ee719b5b5","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"name":"items_updateChangeNoticeStatus","classification":"WRITE","paramCount":4,"schema":"fb1c5bc3ec27","response":"b7cda6fcc03b","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateConfigurationParameterGroupOrder","classification":"WRITE","paramCount":2,"schema":"cf28ccd3b252","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:update","paginates":false},- {"name":"items_updateConfigurationParameterOrder","classification":"WRITE","paramCount":3,"schema":"3c4e90ddafb4","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateDefaultRevision","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"6411d1997ad5","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateItem","classification":"WRITE","paramCount":18,"schema":"f24ba73701ab","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateItemCost","classification":"WRITE","paramCount":2,"schema":"c55de757a7e4","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateItemMethodAndSourcing","classification":"WRITE","paramCount":3,"schema":"1165eb54378a","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"name":"items_updateMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false,"result":"envelopes"},- {"name":"items_updateMaterialProperties","classification":"WRITE","paramCount":7,"schema":"ba2c8db7ad05","response":"82322ed42796","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false,"result":"envelopes"},- {"name":"items_updateRevision","classification":"WRITE","paramCount":2,"schema":"25c295d358ea","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_upsertChangeNoticeRequiredAction","classification":"WRITE","paramCount":3,"schema":"e790518da1ff","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertChangeNoticeType","classification":"WRITE","paramCount":1,"schema":"a91f73f30ea3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertConfigurationParameter","classification":"WRITE","paramCount":8,"schema":"4dc6f3365b3b","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertConfigurationParameterGroup","classification":"WRITE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertConfigurationRule","classification":"WRITE","paramCount":3,"schema":"da9804f66a45","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertConsumable","classification":"WRITE","paramCount":18,"schema":"917cf6c69912","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},- {"name":"items_upsertItemCost","classification":"WRITE","paramCount":5,"schema":"ec5d1c8dde0d","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemCustomerPart","classification":"WRITE","paramCount":5,"schema":"cde0dd9223dd","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemManufacturing","classification":"WRITE","paramCount":6,"schema":"23bfb7b15eab","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemPlanning","classification":"WRITE","paramCount":14,"schema":"df41fcd1ce4f","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"itemPlanning(itemId,locationId)"},- {"name":"items_upsertItemPostingGroup","classification":"WRITE","paramCount":4,"schema":"c20041c48790","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertItemPurchasing","classification":"WRITE","paramCount":5,"schema":"a2cbed8e5d35","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemSupersession","classification":"DESTRUCTIVE","paramCount":8,"schema":"e50423246d68","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemUnitSalePrice","classification":"WRITE","paramCount":3,"schema":"fafa19d3d976","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMakeMethodVersion","classification":"WRITE","paramCount":3,"schema":"068ef4e9b168","response":"83e06908ebb7","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMaterial","classification":"WRITE","paramCount":25,"schema":"bf3ac65a6327","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},- {"name":"items_upsertMaterialDimension","classification":"WRITE","paramCount":4,"schema":"cd59518ed575","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMaterialFinish","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMaterialForm","classification":"WRITE","paramCount":4,"schema":"e647d9d4d7bd","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertMaterialGrade","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMaterialSubstance","classification":"WRITE","paramCount":4,"schema":"e647d9d4d7bd","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertMaterialType","classification":"WRITE","paramCount":5,"schema":"c033d56db90c","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertMethodMaterial","classification":"WRITE","paramCount":13,"schema":"c08028a572a0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"methodMaterial(id)"},- {"name":"items_upsertMethodOperation","classification":"WRITE","paramCount":22,"schema":"c1059df4fd9a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"methodOperation(id)"},- {"name":"items_upsertMethodOperationParameter","classification":"WRITE","paramCount":5,"schema":"e9784c2bfbc3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertMethodOperationStep","classification":"WRITE","paramCount":11,"schema":"78721aa4be26","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertMethodOperationStepSlide","classification":"WRITE","paramCount":9,"schema":"6be3bd248d68","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertMethodOperationTool","classification":"WRITE","paramCount":5,"schema":"59266e6a790e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertPart","classification":"WRITE","paramCount":21,"schema":"121d76f81f4e","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},- {"name":"items_upsertPickMethod","classification":"WRITE","paramCount":5,"schema":"0e196a6930be","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"pickMethod(itemId,locationId)"},- {"name":"items_upsertPickMethodWithShelfLife","classification":"DESTRUCTIVE","paramCount":6,"schema":"3af3fd086443","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},- {"name":"items_upsertService","classification":"WRITE","paramCount":19,"schema":"e780e7384b56","response":"87c54a97c0fa","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},- {"name":"items_upsertSupplierPart","classification":"WRITE","paramCount":11,"schema":"b7fbcd164308","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"items_upsertTool","classification":"WRITE","paramCount":21,"schema":"121d76f81f4e","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},- {"name":"items_upsertUnitOfMeasure","classification":"WRITE","paramCount":4,"schema":"85315f99e855","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},- {"name":"people_clockIn","classification":"WRITE","paramCount":1,"schema":"3d90cb5d0437","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:update","paginates":false},- {"name":"people_clockOut","classification":"WRITE","paramCount":3,"schema":"f1fa7800aa59","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:update","paginates":false},- {"name":"people_createTimeCardEntry","classification":"WRITE","paramCount":4,"schema":"d88eff32bf40","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create","paginates":false},- {"name":"people_deleteAttribute","classification":"DESTRUCTIVE","paramCount":1,"schema":"437fb5c5c303","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteAttributeCategory","classification":"DESTRUCTIVE","paramCount":1,"schema":"b773edae357b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteDepartment","classification":"DESTRUCTIVE","paramCount":1,"schema":"01883d2055a5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteHoliday","classification":"DESTRUCTIVE","paramCount":1,"schema":"9189cc10f756","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteShift","classification":"DESTRUCTIVE","paramCount":1,"schema":"fbdb1fa56a88","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_deleteTimeCardEntry","classification":"DESTRUCTIVE","paramCount":1,"schema":"c53dc26677e4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:delete","paginates":false},- {"name":"people_getAttribute","classification":"READ","paramCount":1,"schema":"437fb5c5c303","response":"9c635d811516","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getAttributeCategories","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"64bbb296aaa1","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getAttributeCategory","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a52b87433b3b","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getAttributeDataTypes","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"dd6f3a6f89d0","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getClockedInEmployees","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getContacts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"de41996ed14c","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getDepartment","classification":"READ","paramCount":1,"schema":"01883d2055a5","response":"10600fcaa49e","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getDepartments","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"f483d2bc2259","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getDepartmentsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getDepartmentsTree","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8476e48a3c04","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getEmployeeDepartments","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"94b797b98edf","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getEmployeeJob","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"4a3b9b98079b","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getEmployeeShifts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"68279ed68276","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getEmployeeSummary","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"afd28b3efe9e","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getHoliday","classification":"READ","paramCount":1,"schema":"9189cc10f756","response":"8d2b62b6a13b","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getHolidays","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"1fedcd5adb59","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f3764070545e","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getOpenClockEntry","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getPeople","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"5483e69d7515","injectAuth":"companyId","permission":"people:view","paginates":false,"defaults":"always"},- {"name":"people_getRecentTimecards","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getScheduledEmployeesToday","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c93c10ff0dbe","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getShift","classification":"READ","paramCount":1,"schema":"fbdb1fa56a88","response":"86e4039d95bd","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getShifts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"92fec9db1b7e","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getShiftsList","classification":"READ","paramCount":1,"schema":"b76e1039273f","response":"ce08332e0ce6","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getShiftsWithTimes","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"5b99e0634dc7","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getTimecardEntries","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},- {"name":"people_getTimeCardEntries","classification":"READ","paramCount":3,"schema":"bcbe153859d6","response":"f6358cdc55d3","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getTimeCardEntry","classification":"READ","paramCount":1,"schema":"c53dc26677e4","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getWeeklyHoursForEmployees","classification":"READ","paramCount":1,"schema":"392d5681b870","response":"96915ea19193","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_insertAttribute","classification":"WRITE","paramCount":5,"schema":"a9cc1aa15a69","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create","paginates":false},- {"name":"people_insertAttributeCategory","classification":"WRITE","paramCount":3,"schema":"0f2b5b298e7f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create","paginates":false},- {"name":"people_insertEmployeeJob","classification":"WRITE","paramCount":2,"schema":"8518dfd7feec","response":"4a3b9b98079b","injectAuth":"companyId+updatedBy","permission":"people:create","paginates":false},- {"name":"people_updateAttribute","classification":"WRITE","paramCount":4,"schema":"f66dbb270538","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},- {"name":"people_updateAttributeCategory","classification":"WRITE","paramCount":4,"schema":"7bf8c03306de","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},- {"name":"people_updateAttributeSortOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false,"result":"envelopes"},- {"name":"people_updateEmployeeJob","classification":"DESTRUCTIVE","paramCount":2,"schema":"fd3a2eef5bc2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},- {"name":"people_updateTimeCardEntry","classification":"WRITE","paramCount":4,"schema":"486c249ce3fa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},- {"name":"people_upsertDepartment","classification":"WRITE","paramCount":4,"schema":"3d8ae1409b6a","response":"10600fcaa49e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false,"upsert":"id"},- {"name":"people_upsertHoliday","classification":"WRITE","paramCount":4,"schema":"8c7f86c0ca61","response":"8d2b62b6a13b","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false,"upsert":"id"},- {"name":"people_upsertShift","classification":"WRITE","paramCount":13,"schema":"0c60da442fe7","response":"4cc67c58f3c9","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false,"upsert":"id"},- {"name":"production_activateAssemblyInstructionVersion","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_assignPeopleWeek","classification":"WRITE","paramCount":5,"schema":"ea0a43e3afd6","response":"31035ceec7a6","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_autoMatchAssemblyComponents","classification":"WRITE","paramCount":1,"schema":"f9ddf194f67e","response":"41dc031a100a","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_calculateJobPriority","classification":"WRITE","paramCount":4,"schema":"89fd15c91371","response":"cddf8275afa1","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_clearPeopleAbsence","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"11d6b03b19bc","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_completeOperation","classification":"WRITE","paramCount":2,"schema":"92c192733c55","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_convertSalesOrderLinesToJobs","classification":"WRITE","paramCount":1,"schema":"94c4cbf5579d","response":"318d19f6a05c","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_copyAssemblyInstructionAsVersion","classification":"WRITE","paramCount":1,"schema":"87207f927319","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},- {"name":"production_copyPeopleBoard","classification":"WRITE","paramCount":4,"schema":"3cb969f05928","response":"cbf943bfb8ed","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},- {"name":"production_copyPeopleWeek","classification":"WRITE","paramCount":4,"schema":"bd6e745b6883","response":"cbf943bfb8ed","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},- {"name":"production_createAssemblyPlanJob","classification":"WRITE","paramCount":1,"schema":"277f7d872d8c","response":"3797626bd17e","injectAuth":"companyId+createdBy+userId","permission":"production:create","paginates":false},- {"name":"production_createJobDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"6d2b672646dc","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},- {"name":"production_createJobOperationBatch","classification":"WRITE","paramCount":8,"schema":"fffa9134447f","response":"9e056a59d695","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},- {"name":"production_deleteAssemblyComponentMapping","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstruction","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstructionStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstructionStepMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstructionStepSlide","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyInstructionStepTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblySubAssembly","classification":"DESTRUCTIVE","paramCount":2,"schema":"4bb5885b787b","response":"none","injectAuth":"companyId+userId","permission":"production:delete","paginates":false},- {"name":"production_deleteAssemblyUnit","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteFailureMode","classification":"DESTRUCTIVE","paramCount":1,"schema":"4a3e0384d72f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteJob","classification":"DESTRUCTIVE","paramCount":1,"schema":"4999bd4be598","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteJobMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"9b0d4f228240","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteJobOperationParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteJobOperationStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteJobOperationStepSlide","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteJobOperationTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","paramCount":1,"schema":"34cb412f1fae","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteMaintenanceDispatchEvent","classification":"DESTRUCTIVE","paramCount":1,"schema":"281c418606f0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteMaintenanceDispatchItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","paramCount":1,"schema":"c61245800a33","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deletePeopleAssignment","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"6ce160f0feca","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteProcedure","classification":"DESTRUCTIVE","paramCount":1,"schema":"0611728fa5e0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteProcedureParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"2a17205fafa2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteProcedureStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"6b6d6162de02","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteProductionEvent","classification":"DESTRUCTIVE","paramCount":1,"schema":"e749b308e49d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteProductionQuantity","classification":"DESTRUCTIVE","paramCount":1,"schema":"6b2dd7541ea3","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_deleteScrapReason","classification":"DESTRUCTIVE","paramCount":1,"schema":"a5f822fb0806","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:delete","paginates":false},- {"name":"production_duplicateJobOperationStep","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},- {"name":"production_generateAssemblyStepsFromPlan","classification":"DESTRUCTIVE","paramCount":2,"schema":"80eeb7b6dd7c","response":"6a32a10b17d9","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false,"result":"flag"},- {"name":"production_getActiveEmployeeAbilities","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"123f68c94eac","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getActiveJobOperationByJobId","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"ebe9a86ba8b7","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getActiveJobOperationsByLocation","classification":"READ","paramCount":2,"schema":"e1b255975233","response":"6c3ab1d1c098","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getActiveProductionEvents","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"953528dd70d7","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyComponentMappings","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"da74e5f4208a","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstruction","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"76b132dcfb0d","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructions","classification":"READ","paramCount":5,"schema":"902de08eaf06","response":"845b5a451089","injectAuth":"companyId","permission":"production:view","paginates":true},- {"name":"production_getAssemblyInstructionsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c881f4ef7d23","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionStepMaterials","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"89a5f52bebf8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionSteps","classification":"READ","paramCount":1,"schema":"f9ddf194f67e","response":"65fd94da8279","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionStepSlides","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"60aa9b57a118","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionStepTools","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"d771814f7578","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyInstructionVersions","classification":"READ","paramCount":2,"schema":"0c21424ecd86","response":"81c6e04c54bd","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyPlanJson","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"d73d9f72bafb","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getAssemblyUnits","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"7224ef8546c1","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getBatchableOperations","classification":"READ","paramCount":2,"schema":"4cebb10b56d4","response":"3d084de5e690","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getBatchableProcesses","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b0ab8957f96e","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getBatchOutputLots","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"7783e113d7a1","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getCapacityReservationsByJob","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"8ea855e0971b","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getCapacityReservationsForResources","classification":"READ","paramCount":2,"schema":"c0f9784197a0","response":"2ab92ef0d6d4","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getCompletionJobs","classification":"READ","paramCount":4,"schema":"205595d8458d","response":"c0d783b97b99","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getDemandForecasts","classification":"READ","paramCount":3,"schema":"c24ad31f1eaa","response":"21892ee9e3b8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getDemandProjections","classification":"READ","paramCount":3,"schema":"c24ad31f1eaa","response":"f963e0e91868","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getFailureMode","classification":"READ","paramCount":1,"schema":"4a3e0384d72f","response":"2f49c8d39495","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getFailureModes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"6fe6b1e0f957","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getFailureModesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getFlattenedBomMaterials","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7f3fb0d1aeb3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJob","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"1e59878bcf47","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobByOperationId","classification":"READ","paramCount":1,"schema":"c407a9edb930","response":"07382c86b3b8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobDocuments","classification":"READ","paramCount":4,"schema":"f41144061088","response":"5483e69d7515","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobDocumentsWithItemId","classification":"READ","paramCount":2,"schema":"337cb78c5606","response":"5483e69d7515","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobExpediteForecast","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"d377dc3a1fd5","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMakeMethodById","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"96389acf0c72","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterial","classification":"READ","paramCount":1,"schema":"5aa329400da2","response":"7cdf48a49d7f","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialItemIds","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"32068a500dfe","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"a396a00de3b2","response":"b12e99320d04","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialsByMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"562cd876b859","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialShortfallByItem","classification":"READ","paramCount":4,"schema":"644b4df6515a","response":"8a62dcc3c7f9","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialSupplyJobLines","classification":"READ","paramCount":2,"schema":"a396a00de3b2","response":"acbcf89b1800","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMaterialsWithQuantityOnHand","classification":"READ","paramCount":3,"schema":"ef9bf176c913","response":"be0a4b3c547b","injectAuth":"companyId","permission":"production:view","paginates":false,"defaults":"always"},- {"name":"production_getJobMethodTree","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"a0e7ca5d166e","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobMethodTreeArray","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"74f0f766ca05","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperation","classification":"READ","paramCount":1,"schema":"6889e2589fdc","response":"ac4a3201b981","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationAttachments","classification":"READ","paramCount":1,"schema":"0715cdbaa5fb","response":"9a8b9c571a6b","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationBatches","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e4a233e30c55","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getJobOperationBatchEvents","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"8feaefdf02c8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationBatchMembers","classification":"READ","paramCount":1,"schema":"9bbe23a57535","response":"66bcdc105c00","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationBatchMemberStats","classification":"READ","paramCount":1,"schema":"9bbe23a57535","response":"03aaee65a70b","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationBatchWithMembers","classification":"READ","paramCount":1,"schema":"979f64cb9229","response":"97fc58623359","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationDependencies","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"9214ed6d51dd","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperations","classification":"READ","paramCount":2,"schema":"05cbfcbf7494","response":"720a58fe2501","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getJobOperationsAssignedToEmployee","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"20f7748935c7","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationsByMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"3c7b7b51dac3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationsForTimeline","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"6f0169823721","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationsList","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"4e5425835530","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobOperationStepRecords","classification":"READ","paramCount":2,"schema":"08f98a38ea9d","response":"272548978b28","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getJobOrderStatusMap","classification":"READ","paramCount":5,"schema":"2b87b9cde70f","response":"6b4f76e71d08","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobPromiseDate","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"bd69f777e8e9","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobPurchaseOrderLines","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"309dea2a265c","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobReceiptSnapshot","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"af63ddd51939","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobReleaseReadiness","classification":"READ","paramCount":1,"schema":"267b4780c1d3","response":"9712d0076586","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobs","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"be55a4e21412","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getJobsByDateRange","classification":"READ","paramCount":3,"schema":"00794c516592","response":"847ba339f22a","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobsBySalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"be55a4e21412","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getJobsList","classification":"READ","paramCount":1,"schema":"6168fc8fbdbe","response":"232ee7305e73","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getLatestAssemblyPlan","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"6b38ef1e4ead","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getLatestAssemblyPlanJob","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"d45b1cde8dd5","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getLocationEmployees","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"72ccccdcfc21","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatch","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"f0addd41ad4e","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatchComments","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"7df6d6b7ba88","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatches","classification":"READ","paramCount":4,"schema":"c19d6a6c007b","response":"8cdb79a1ff07","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getMaintenanceDispatchEvents","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"fc0af15629d8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatchItems","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"7d22c1b8235d","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDispatchWorkCenters","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"245d61ef36d3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDowntimeForResources","classification":"READ","paramCount":1,"schema":"935cc20961b6","response":"c9ce440846e1","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceSchedule","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"c9d71a024473","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceScheduleItems","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"6e7c564b202a","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceSchedules","classification":"READ","paramCount":4,"schema":"d55eeae51beb","response":"69ee71e3d5a8","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getModelForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"a64658053ae5","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getOutsideOperationsByJobId","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"b75ab9ed0211","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleAbsences","classification":"READ","paramCount":1,"schema":"2f19cae7bae1","response":"f98df1954626","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleAbsencesRange","classification":"READ","paramCount":2,"schema":"265827be4a3e","response":"90f4a38d3460","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleAssignments","classification":"READ","paramCount":2,"schema":"0a3119f1e6d7","response":"6bf01853c73a","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleAssignmentsRange","classification":"READ","paramCount":3,"schema":"00794c516592","response":"ba9f9d495de9","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getPeopleCapacityOperations","classification":"READ","paramCount":3,"schema":"19f229146b3b","response":"9bbc101347c4","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedure","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"54f86be1acc6","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedureParameters","classification":"READ","paramCount":1,"schema":"0611728fa5e0","response":"07629bf64853","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedures","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"ba57bd0be81d","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProceduresList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fe6a24448aaa","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedureSteps","classification":"READ","paramCount":1,"schema":"0611728fa5e0","response":"fd4f59b40560","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProcedureVersions","classification":"READ","paramCount":2,"schema":"89111eab017d","response":"f97efca67bd3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionDataByOperations","classification":"READ","paramCount":1,"schema":"0715cdbaa5fb","response":"9664edfb7c53","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionEvent","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"b1799639bb8d","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionEvents","classification":"READ","paramCount":2,"schema":"91c6f90c1d2d","response":"acc5e1d1e2c9","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProductionEventsByJob","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"0c36813c32a1","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionEventsByOperations","classification":"READ","paramCount":1,"schema":"0715cdbaa5fb","response":"acc5e1d1e2c9","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getProductionEventsPage","classification":"READ","paramCount":3,"schema":"d3ce152358d0","response":"d82d26b306e9","injectAuth":"companyId","permission":"production:view","paginates":true},- {"name":"production_getProductionPlanning","classification":"READ","paramCount":3,"schema":"4d6e5e2b1875","response":"70236c14db92","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProductionProjections","classification":"READ","paramCount":3,"schema":"c3afb01f3040","response":"4973a62dfd1b","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProductionQuantities","classification":"READ","paramCount":2,"schema":"91c6f90c1d2d","response":"3b4cf7a6bc87","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getProductionQuantity","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"c506c8c71d8f","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getRootMakeMethod","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"96389acf0c72","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getScrapReason","classification":"READ","paramCount":1,"schema":"a5f822fb0806","response":"4bbb50609deb","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getScrapReasons","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a5e736373756","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},- {"name":"production_getScrapReasonsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getTrackedEntitiesByJobId","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"c20d7cb06756","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getTrackedEntityByJobId","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"d485710baf81","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getUnbatchedBatchableOperationCount","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce387c10b075","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getUnscheduledJobs","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"807e503150d6","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getWorkCenterRequiredAbilities","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"7418ea1fc0a7","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getWorkCenterReservationsRange","classification":"READ","paramCount":2,"schema":"99ea73b8e7a1","response":"a7e9bc09d2ab","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getWorkCenterShifts","classification":"READ","paramCount":1,"schema":"e94892850934","response":"2b4835f80e6c","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_insertAssemblyInstructionStep","classification":"WRITE","paramCount":1,"schema":"f14d1689b7f8","response":"00404e686415","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},- {"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"231e1d7f0444","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},- {"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_makeAssemblySubAssembly","classification":"WRITE","paramCount":2,"schema":"e39572ccf46c","response":"00404e686415","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_maxToolQuantityByItem","classification":"READ","paramCount":1,"schema":"8b9e90037b9a","response":"none","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_recalculateJobOperationDependencies","classification":"WRITE","paramCount":1,"schema":"4999bd4be598","response":"a70079765330","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_recalculateJobRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_releaseJobOperationBatch","classification":"WRITE","paramCount":1,"schema":"979f64cb9229","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_runMRP","classification":"WRITE","paramCount":2,"schema":"6e039fba26f6","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_scheduleJob","classification":"WRITE","paramCount":1,"schema":"4999bd4be598","response":"a70079765330","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_setJobMaterialStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"805d2a5ebf8e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_setJobOperationToolStepLink","classification":"DESTRUCTIVE","paramCount":4,"schema":"2d14950ae331","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_setPeopleAbsence","classification":"WRITE","paramCount":4,"schema":"efea076202c2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_setPeopleAbsenceRange","classification":"WRITE","paramCount":5,"schema":"f40e1c93667c","response":"9859df3143fe","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_setPeopleAssignmentHours","classification":"WRITE","paramCount":2,"schema":"29aa7bdf6d50","response":"3ca729812149","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_setPeopleDay","classification":"DESTRUCTIVE","paramCount":7,"schema":"e5c972d7b8c3","response":"b4c094a53e37","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_setPeopleOvertimeBulk","classification":"WRITE","paramCount":6,"schema":"8f082483561d","response":"577d7088b794","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_syncAssemblyInstructionToOperation","classification":"DESTRUCTIVE","paramCount":2,"schema":"8160f8d92b1b","response":"4348d3bad80b","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_syncAssemblyStepMaterialsFromMappings","classification":"WRITE","paramCount":4,"schema":"7f7346bb3bd0","response":"5815c4dbf43d","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_toViewerStep","classification":"WRITE","paramCount":1,"schema":"29ac1466e693","response":"af67df1e83ed","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_unassignPeopleWeek","classification":"DESTRUCTIVE","paramCount":4,"schema":"06ead5d3d9ce","response":"9658926b2cd2","injectAuth":"companyId","permission":"production:update","paginates":false},- {"name":"production_ungroupAssemblySubAssembly","classification":"DESTRUCTIVE","paramCount":2,"schema":"4bb5885b787b","response":"none","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_unreleaseJobOperationBatch","classification":"WRITE","paramCount":1,"schema":"979f64cb9229","response":"9e056a59d695","injectAuth":"companyId+userId","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStatus","classification":"WRITE","paramCount":2,"schema":"e43955681d7c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStepMaterialOrder","classification":"WRITE","paramCount":2,"schema":"5a4d7dc208a5","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStepOrder","classification":"WRITE","paramCount":2,"schema":"86adf519c2e9","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyInstructionStepStatus","classification":"WRITE","paramCount":2,"schema":"9291eed55a4a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyStepComponents","classification":"WRITE","paramCount":2,"schema":"d7ea6b1800f7","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyStepHiddenComponents","classification":"WRITE","paramCount":3,"schema":"3ac4e88c4df0","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblyStepMotion","classification":"WRITE","paramCount":5,"schema":"aa7dfb67132e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateAssemblySubAssembly","classification":"WRITE","paramCount":4,"schema":"0f0cbf9e32e1","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_updateJob","classification":"WRITE","paramCount":22,"schema":"fc37d97579b2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateJobBatchNumber","classification":"WRITE","paramCount":2,"schema":"a4c2a31bb8a6","response":"f7a40899c090","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateJobMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateJobOperationBatch","classification":"WRITE","paramCount":4,"schema":"6aa26c8c9567","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_updateJobOperationDueDate","classification":"WRITE","paramCount":2,"schema":"e04478fc58f7","response":"ac4a3201b981","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"context":"updatedBy=userId"},- {"name":"production_updateJobOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateJobOperationStatus","classification":"WRITE","paramCount":2,"schema":"b22654081076","response":"ac4a3201b981","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"context":"updatedBy=userId"},- {"name":"production_updateJobOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateJobStatus","classification":"WRITE","paramCount":4,"schema":"458fa5786030","response":"8394fbabd845","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateKanbanJob","classification":"WRITE","paramCount":2,"schema":"2c22838be2d2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_updateMethodOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateProcedureStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_upsertAssemblyComponentMapping","classification":"WRITE","paramCount":4,"schema":"9ed1f38ce764","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertAssemblyInstruction","classification":"WRITE","paramCount":4,"schema":"a1796f1bd347","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","paramCount":1,"schema":"28bd332a0905","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertAssemblyInstructionStepMaterial","classification":"WRITE","paramCount":5,"schema":"a21b4fac4b90","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertAssemblyInstructionStepSlide","classification":"WRITE","paramCount":9,"schema":"6be3bd248d68","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertAssemblyInstructionStepTool","classification":"WRITE","paramCount":5,"schema":"d64500fd5c94","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertAssemblyUnit","classification":"WRITE","paramCount":5,"schema":"74497d782594","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertFailureMode","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertJob","classification":"WRITE","paramCount":2,"schema":"2a177dc982bb","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertJobMaterial","classification":"WRITE","paramCount":17,"schema":"c9c68d632c9d","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"jobMaterial(id)"},- {"name":"production_upsertJobMaterialMakeMethod","classification":"WRITE","paramCount":5,"schema":"d603e9c57b46","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create+update","paginates":false},- {"name":"production_upsertJobMethod","classification":"WRITE","paramCount":2,"schema":"170fba7b05c6","response":"9e056a59d695","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create+update","paginates":false},- {"name":"production_upsertJobOperation","classification":"WRITE","paramCount":26,"schema":"46e4f69aa1f7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"jobOperation(id)"},- {"name":"production_upsertJobOperationParameter","classification":"WRITE","paramCount":5,"schema":"e9784c2bfbc3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertJobOperationStep","classification":"WRITE","paramCount":11,"schema":"78721aa4be26","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertJobOperationStepSlide","classification":"WRITE","paramCount":9,"schema":"6be3bd248d68","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertJobOperationTool","classification":"WRITE","paramCount":5,"schema":"59266e6a790e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertMaintenanceDispatchComment","classification":"WRITE","paramCount":3,"schema":"15129a94d57d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertMaintenanceDispatchEvent","classification":"WRITE","paramCount":7,"schema":"a98569352969","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertMaintenanceDispatchItem","classification":"WRITE","paramCount":6,"schema":"41c857266e1d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertMaintenanceSchedule","classification":"WRITE","paramCount":8,"schema":"4f46ce8d0845","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertMakeMethodFromJob","classification":"WRITE","paramCount":3,"schema":"32b3a0f5efa0","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create+update","paginates":false},- {"name":"production_upsertMakeMethodFromJobMethod","classification":"WRITE","paramCount":3,"schema":"32b3a0f5efa0","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create+update","paginates":false},- {"name":"production_upsertPeopleAssignment","classification":"DESTRUCTIVE","paramCount":7,"schema":"1ec71dfcea20","response":"a726aa587ccc","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},- {"name":"production_upsertProcedure","classification":"WRITE","paramCount":6,"schema":"d4a8e99e0523","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertProcedureParameter","classification":"WRITE","paramCount":4,"schema":"3ec6c5dece78","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertProcedureStep","classification":"WRITE","paramCount":10,"schema":"af47a3cf4652","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertProductionEvent","classification":"WRITE","paramCount":8,"schema":"05b066cee802","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertProductionQuantity","classification":"WRITE","paramCount":6,"schema":"24b2fd6be216","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"production_upsertScrapReason","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_cancelPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_confirmPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_convertSupplierQuoteToOrder","classification":"WRITE","paramCount":2,"schema":"16be78b08a8f","response":"ec9aaaf82857","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_createPurchaseReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"806d15ac58ff","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"invoicing:create","paginates":false},- {"name":"purchasing_createReplacementPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"11b028f16d94","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},- {"name":"purchasing_createSupplierInteractionDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"a424256cbe29","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_createSupplierInteractionLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_deleteLease","classification":"DESTRUCTIVE","paramCount":1,"schema":"9fb51372ff53","response":"8394fbabd845","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteLeaseLine","classification":"DESTRUCTIVE","paramCount":2,"schema":"bb4487ea3e25","response":"8394fbabd845","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteLeasePayment","classification":"DESTRUCTIVE","paramCount":2,"schema":"ae1ccfbfd489","response":"8394fbabd845","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchaseOrder","classification":"DESTRUCTIVE","paramCount":1,"schema":"28cffcd9d6e8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchaseOrderLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"ed69a5b8e424","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchaseReturnOrder","classification":"DESTRUCTIVE","paramCount":1,"schema":"11b028f16d94","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchaseReturnOrderLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"063a6777d378","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchasingRFQ","classification":"DESTRUCTIVE","paramCount":1,"schema":"4e16cef99961","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deletePurchasingRFQLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"943916e70d0b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplier","classification":"DESTRUCTIVE","paramCount":1,"schema":"67043a31b1b5","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"purchasing_deleteSupplierContact","classification":"DESTRUCTIVE","paramCount":2,"schema":"041a4bd97ec8","response":"700b93baa3ef","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierLocation","classification":"DESTRUCTIVE","paramCount":2,"schema":"dad5decd6951","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierProcess","classification":"DESTRUCTIVE","paramCount":1,"schema":"fe73a000b6f7","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierQuote","classification":"DESTRUCTIVE","paramCount":1,"schema":"5db39f9abf41","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierQuoteLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_deleteSupplierType","classification":"DESTRUCTIVE","paramCount":1,"schema":"900045091850","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},- {"name":"purchasing_duplicatePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"b6bf3abf506d","response":"f5212679d580","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},- {"name":"purchasing_finalizePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_finalizePurchasingRfq","classification":"WRITE","paramCount":1,"schema":"9531e4360acd","response":"e2e56b5a6c0a","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_finalizeSupplierQuote","classification":"WRITE","paramCount":1,"schema":"5db39f9abf41","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_getCreditableQuantitiesForPurchaseReturn","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"1e97e6c72b1d","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getDefaultAttachmentsForPO","classification":"READ","paramCount":2,"schema":"17cccb0ea3ef","response":"4a42c6b9da80","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLease","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"088b0a26be2c","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeaseEvents","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"d33db68815b5","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeaseLines","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"c67039919353","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeasePayments","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"73152bc44605","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeaseRelatedDocuments","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"c999fc505e07","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLeases","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"2492d3f8f118","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getLeaseSchedule","classification":"READ","paramCount":1,"schema":"9fb51372ff53","response":"033eb326814e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLinkedPurchasingRfqs","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"9c82bc9ce35e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLinkedPurchasingRfqsForInteraction","classification":"READ","paramCount":1,"schema":"6e2899e1731e","response":"c7f7518e09d1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLinkedPurchasingRfqsForOrder","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"9c82bc9ce35e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getLinkedSupplierQuotes","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"cb143b1fe761","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrder","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"3797db2be7c6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderDelivery","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"0564bac29ef5","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderLine","classification":"READ","paramCount":1,"schema":"ed69a5b8e424","response":"56c9d7ca858b","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderLines","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"4e2a81139b3b","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderLocations","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"d4d4c42eb761","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrderPayment","classification":"READ","paramCount":1,"schema":"28cffcd9d6e8","response":"c7a62e53e09b","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseOrders","classification":"READ","paramCount":5,"schema":"f3468ea9b0a6","response":"fbaa9ca23142","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getPurchaseOrderSuppliers","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fc7a0345fc53","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrder","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"8cb2133c047e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderCredits","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"49639d091139","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderIssues","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"a81c998e95a3","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"6e3bf67c7a97","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderLines","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"1f58312907d8","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrderLineTrackedEntities","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"75ed48edf5c1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchaseReturnOrders","classification":"READ","paramCount":5,"schema":"f3468ea9b0a6","response":"de438833d869","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getPurchaseReturnOrderShipments","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"08e1b6f03862","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingDocumentsAssignedToMe","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"cb047e0da459","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingPlanning","classification":"READ","paramCount":3,"schema":"4d6e5e2b1875","response":"e09989d16685","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getPurchasingRFQ","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"08cb90c207da","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingRFQLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"045f66457f11","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingRFQLines","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"24a761144b4a","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingRFQs","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a2661a189775","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getPurchasingRFQSuppliers","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"5483e69d7515","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingRFQSuppliersWithLinks","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"5483e69d7515","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingTerms","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"91b7924d48bd","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getReturnableEntitiesForReceiptLine","classification":"READ","paramCount":2,"schema":"0d233758ff1f","response":"5c104e265494","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getReturnableEntitiesForSupplier","classification":"READ","paramCount":2,"schema":"3700a887762e","response":"4e436e8a6f98","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getReturnableLinesForSupplier","classification":"READ","paramCount":2,"schema":"7a1204db0d90","response":"24dd6c0d1c55","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSiblingQuotesForQuote","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"cb143b1fe761","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"10c7209cc38a","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierBankAccounts","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"f2b09b60b722","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"purchasing_getSupplierContact","classification":"READ","paramCount":1,"schema":"bc2c630a873e","response":"6d2aa722b1ce","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierContacts","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"e28ccbd2c417","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierInteraction","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"e933ede17ac0","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierInteractionDocuments","classification":"READ","paramCount":1,"schema":"2df4b3d111cd","response":"95c1c04c0566","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierInteractionLineDocuments","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"95c1c04c0566","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierLocation","classification":"READ","paramCount":1,"schema":"bc2c630a873e","response":"4603d06d1055","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierLocations","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"6dad1063175d","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierPayment","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"24b286adf1ff","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierProcessById","classification":"READ","paramCount":1,"schema":"fe73a000b6f7","response":"7d3e895a1991","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierProcessesByProcess","classification":"READ","paramCount":1,"schema":"01edb53077b2","response":"c2eb609c8ad1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierProcessesBySupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"c2eb609c8ad1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuote","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"f998bf4f97dc","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteByExternalLinkId","classification":"READ","paramCount":1,"schema":"feb52bb98a20","response":"8c242582e5e6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteByInteractionId","classification":"READ","paramCount":1,"schema":"2df4b3d111cd","response":"f998bf4f97dc","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteLine","classification":"READ","paramCount":1,"schema":"88823065a537","response":"549f0e57572d","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteLinePrices","classification":"READ","paramCount":1,"schema":"88823065a537","response":"22abc40c4789","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteLinePricesByQuoteId","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"22abc40c4789","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuoteLines","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"50759a9c2b79","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuotes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"9e311e59b82e","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getSupplierQuotesForComparison","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"540207b2c74e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierQuotesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"967dcad15168","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierReportContacts","classification":"READ","paramCount":1,"schema":"f6d6276b4996","response":"5adbc4c5e67c","injectAuth":"companyId","permission":"purchasing:view","paginates":false,"result":"envelopes"},- {"name":"purchasing_getSuppliers","classification":"READ","paramCount":5,"schema":"fe4524096cbe","response":"947b627d845e","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getSupplierShipping","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"17117a952d24","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSuppliersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierTax","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"303387b4fc28","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierType","classification":"READ","paramCount":1,"schema":"900045091850","response":"8b3eca34dbfd","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7c6550dea5b1","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},- {"name":"purchasing_getSupplierTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_insertLease","classification":"WRITE","paramCount":19,"schema":"b7cf150e300e","response":"f6631a819d19","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false,"defaults":"always"},- {"name":"purchasing_insertPurchaseOrder","classification":"WRITE","paramCount":15,"schema":"27513cc48e8d","response":"73785d310369","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_insertPurchaseReturnOrder","classification":"WRITE","paramCount":12,"schema":"d3253380f7e2","response":"d53d13c89312","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_insertPurchasingRFQ","classification":"WRITE","paramCount":8,"schema":"cb4ec49c926e","response":"0c1a1b93cca3","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_insertSupplier","classification":"WRITE","paramCount":9,"schema":"05cf2198c6ac","response":"9d2416e8ad75","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_insertSupplierContact","classification":"WRITE","paramCount":4,"schema":"987f8dd2f02d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_insertSupplierLocation","classification":"WRITE","paramCount":4,"schema":"c903cae736f0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_insertSupplierQuote","classification":"WRITE","paramCount":13,"schema":"aa8560bfb767","response":"77e21c1e2e32","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_reopenPurchaseOrderAsRevision","classification":"WRITE","paramCount":2,"schema":"ffa38ce5274f","response":"cddf8275afa1","injectAuth":"companyId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_reopenPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_sendSupplierQuote","classification":"WRITE","paramCount":1,"schema":"5db39f9abf41","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_setPurchaseReturnOrderLineTrackedEntities","classification":"DESTRUCTIVE","paramCount":2,"schema":"f3f13d81cd8c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_shortClosePurchaseOrderLine","classification":"WRITE","paramCount":3,"schema":"fc9c2f370fc5","response":"none","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_shortClosePurchaseReturnOrderLine","classification":"WRITE","paramCount":3,"schema":"a21cfee98b1a","response":"none","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateLeaseDetails","classification":"WRITE","paramCount":5,"schema":"a42727e2a52e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchaseOrder","classification":"WRITE","paramCount":11,"schema":"f254c2222188","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchaseOrderExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchaseOrderFavorite","classification":"DESTRUCTIVE","paramCount":2,"schema":"85769b943e30","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchaseOrderLineOrder","classification":"WRITE","paramCount":2,"schema":"744101d1c67c","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchaseOrderStatus","classification":"WRITE","paramCount":3,"schema":"d55cadd232ef","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchasingRFQLineOrder","classification":"WRITE","paramCount":2,"schema":"3be259f3e887","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updatePurchasingRFQStatus","classification":"WRITE","paramCount":3,"schema":"8dc0490a9402","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierContact","classification":"WRITE","paramCount":4,"schema":"f6b4a36788e6","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierLocation","classification":"WRITE","paramCount":4,"schema":"9d205b68ee4f","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierPayment","classification":"WRITE","paramCount":6,"schema":"7c667f4542f3","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierQuote","classification":"WRITE","paramCount":8,"schema":"64e0b2d29d98","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierQuoteExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierQuoteLineOrder","classification":"WRITE","paramCount":2,"schema":"7bf10894875d","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierQuoteStatus","classification":"WRITE","paramCount":3,"schema":"856b61886f1f","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierShipping","classification":"WRITE","paramCount":8,"schema":"ac0c2133e800","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_updateSupplierTax","classification":"WRITE","paramCount":8,"schema":"7e31a89af103","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_upsertLeasePayment","classification":"WRITE","paramCount":8,"schema":"341b1b86d9c9","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},- {"name":"purchasing_upsertPurchaseOrder","classification":"WRITE","paramCount":2,"schema":"d458b7f2c10f","response":"1b33aad6f934","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_upsertPurchaseOrderDelivery","classification":"WRITE","paramCount":15,"schema":"5fb9d54c12e7","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertPurchaseOrderLine","classification":"WRITE","paramCount":25,"schema":"ca0929113e1d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"purchasing_upsertPurchaseOrderPayment","classification":"WRITE","paramCount":6,"schema":"1e1be871f655","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertPurchaseReturnOrderLine","classification":"WRITE","paramCount":12,"schema":"9272c7cdfeaf","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_upsertPurchasingRFQ","classification":"WRITE","paramCount":8,"schema":"fdd694519621","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false},- {"name":"purchasing_upsertPurchasingRFQLine","classification":"WRITE","paramCount":1,"schema":"66adf4b67af2","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_upsertPurchasingRFQSuppliers","classification":"DESTRUCTIVE","paramCount":2,"schema":"fa459fc25bca","response":"5c9ba5bee3f1","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"context":"createdBy=userId"},- {"name":"purchasing_upsertSupplier","classification":"WRITE","paramCount":10,"schema":"999cedb57790","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_upsertSupplierBankAccount","classification":"WRITE","paramCount":13,"schema":"cde0d3ca4444","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_upsertSupplierProcess","classification":"WRITE","paramCount":6,"schema":"26d15056f196","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_upsertSupplierQuoteLine","classification":"WRITE","paramCount":14,"schema":"3c9810ea1df4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"name":"purchasing_upsertSupplierType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create+update","paginates":false,"upsert":"id"},- {"name":"quality_activateGauge","classification":"WRITE","paramCount":1,"schema":"f65da45a1155","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:update","paginates":false},- {"name":"quality_deactivateGauge","classification":"WRITE","paramCount":1,"schema":"f65da45a1155","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:update","paginates":false},- {"name":"quality_deleteGauge","classification":"DESTRUCTIVE","paramCount":1,"schema":"f65da45a1155","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteGaugeCalibrationRecord","classification":"DESTRUCTIVE","paramCount":1,"schema":"81eca1e58f6e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteGaugeType","classification":"DESTRUCTIVE","paramCount":1,"schema":"24fb90489cd4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteInspectionDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"e92dda062549","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteIssue","classification":"DESTRUCTIVE","paramCount":1,"schema":"a78c6c21c084","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteIssueAssociation","classification":"DESTRUCTIVE","paramCount":2,"schema":"5e9621fb955d","response":"none","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteIssueType","classification":"DESTRUCTIVE","paramCount":1,"schema":"bb6b04f68710","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteIssueWorkflow","classification":"DESTRUCTIVE","paramCount":1,"schema":"15a80db054e6","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteQualityDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"6d79e6870690","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteRequiredAction","classification":"DESTRUCTIVE","paramCount":1,"schema":"cca3bf9f3ebb","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_deleteRisk","classification":"DESTRUCTIVE","paramCount":1,"schema":"7002f7ae1c58","response":"bcde375ebd4c","injectAuth":"companyId","permission":"quality:delete","paginates":false},- {"name":"quality_getBalloons","classification":"READ","paramCount":1,"schema":"c25fe011e891","response":"3fec0abbc97d","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGauge","classification":"READ","paramCount":1,"schema":"f65da45a1155","response":"19d84b9bffdb","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGaugeCalibrationRecord","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"90fb86d6af14","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGaugeCalibrationRecords","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7ed9f83a9f0f","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getGaugeCalibrationRecordsByGaugeId","classification":"READ","paramCount":1,"schema":"f65da45a1155","response":"7ed9f83a9f0f","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGauges","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7d2b6ae79d59","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getGaugesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"34b9a5801676","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGaugeType","classification":"READ","paramCount":1,"schema":"24fb90489cd4","response":"63b5b3f8f143","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getGaugeTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"95195653f3fc","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getGaugeTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspection","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionDocument","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a82889f583de","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionDocuments","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"0daf2106401c","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getInspectionDocumentsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"cfa5f1f7b8aa","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionFeatures","classification":"READ","paramCount":1,"schema":"c25fe011e891","response":"1e8d8f002f21","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionGauges","classification":"READ","paramCount":1,"schema":"d88996520fca","response":"d5c3ebb5ddd2","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionMeasurements","classification":"READ","paramCount":1,"schema":"d88996520fca","response":"c6a90b70c17b","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionPlan","classification":"READ","paramCount":1,"schema":"c25fe011e891","response":"83a9b3640e41","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspections","classification":"READ","paramCount":5,"schema":"81ca1d9d2144","response":"b942685a303b","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getInspectionSamplingPlans","classification":"READ","paramCount":1,"schema":"d88996520fca","response":"5b3237ad5668","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionTrackedEntities","classification":"READ","paramCount":1,"schema":"17337505bb69","response":"c20d7cb06756","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssue","classification":"READ","paramCount":1,"schema":"a78c6c21c084","response":"1a2ca8014c88","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueActionTasks","classification":"READ","paramCount":2,"schema":"989a1bef3af7","response":"0f3a25ff459d","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueApprovalTasks","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"60bd02d2af2c","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueAssociations","classification":"READ","paramCount":1,"schema":"a78c6c21c084","response":"ebdefbd901a7","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueFromExternalLink","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"81ecd90279ab","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueItems","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ca2b3990f2f7","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueReviewers","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"fa7631f38515","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssues","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e08ce0758580","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getIssueSuppliers","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"2a7e42e2f8c2","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueTasks","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"28fce89961bd","injectAuth":"companyId","permission":"quality:view","paginates":false,"result":"envelopes"},- {"name":"quality_getIssueType","classification":"READ","paramCount":1,"schema":"bb6b04f68710","response":"63b5b3f8f143","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueTypeByName","classification":"READ","paramCount":2,"schema":"858a6cb73bbb","response":"3797626bd17e","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"95195653f3fc","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getIssueTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueWorkflow","classification":"READ","paramCount":1,"schema":"15a80db054e6","response":"3272b87b8442","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueWorkflows","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"38608ae87f0d","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getIssueWorkflowsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"38608ae87f0d","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getItemInspectionDocumentAssignments","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"9bedeef9a12b","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityActions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"76d10ad61a21","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getQualityDocument","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a8b2d87af029","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityDocuments","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"8bb4ab685129","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getQualityDocumentsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f0df86b695e6","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityDocumentSteps","classification":"READ","paramCount":1,"schema":"6d79e6870690","response":"55202747c3b2","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityDocumentVersions","classification":"READ","paramCount":2,"schema":"89111eab017d","response":"63e52c70cbef","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityFiles","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ffefd03548aa","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getReceiptInspections","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"e30d015c0242","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getRequiredAction","classification":"READ","paramCount":1,"schema":"cca3bf9f3ebb","response":"00f7e228e469","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getRequiredActions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"477e4aa9ac3b","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_getRequiredActionsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getRisk","classification":"READ","paramCount":1,"schema":"7002f7ae1c58","response":"f0e54ff68cc5","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getRisks","classification":"READ","paramCount":6,"schema":"edf9ecb3ea7f","response":"72f8ffc765cc","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},- {"name":"quality_insertGauge","classification":"WRITE","paramCount":15,"schema":"f067ee95ad2f","response":"3269d4609ad2","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create","paginates":false},- {"name":"quality_insertIssue","classification":"WRITE","paramCount":20,"schema":"308033845426","response":"bf12cbd0f560","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create","paginates":false},- {"name":"quality_insertIssueReviewer","classification":"WRITE","paramCount":2,"schema":"fdfb09172931","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create","paginates":false},- {"name":"quality_saveInspectionDocumentAtomic","classification":"WRITE","paramCount":7,"schema":"302bbaaf5d0c","response":"none","injectAuth":"companyId+userId","permission":"quality:update","paginates":false},- {"name":"quality_updateGauge","classification":"WRITE","paramCount":16,"schema":"d62e872469a5","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateInspectionDocumentSampling","classification":"WRITE","paramCount":7,"schema":"e85058fba971","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"quality:update","paginates":false},- {"name":"quality_updateIssue","classification":"WRITE","paramCount":16,"schema":"93bb71a6bcdc","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateIssueActionProcesses","classification":"DESTRUCTIVE","paramCount":2,"schema":"9dbd38e74ee8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateIssueStatus","classification":"WRITE","paramCount":4,"schema":"71469c92601d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateIssueTaskContent","classification":"WRITE","paramCount":3,"schema":"4475ba505172","response":"a78c6c21c084","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},- {"name":"quality_updateIssueTaskStatus","classification":"WRITE","paramCount":4,"schema":"cd763f773f42","response":"a78c6c21c084","injectAuth":"companyId+updatedBy+userId","permission":"quality:update","paginates":false},- {"name":"quality_upsertGaugeCalibrationRecord","classification":"WRITE","paramCount":15,"schema":"edcab69c8c1a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"name":"quality_upsertGaugeType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"name":"quality_upsertInspectionDocument","classification":"WRITE","paramCount":10,"schema":"68e08a92df7a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertIssueType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"name":"quality_upsertIssueWorkflow","classification":"WRITE","paramCount":7,"schema":"e1638767f6ac","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"name":"quality_upsertItemInspectionDocumentAssignment","classification":"DESTRUCTIVE","paramCount":3,"schema":"3e4ebfc49e2a","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"quality:create+update","paginates":false},- {"name":"quality_upsertQualityDocument","classification":"WRITE","paramCount":5,"schema":"acd2ed0af051","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"name":"quality_upsertRequiredAction","classification":"WRITE","paramCount":3,"schema":"f0cd89df8f83","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"name":"quality_upsertRisk","classification":"WRITE","paramCount":12,"schema":"980470d15320","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false,"upsert":"id"},- {"name":"resources_activateProcess","classification":"WRITE","paramCount":1,"schema":"01edb53077b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},- {"name":"resources_activateWorkCenter","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},- {"name":"resources_deleteAbility","classification":"DESTRUCTIVE","paramCount":2,"schema":"f642be0f483d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteContractor","classification":"DESTRUCTIVE","paramCount":1,"schema":"c178e4a4c21e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteEmployeeAbility","classification":"DESTRUCTIVE","paramCount":1,"schema":"5ccac46fc41e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteFailureMode","classification":"DESTRUCTIVE","paramCount":1,"schema":"4a3e0384d72f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteLocation","classification":"DESTRUCTIVE","paramCount":1,"schema":"de371a276a58","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","paramCount":1,"schema":"34cb412f1fae","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteMaintenanceDispatchEvent","classification":"DESTRUCTIVE","paramCount":1,"schema":"281c418606f0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteMaintenanceDispatchItem","classification":"DESTRUCTIVE","paramCount":1,"schema":"623ca47a6c74","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","paramCount":1,"schema":"c61245800a33","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deletePartner","classification":"DESTRUCTIVE","paramCount":1,"schema":"74d289586b4f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteProcess","classification":"DESTRUCTIVE","paramCount":1,"schema":"01edb53077b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteShift","classification":"DESTRUCTIVE","paramCount":1,"schema":"fbdb1fa56a88","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteSuggestion","classification":"DESTRUCTIVE","paramCount":1,"schema":"3a7f44ccb395","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteTraining","classification":"DESTRUCTIVE","paramCount":1,"schema":"3f6f0a410b0f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteTrainingAssignment","classification":"DESTRUCTIVE","paramCount":1,"schema":"7d3fe60cc8ed","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteTrainingCompletion","classification":"DESTRUCTIVE","paramCount":1,"schema":"656576baec15","response":"a390c0860228","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteTrainingQuestion","classification":"DESTRUCTIVE","paramCount":1,"schema":"b4f48c09ba9f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_deleteWorkCenter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},- {"name":"resources_ensureProcessAbility","classification":"WRITE","paramCount":2,"schema":"6381d05a75ce","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"resources:update","paginates":false},- {"name":"resources_getAbilities","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"53c80a9d1965","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getAbilitiesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fc7a0345fc53","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getAbility","classification":"READ","paramCount":1,"schema":"5133c0e3b586","response":"d98eac986c97","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getContractor","classification":"READ","paramCount":1,"schema":"c178e4a4c21e","response":"995cb2d28a3e","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getContractors","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"155b783e2512","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getEmployeeAbilities","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"328aa0024967","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getEmployeeAbility","classification":"READ","paramCount":1,"schema":"5ccac46fc41e","response":"f0d72cd0ea38","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getFailureMode","classification":"READ","paramCount":1,"schema":"4a3e0384d72f","response":"2f49c8d39495","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getFailureModes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"6fe6b1e0f957","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getFailureModesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"99dfd44b4c2e","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getLocations","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"cf3608cc2732","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getLocationsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e19c89c1e8a0","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatch","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"5547ae49213e","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatchComments","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"7df6d6b7ba88","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatches","classification":"READ","paramCount":4,"schema":"c19d6a6c007b","response":"8cdb79a1ff07","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getMaintenanceDispatchesByLocation","classification":"READ","paramCount":2,"schema":"5ccae51b79d8","response":"774cad94afc0","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getMaintenanceDispatchEvents","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"fc0af15629d8","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatchItems","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"595d666b79ec","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatchItemTrackedEntities","classification":"READ","paramCount":1,"schema":"63ddd4fe05c0","response":"0ae53e4d5350","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceDispatchWorkCenters","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"245d61ef36d3","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceSchedule","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"c9d71a024473","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceScheduleItems","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"6e7c564b202a","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getMaintenanceSchedules","classification":"READ","paramCount":4,"schema":"d55eeae51beb","response":"69ee71e3d5a8","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getMaintenanceSchedulesByLocation","classification":"READ","paramCount":2,"schema":"68aa9154c497","response":"71889eb4641f","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getOutstandingTrainingsForUser","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"912a69b68c49","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getPartner","classification":"READ","paramCount":2,"schema":"7a4efbb751fd","response":"690aa589fb9c","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getPartnerBySupplierId","classification":"READ","paramCount":1,"schema":"74d289586b4f","response":"690aa589fb9c","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getPartners","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"f1a7446bd053","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getProcess","classification":"READ","paramCount":1,"schema":"01edb53077b2","response":"d981fcf79885","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getProcesses","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"e2daca4791c0","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getProcessesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getProcessesWithoutAbility","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getSuggestion","classification":"READ","paramCount":1,"schema":"3a7f44ccb395","response":"77bb66a1249a","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getSuggestions","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"9e90aae0404b","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getTraining","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"7339291fb8fa","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignment","classification":"READ","paramCount":1,"schema":"7d3fe60cc8ed","response":"c9862a5e4a1f","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentForCompletion","classification":"READ","paramCount":1,"schema":"7d3fe60cc8ed","response":"099b764ee26c","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignments","classification":"READ","paramCount":1,"schema":"d541f0a7e11f","response":"5afd387c50a2","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentStatus","classification":"READ","paramCount":4,"schema":"12f3ccba8f51","response":"912a69b68c49","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentStatusForEmployee","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"912a69b68c49","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingAssignmentSummary","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"9528aa75cdb8","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingGrantedAbilityId","classification":"READ","paramCount":1,"schema":"fbebd108a3c4","response":"174e29b899b9","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainingQuestions","classification":"READ","paramCount":1,"schema":"3f6f0a410b0f","response":"cbc84076fe3b","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getTrainings","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"cc28f2dfe36f","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getTrainingsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8a9d99ad8810","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getWorkCenter","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"e5193d0e2978","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getWorkCenters","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"0340d99e8700","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},- {"name":"resources_getWorkCentersByLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"f602591e2bf5","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getWorkCentersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0340d99e8700","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getWorkCentersListWithBlockingStatus","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fcb9583f02e0","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_insertMaintenanceDispatch","classification":"WRITE","paramCount":14,"schema":"b192bab74c65","response":"ede36af7307d","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create","paginates":false},- {"name":"resources_processDeactivate","classification":"WRITE","paramCount":1,"schema":"01edb53077b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},- {"name":"resources_resolveEmployeeAbilityExpiresAt","classification":"WRITE","paramCount":3,"schema":"ec5fc6dfaa43","response":"174e29b899b9","injectAuth":"companyId","permission":"resources:update","paginates":false},- {"name":"resources_updateAbility","classification":"WRITE","paramCount":2,"schema":"331c98a989f9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},- {"name":"resources_updateMaintenanceDispatch","classification":"WRITE","paramCount":18,"schema":"02877e9f1f8d","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},- {"name":"resources_updateSuggestionEmoji","classification":"WRITE","paramCount":2,"schema":"dc61bce0f764","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},- {"name":"resources_updateTrainingQuestionOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false,"result":"envelopes"},- {"name":"resources_upsertContractor","classification":"DESTRUCTIVE","paramCount":1,"schema":"6630f8761e37","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"contractor(id)"},- {"name":"resources_upsertEmployeeAbilityCell","classification":"WRITE","paramCount":4,"schema":"800b78f5bbae","response":"3797626bd17e","injectAuth":"companyId","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertFailureMode","classification":"WRITE","paramCount":4,"schema":"e4d170d8f468","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertLocation","classification":"WRITE","paramCount":13,"schema":"5771361986b6","response":"99dfd44b4c2e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertMaintenanceDispatchComment","classification":"WRITE","paramCount":3,"schema":"15129a94d57d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertMaintenanceDispatchEvent","classification":"WRITE","paramCount":7,"schema":"a98569352969","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertMaintenanceDispatchItem","classification":"WRITE","paramCount":6,"schema":"41c857266e1d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertMaintenanceSchedule","classification":"WRITE","paramCount":20,"schema":"f0980197b765","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertPartner","classification":"WRITE","paramCount":3,"schema":"bcf9a7c682d9","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"partner(id)"},- {"name":"resources_upsertProcess","classification":"DESTRUCTIVE","paramCount":17,"schema":"bfa604f1eeb7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id","defaults":"create"},- {"name":"resources_upsertTraining","classification":"WRITE","paramCount":4,"schema":"385fb9c5d8d1","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertTrainingAssignment","classification":"WRITE","paramCount":4,"schema":"33b78ee5baf0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},- {"name":"resources_upsertTrainingQuestion","classification":"WRITE","paramCount":12,"schema":"1c336cac9dc8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertWorkCenter","classification":"DESTRUCTIVE","paramCount":15,"schema":"cbbc99da1ba7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"sales_buildMakeToOrderPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"10ba10c1ac60","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_buildPullFromInventoryPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"10ba10c1ac60","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_buildPurchaseToOrderPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"10ba10c1ac60","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_calculatePricesForQuantities","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_cancelSalesOrder","classification":"WRITE","paramCount":2,"schema":"745d2b9e6ebc","response":"903bb804a4ff","injectAuth":"companyId+userId","permission":"sales:update","paginates":false,"result":"flag"},- {"name":"sales_cancelSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},- {"name":"sales_confirmSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_convertQuoteToOrder","classification":"WRITE","paramCount":5,"schema":"fc53803a89ca","response":"ec9aaaf82857","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},- {"name":"sales_convertSalesRfqToQuote","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"ec9aaaf82857","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},- {"name":"sales_copyQuote","classification":"WRITE","paramCount":2,"schema":"174cbee1fad4","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},- {"name":"sales_copyQuoteLine","classification":"WRITE","paramCount":9,"schema":"692ceb74fe3d","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},- {"name":"sales_createOpportunityDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"45722937a7bb","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_createOpportunityLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_createPricingRule","classification":"WRITE","paramCount":17,"schema":"8a6a210cb492","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false,"defaults":"always"},- {"name":"sales_createReplacementSalesOrder","classification":"WRITE","paramCount":1,"schema":"f41daa12b05a","response":"3797626bd17e","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},- {"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"b73e7908d9de","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"invoicing:create","paginates":false},- {"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","paramCount":1,"schema":"09e48c79fb16","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerBankAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},- {"name":"sales_deleteCustomerContact","classification":"DESTRUCTIVE","paramCount":2,"schema":"3fd22b0165d4","response":"700b93baa3ef","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerItemPriceOverride","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerItemRentalRate","classification":"DESTRUCTIVE","paramCount":1,"schema":"ee5e30c7b358","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerLocation","classification":"DESTRUCTIVE","paramCount":2,"schema":"1786ebad8e35","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerStatus","classification":"DESTRUCTIVE","paramCount":1,"schema":"d9fee396ed8f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteCustomerType","classification":"DESTRUCTIVE","paramCount":1,"schema":"b79bc02c5595","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteNoQuoteReason","classification":"DESTRUCTIVE","paramCount":1,"schema":"a37352ef51ef","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deletePricingRule","classification":"DESTRUCTIVE","paramCount":1,"schema":"360072ef68fd","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteQuote","classification":"DESTRUCTIVE","paramCount":1,"schema":"c726ae407913","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteQuoteLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"e0050938a2c8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteQuoteMaterial","classification":"DESTRUCTIVE","paramCount":1,"schema":"5718812a5810","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteQuoteOperationParameter","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteQuoteOperationStep","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteQuoteOperationTool","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteRentalAgreement","classification":"DESTRUCTIVE","paramCount":1,"schema":"ac265594426e","response":"3797626bd17e","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteRentalAgreementCharge","classification":"DESTRUCTIVE","paramCount":1,"schema":"42fbbc48ae45","response":"3797626bd17e","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteRentalAgreementLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"9729319c460e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteReturnReason","classification":"DESTRUCTIVE","paramCount":1,"schema":"937e7a95a060","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesOrder","classification":"DESTRUCTIVE","paramCount":1,"schema":"d160a49d6787","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesOrderLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"58e3c9762923","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesReturnOrder","classification":"DESTRUCTIVE","paramCount":1,"schema":"f41daa12b05a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesReturnOrderLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"063a6777d378","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesRFQ","classification":"DESTRUCTIVE","paramCount":1,"schema":"1f7e47a99145","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_deleteSalesRFQLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"8b2f2f9d8451","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},- {"name":"sales_duplicatePricingRule","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_finalizeQuote","classification":"WRITE","paramCount":1,"schema":"c726ae407913","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_getAllCustomersItemPriceOverride","classification":"READ","paramCount":3,"schema":"746e975d6c8f","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getBaseCatalog","classification":"READ","paramCount":3,"schema":"b00172859bab","response":"7da40016b67c","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getConfigurationParametersByQuoteLineId","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"c36ad21b447b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContract","classification":"READ","paramCount":1,"schema":"a18bd6ac2fe5","response":"61ce667abaa8","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContractAmendments","classification":"READ","paramCount":1,"schema":"a18bd6ac2fe5","response":"d9f1b6608c99","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContractInvoiceSchedule","classification":"READ","paramCount":1,"schema":"a18bd6ac2fe5","response":"194d22065482","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContractLine","classification":"READ","paramCount":1,"schema":"3d08011d330a","response":"557e5390f61f","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContractLines","classification":"READ","paramCount":1,"schema":"a18bd6ac2fe5","response":"69f1c97ee590","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getContracts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"fc8b89e1366e","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCreditableQuantities","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"da2f02c5bdac","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomer","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"8642159293c2","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerBankAccounts","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"d8173b9c2e54","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"sales_getCustomerContact","classification":"READ","paramCount":1,"schema":"ad038ec2602b","response":"d16ba475ee9a","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerContacts","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"acc29dbe9746","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerContractStatuses","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"b4542ed3da5e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerItemPriceOverride","classification":"READ","paramCount":4,"schema":"3f17d1d3bb22","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerItemPriceOverrideById","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerItemPriceOverridesList","classification":"READ","paramCount":6,"schema":"1e549e10e0a2","response":"bae32978787b","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCustomerItemRentalRate","classification":"READ","paramCount":1,"schema":"ee5e30c7b358","response":"b3b8ce0eaba0","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerItemRentalRates","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"8b9441c41a32","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerLocation","classification":"READ","paramCount":1,"schema":"339ac15c3167","response":"be52ec9b4436","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerLocations","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"bcf222d6d73a","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerPayment","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"4357e4e42177","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"07fbe06b66b8","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCustomerShipping","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"68f579c7eb78","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerStatus","classification":"READ","paramCount":1,"schema":"d9fee396ed8f","response":"9203566a8ab4","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerStatuses","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"a5e736373756","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCustomerStatusesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerTax","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"35cfe732826b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerType","classification":"READ","paramCount":1,"schema":"b79bc02c5595","response":"8b3eca34dbfd","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerTypeItemPriceOverride","classification":"READ","paramCount":4,"schema":"e4596e241f82","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getCustomerTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7c6550dea5b1","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getCustomerTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getDefaultRentalRates","classification":"READ","paramCount":4,"schema":"9ccf2aa2b622","response":"c30d2e6a59d6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getExternalSalesOrderLines","classification":"READ","paramCount":2,"schema":"ddc644088147","response":"93fb8fa8e058","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getItemRentalRate","classification":"READ","paramCount":2,"schema":"fdb1e4807b11","response":"d1badca592c6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getModelByQuoteLineId","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"none","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getNoQuoteReason","classification":"READ","paramCount":1,"schema":"a37352ef51ef","response":"4bbb50609deb","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getNoQuoteReasons","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"28837d034643","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getNoQuoteReasonsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOnRentLineForAsset","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"3d1ddb71d505","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpenSalesOrderLinesForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"2c3da47e06b1","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpportunity","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"b203af1d4a1e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpportunityDocuments","classification":"READ","paramCount":1,"schema":"a4fcfa20a027","response":"95c1c04c0566","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpportunityLineDocuments","classification":"READ","paramCount":2,"schema":"067400ea63f8","response":"95c1c04c0566","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getPricingRule","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"2a1e20313f8b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getPricingRules","classification":"READ","paramCount":3,"schema":"b00172859bab","response":"f3613d31804a","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getQuote","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"bf6f646d5145","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteAssemblies","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"9807da529af1","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteAssembliesByLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"9807da529af1","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteByExternalId","classification":"READ","paramCount":1,"schema":"21801463053a","response":"960e90f367ef","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteCustomerDetails","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"7656953707c3","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"2e0476c17730","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePrices","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"b380070f2ac3","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePricesByItemId","classification":"READ","paramCount":2,"schema":"17311e00ca6f","response":"2d479ad29d1f","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePricesByItemIds","classification":"READ","paramCount":2,"schema":"64b602e1a6e4","response":"2d479ad29d1f","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePricesByQuoteId","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"b380070f2ac3","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinePriceTraces","classification":"READ","paramCount":2,"schema":"55ee981d3d94","response":"898c52004ae5","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLines","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"31ca07c6139c","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteLinesList","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"5ebff9af923d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMakeMethod","classification":"READ","paramCount":1,"schema":"899e2f637661","response":"9bc4f5e58344","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterial","classification":"READ","paramCount":1,"schema":"5aa329400da2","response":"1600eb794a06","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterials","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"98a32a315556","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterialsByLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"98a32a315556","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterialsByMethodId","classification":"READ","paramCount":1,"schema":"899e2f637661","response":"d8257d5ecd6b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMaterialsByOperation","classification":"READ","paramCount":1,"schema":"9d2e26473601","response":"98a32a315556","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMethodTreeArray","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"37f28086fadc","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteMethodTrees","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"5cf44f338f23","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteOperation","classification":"READ","paramCount":1,"schema":"9d2e26473601","response":"cc467608e48d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteOperations","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"9e17db1d5582","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteOperationsByLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"9e17db1d5582","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuoteOperationsByMethodId","classification":"READ","paramCount":1,"schema":"899e2f637661","response":"0ee46500fe67","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuotePayment","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"c94b5d1f2b47","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuotes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ef1a8a2074f8","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getQuoteShipment","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"ee2ac29cff92","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getQuotesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0ff25946068c","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRelatedPricesForQuoteLine","classification":"READ","paramCount":2,"schema":"71f31780bb98","response":"935691b285a7","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentableFleetAssets","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"18707409983d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreement","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"2ab46243420d","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementCharges","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"49b56d3a2f77","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementDeposits","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"d1712908bacb","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementLine","classification":"READ","paramCount":1,"schema":"9729319c460e","response":"241639dc09ac","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementLines","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"3ed7f3538cc6","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreementRelatedDocuments","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"e6faf3cc340a","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRentalAgreements","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"b02eb9e8bf70","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getRentalBillingPeriods","classification":"READ","paramCount":1,"schema":"ac265594426e","response":"10915ab32ad5","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getReturnableLinesForCustomer","classification":"READ","paramCount":2,"schema":"e9ef772b4706","response":"8b3d2e7917fd","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getReturnReason","classification":"READ","paramCount":1,"schema":"937e7a95a060","response":"784c9ecc581f","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getReturnReasons","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"1367348aaf16","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getReturnReasonsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"152e0efd7e28","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getRootQuoteMakeMethod","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"9bc4f5e58344","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesDocumentsAssignedToMe","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"74270bb8ea95","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrder","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"c95639a37a20","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderCustomerDetails","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"141326b70f84","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderCustomers","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fc7a0345fc53","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderInvoiceLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"1ff852ae9154","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderInvoicePaymentsByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"397cd2bf218b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"cd5bcdc964de","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"5bd9ba5f7ba2","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLinesByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLinesByItemIds","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"64e0b7280c5e","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderLineShipments","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"2414f4b5bcaf","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderPayment","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"e52a6a8beddf","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderRelatedItems","classification":"READ","paramCount":2,"schema":"651e9f51b36d","response":"de3f79e02cdb","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrders","classification":"READ","paramCount":5,"schema":"ef4d06fef47e","response":"f397c1f3b176","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getSalesOrdersByIds","classification":"READ","paramCount":1,"schema":"0eb0c2be01ed","response":"5cc20a44d4fe","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrderShipment","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"0f0a39ddefae","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesOrdersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"5cc20a44d4fe","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrder","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"a2cca2d13294","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderCredits","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"49639d091139","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderIssues","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"7cc200ea4b26","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"06aa29fc6b50","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderLines","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"580ee4dec9d4","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderLineTrackedEntities","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"71f9ff6abcae","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrderReceipts","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"71de851646a8","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesReturnOrders","classification":"READ","paramCount":5,"schema":"ef4d06fef47e","response":"31090a014afa","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getSalesRFQ","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"be949b1d682b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesRFQLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"a53064f9e7fe","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesRFQLines","classification":"READ","paramCount":1,"schema":"1f7e47a99145","response":"17f5b7f57e4c","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getSalesRFQs","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"cb436531316b","injectAuth":"companyId","permission":"sales:view","paginates":true,"defaults":"always"},- {"name":"sales_getSalesTerms","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"9819ae68df9b","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getShippedTrackedEntitiesForCustomer","classification":"READ","paramCount":2,"schema":"03d6f7a5e605","response":"1eabdd9a5634","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_insertContract","classification":"WRITE","paramCount":29,"schema":"2ce74f76bcb5","response":"b0da0d6d41c1","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertCustomerContact","classification":"WRITE","paramCount":4,"schema":"c5775e935035","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertCustomerLocation","classification":"WRITE","paramCount":4,"schema":"c30fcaea26e0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertQuote","classification":"WRITE","paramCount":16,"schema":"a6c40455c9f1","response":"9e29b49e1dc8","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertRentalAgreement","classification":"WRITE","paramCount":22,"schema":"1ba69424695e","response":"83a132e7dfec","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertSalesOrder","classification":"WRITE","paramCount":17,"schema":"b76b79d52d88","response":"dbfc22813350","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertSalesReturnOrder","classification":"WRITE","paramCount":12,"schema":"307356313ba5","response":"c32485518acd","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_insertSalesRFQ","classification":"WRITE","paramCount":13,"schema":"5a54a12e500f","response":"0c1a1b93cca3","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_recalculateQuoteLinePrices","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"bef3efeea4ce","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_releaseSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_reopenSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},- {"name":"sales_repriceQuoteLineFromRules","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_resolvePrice","classification":"WRITE","paramCount":1,"schema":"e21d9e9b3005","response":"eb12029769da","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_resolvePriceList","classification":"WRITE","paramCount":6,"schema":"aa4cc3b4c9e6","response":"7da40016b67c","injectAuth":"companyId","permission":"sales:update","paginates":true,"defaults":"always"},- {"name":"sales_resolvePurchaseToOrderPrices","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_resolveQuoteLinePrices","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update","paginates":false},- {"name":"sales_setSalesReturnOrderLineDisposition","classification":"WRITE","paramCount":2,"schema":"a8526e566c94","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},- {"name":"sales_shortCloseSalesReturnOrderLine","classification":"WRITE","paramCount":3,"schema":"a3098b18fc68","response":"none","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},- {"name":"sales_updateContract","classification":"WRITE","paramCount":29,"schema":"2d479c6cdf33","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateContractNotes","classification":"WRITE","paramCount":2,"schema":"2ab51d0b91d5","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateContractType","classification":"WRITE","paramCount":2,"schema":"9a1390515c73","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateCustomerContact","classification":"WRITE","paramCount":4,"schema":"f0fc7be0eef2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateCustomerLocation","classification":"WRITE","paramCount":4,"schema":"9d205b68ee4f","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateCustomerPayment","classification":"WRITE","paramCount":5,"schema":"f4b0bf1f4ec1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateCustomerShipping","classification":"WRITE","paramCount":7,"schema":"1c4be8a465fb","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateCustomerTax","classification":"WRITE","paramCount":8,"schema":"adc033566bc5","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updatePricingRule","classification":"WRITE","paramCount":2,"schema":"d8ff12f7ca7a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuote","classification":"WRITE","paramCount":17,"schema":"ad5fc3f2a158","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteLineOrder","classification":"WRITE","paramCount":2,"schema":"fce9a5d72ad3","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteLinePrecision","classification":"WRITE","paramCount":3,"schema":"90f52ec96806","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false,"result":"envelopes"},- {"name":"sales_updateQuoteOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false,"result":"envelopes"},- {"name":"sales_updateQuoteStatus","classification":"WRITE","paramCount":3,"schema":"db2529b2f9b5","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateRentalAgreement","classification":"WRITE","paramCount":22,"schema":"ffc475da95c4","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateRentalAgreementInvoiceAutomation","classification":"WRITE","paramCount":2,"schema":"321dd5c5e689","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesOrder","classification":"WRITE","paramCount":9,"schema":"d9b815fe7f4c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","paramCount":2,"schema":"fc73ab432ad8","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesOrderStatus","classification":"WRITE","paramCount":3,"schema":"4d2e908ca09f","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesRFQLineOrder","classification":"WRITE","paramCount":2,"schema":"7a17ee77c8c5","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesRFQStatus","classification":"WRITE","paramCount":4,"schema":"edf30d1c08da","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_upsertContractLine","classification":"WRITE","paramCount":18,"schema":"7a649c12168f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertCustomer","classification":"WRITE","paramCount":11,"schema":"27fc0d9d8eb0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertCustomerBankAccount","classification":"WRITE","paramCount":13,"schema":"71b1f32160c0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertCustomerItemPriceOverride","classification":"DESTRUCTIVE","paramCount":10,"schema":"6f67d6ad287a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertCustomerItemRentalRate","classification":"WRITE","paramCount":11,"schema":"d9f007b1b5e5","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertCustomerStatus","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertCustomerType","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertItemRentalRate","classification":"WRITE","paramCount":5,"schema":"f4cb0467e3dc","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertMakeMethodFromQuoteLine","classification":"WRITE","paramCount":4,"schema":"ca78a9869ff2","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertMakeMethodFromQuoteMethod","classification":"WRITE","paramCount":3,"schema":"32b3a0f5efa0","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertNoQuoteReason","classification":"WRITE","paramCount":3,"schema":"fbdc294966b9","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertQuote","classification":"WRITE","paramCount":21,"schema":"0c5ee8c52242","response":"3acbb53b8c04","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertQuoteLine","classification":"WRITE","paramCount":19,"schema":"0418d6bec04a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertQuoteLineAdditionalCharges","classification":"WRITE","paramCount":2,"schema":"af3d9c81e1c3","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteLineMethod","classification":"WRITE","paramCount":5,"schema":"5f94e8a4cbf6","response":"4e1a8f1febce","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteLinePrices","classification":"DESTRUCTIVE","paramCount":3,"schema":"03bc74906afb","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteMaterial","classification":"WRITE","paramCount":17,"schema":"ab28a6a008f4","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"quoteMaterial(id)"},- {"name":"sales_upsertQuoteMaterialMakeMethod","classification":"WRITE","paramCount":4,"schema":"06f97e90fc79","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteOperation","classification":"WRITE","paramCount":27,"schema":"4fa5726841a8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"quoteOperation(id)"},- {"name":"sales_upsertQuoteOperationParameter","classification":"WRITE","paramCount":5,"schema":"e9784c2bfbc3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertQuoteOperationStep","classification":"WRITE","paramCount":11,"schema":"78721aa4be26","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertQuoteOperationTool","classification":"WRITE","paramCount":5,"schema":"59266e6a790e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertQuotePayment","classification":"WRITE","paramCount":6,"schema":"36ca53e35fa3","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertQuoteShipment","classification":"WRITE","paramCount":7,"schema":"b67f297e5398","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertRentalAgreementCharge","classification":"WRITE","paramCount":7,"schema":"a914e37d74f4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertRentalAgreementLine","classification":"WRITE","paramCount":9,"schema":"cb7e4d4579e2","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertReturnReason","classification":"WRITE","paramCount":4,"schema":"85bdd818fbab","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertSalesOrder","classification":"WRITE","paramCount":19,"schema":"9d987dd63daf","response":"5cc20a44d4fe","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertSalesOrderLine","classification":"WRITE","paramCount":27,"schema":"cf0093721ce3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertSalesOrderPayment","classification":"WRITE","paramCount":8,"schema":"310037cea6c3","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertSalesOrderShipment","classification":"WRITE","paramCount":17,"schema":"a1ab551afe2a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:create+update","paginates":false},- {"name":"sales_upsertSalesReturnOrderLine","classification":"WRITE","paramCount":12,"schema":"2715ff7be34d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertSalesRFQ","classification":"WRITE","paramCount":15,"schema":"d213ee469a92","response":"2e56e1180d37","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"sales_upsertSalesRFQLine","classification":"WRITE","paramCount":11,"schema":"f00afd5737b0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false,"upsert":"id"},- {"name":"settings_deleteDocumentSection","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:delete","paginates":false},- {"name":"settings_deleteItemSerialSequence","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:delete","paginates":false},- {"name":"settings_getAccountsPayableBillingAddress","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7c0b9dc6d441","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getAccountsReceivableBillingAddress","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7c0b9dc6d441","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getApiKeys","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"eec810be5b96","injectAuth":"companyId","permission":"users:update","paginates":true,"defaults":"always"},- {"name":"settings_getCompanies","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"207f0b849926","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompany","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"81a93f0029ec","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompanyIntegrations","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3a98b34db51d","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompanyPlan","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"none","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompanySettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"592dc0578df9","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getConfig","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"aa1021ff34cf","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCurrentSequence","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"00404e686415","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCustomField","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a533a796c094","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCustomFields","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"4dd4a7dca597","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCustomFieldsTables","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"4d68a1d346ce","injectAuth":"companyId","permission":"settings:view","paginates":true,"defaults":"always"},- {"name":"settings_getDocumentSection","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"955f14940530","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentSections","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"d8b65982e0d9","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentSectionsByIds","classification":"READ","paramCount":1,"schema":"0eb0c2be01ed","response":"d8b65982e0d9","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentTemplate","classification":"READ","paramCount":1,"schema":"66ed1f5ba422","response":"99cae633d7cb","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getDocumentTemplateConfig","classification":"READ","paramCount":1,"schema":"66ed1f5ba422","response":"b6618b8c597f","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getEmployeeCompanies","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"207f0b849926","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getIndustries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"5dcce0f224dd","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getIntegration","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"099545249106","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getIntegrations","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"66d5dad6d7fc","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getItemSerialSequence","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"16afb36e5f82","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getItemSerialSequenceByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"1a875b64a77f","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getItemSerialSequences","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"ef60889e0cf5","injectAuth":"companyId","permission":"settings:view","paginates":true,"defaults":"always"},- {"name":"settings_getKanbanOutputSetting","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ca53dc098fc8","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getNextSequence","classification":"WRITE","paramCount":1,"schema":"f55836d6d401","response":"00404e686415","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_getPlanById","classification":"READ","paramCount":1,"schema":"a77c6a03353f","response":"none","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getPlans","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"5483e69d7515","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getSequence","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"ef17e2453ded","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getSequences","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"395e5a595aba","injectAuth":"companyId","permission":"settings:view","paginates":true,"defaults":"always"},- {"name":"settings_getSequencesList","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"8394fbabd845","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getSubsidiaries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"577bb278c46e","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getSubsidiary","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ac5d56a91ae0","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getTerms","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"deb82bb77180","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getWebhook","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"cb2b17a3252e","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getWebhooks","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"f236afae1a37","injectAuth":"companyId","permission":"settings:view","paginates":true,"defaults":"always"},- {"name":"settings_getWebhookTables","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"633f9f3bffc6","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_resolveSections","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"59781d2a00b3","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateAccountsPayableAddressSetting","classification":"WRITE","paramCount":1,"schema":"7a679bb0d746","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateAccountsPayableBillingAddress","classification":"WRITE","paramCount":10,"schema":"1d9ef8425567","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false,"context":"updatedBy=userId"},- {"name":"settings_updateAccountsReceivableAddressSetting","classification":"WRITE","paramCount":1,"schema":"aee1361e5321","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateAccountsReceivableBillingAddress","classification":"WRITE","paramCount":10,"schema":"1d9ef8425567","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false,"context":"updatedBy=userId"},- {"name":"settings_updateAllowLowercaseItemIdsSetting","classification":"WRITE","paramCount":1,"schema":"4bfa8b2e5538","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateAssetTaxDepreciationSettings","classification":"WRITE","paramCount":2,"schema":"6decaad55e9c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateAutoSelectMaterialWithoutPickingListSetting","classification":"WRITE","paramCount":1,"schema":"c8c780d1ee3a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateBomExplorerReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"f58f54c509a0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateCompany","classification":"WRITE","paramCount":17,"schema":"51b47fb4a6bd","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateCompanyWithBaseCurrencyChange","classification":"DESTRUCTIVE","paramCount":17,"schema":"51b47fb4a6bd","response":"none","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateDefaultCustomerCc","classification":"WRITE","paramCount":1,"schema":"69d7696df422","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateDefaultSupplierCc","classification":"WRITE","paramCount":1,"schema":"862b3d182ce1","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateDigitalQuoteSetting","classification":"WRITE","paramCount":3,"schema":"01dcd07bf6d9","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateIncludeMaterialsOnTravelerSetting","classification":"WRITE","paramCount":1,"schema":"c44d043f2507","response":"none","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateIncludeOperationsOnTravelerSetting","classification":"WRITE","paramCount":1,"schema":"dcfff3bec454","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateIncompletePickingListPolicySetting","classification":"WRITE","paramCount":1,"schema":"0f134dc7536d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateInvoiceAutomationSetting","classification":"WRITE","paramCount":1,"schema":"58ff6b5b2f88","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateInvoiceNotificationSetting","classification":"WRITE","paramCount":1,"schema":"e1f0172b7519","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateKanbanOutputSetting","classification":"WRITE","paramCount":1,"schema":"ca53dc098fc8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateLeadTimesOnReceiptSetting","classification":"WRITE","paramCount":1,"schema":"95c137844a39","response":"none","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateLeasePolicySettings","classification":"WRITE","paramCount":6,"schema":"73eeba3e8660","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateLogoDark","classification":"WRITE","paramCount":1,"schema":"f2a952625b72","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateLogoDarkIcon","classification":"WRITE","paramCount":1,"schema":"cc8cf36714fa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateLogoLight","classification":"WRITE","paramCount":1,"schema":"9baa1881adb6","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateLogoLightIcon","classification":"WRITE","paramCount":1,"schema":"17c809b3aebf","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateLogoWatermark","classification":"WRITE","paramCount":1,"schema":"22e7a3b83c3a","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateMaintenanceDispatchNotificationSettings","classification":"WRITE","paramCount":4,"schema":"c857a8ae87fd","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateMaterialGeneratedIdsSetting","classification":"WRITE","paramCount":1,"schema":"8de91cc6fb4f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateMetricSettings","classification":"WRITE","paramCount":1,"schema":"6310a488e8b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateMrpRunTimeSetting","classification":"WRITE","paramCount":1,"schema":"7e0d8d6dda56","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updatePlmReleaseControlSetting","classification":"WRITE","paramCount":1,"schema":"b74d1adb972d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updatePurchasePriceUpdateTimingSetting","classification":"WRITE","paramCount":1,"schema":"6e01697e737c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateQuoteLineCategoryMarkups","classification":"WRITE","paramCount":1,"schema":"46b636ff84f8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateReceiptQuantitiesStartAtZeroSetting","classification":"WRITE","paramCount":1,"schema":"e7e5782aa8aa","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateRequireCustomerContactSetting","classification":"WRITE","paramCount":1,"schema":"4cff457269be","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateRequireSupplierContactSetting","classification":"WRITE","paramCount":1,"schema":"36a0cd98c43c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateReturnPickedMaterialTimingSetting","classification":"WRITE","paramCount":1,"schema":"59acd7763b9c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateRfqReadySetting","classification":"WRITE","paramCount":1,"schema":"8828dbf1724d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateSalesRuleNotificationSetting","classification":"WRITE","paramCount":1,"schema":"fcb0888da832","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateSequence","classification":"WRITE","paramCount":2,"schema":"c28f12fe484d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateShelfLifeSettings","classification":"WRITE","paramCount":4,"schema":"64b05764105a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateShowCurrencyTrailingZerosSetting","classification":"WRITE","paramCount":1,"schema":"42d586011b23","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateShowCustomerReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"8b384c0bd6a0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateShowSupplierReadableIdSetting","classification":"WRITE","paramCount":1,"schema":"e28a3e070640","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateSubsidiary","classification":"WRITE","paramCount":2,"schema":"7827cc68ef29","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateSuggestionNotificationSetting","classification":"WRITE","paramCount":1,"schema":"ac461e36d464","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update","paginates":false},- {"name":"settings_updateSupplierQuoteNotificationSetting","classification":"WRITE","paramCount":1,"schema":"56a6d061d358","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_updateTimeCardSetting","classification":"WRITE","paramCount":1,"schema":"9389085b800b","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},- {"name":"settings_upsertDocumentSection","classification":"WRITE","paramCount":5,"schema":"68db6a083683","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false,"upsert":"documentSection(id)"},- {"name":"settings_upsertDocumentTemplate","classification":"WRITE","paramCount":6,"schema":"46782204d1c1","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false},- {"name":"settings_upsertItemSerialSequence","classification":"WRITE","paramCount":7,"schema":"ddbb6ec42577","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"settings:create+update","paginates":false,"upsert":"id"},- {"name":"shared_deleteSavedView","classification":"DESTRUCTIVE","paramCount":1,"schema":"1fbe3d41dab0","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getBase64ImageFromSupabase","classification":"READ","paramCount":1,"schema":"923b083c9bca","response":"174e29b899b9","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getCountries","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0e8a11b4e81c","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getCustomerPortal","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getCustomerPortals","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"fbffc4ca5fac","injectAuth":"companyId","permission":"none","paginates":true,"defaults":"always"},- {"name":"shared_getEnforcementRule","classification":"READ","paramCount":2,"schema":"fa9ceafd871f","response":"55286a46f24b","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getEnforcementRuleAssignmentCounts","classification":"READ","paramCount":1,"schema":"47af2b550d52","response":"ab5d5774b961","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getEnforcementRules","classification":"READ","paramCount":2,"schema":"f7fab064142e","response":"a58a59f02a18","injectAuth":"companyId","permission":"none","paginates":true,"defaults":"always"},- {"name":"shared_getExternalLink","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"0f7860db4299","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getModelByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"none","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getNotes","classification":"READ","paramCount":1,"schema":"e7617eb689c8","response":"1a052a4417b5","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getPeriods","classification":"READ","paramCount":2,"schema":"265827be4a3e","response":"e635c6c77f6d","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getSavedViews","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"be2b0aada3eb","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getTagsList","classification":"READ","paramCount":1,"schema":"43c92414cb2f","response":"b837740e18f4","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_getTimezoneNames","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"93968ed2dcdb","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_importCsv","classification":"WRITE","paramCount":4,"schema":"8f2d77f74ffb","response":"fe3f36b94f53","injectAuth":"companyId+userId","permission":"none","paginates":false},- {"name":"shared_insertNote","classification":"WRITE","paramCount":2,"schema":"260839f76e18","response":"c2fb0e5225f8","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},- {"name":"shared_insertTag","classification":"WRITE","paramCount":1,"schema":"11926edb131b","response":"27f67ae1958c","injectAuth":"companyId+createdBy+updatedBy","permission":"none","paginates":false},- {"name":"shared_lookupBuyPriceFromMap","classification":"READ","paramCount":4,"schema":"4360b71230e3","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_lookupPriceFromBreaks","classification":"READ","paramCount":3,"schema":"14f107043636","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_resolveBuyUnitCost","classification":"WRITE","paramCount":3,"schema":"4c58915f44dd","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_resolveSupplierPrice","classification":"READ","paramCount":4,"schema":"cb376986b1ab","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_updateSavedViewOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"none","paginates":false,"result":"envelopes"},- {"name":"shared_upsertExternalLink","classification":"WRITE","paramCount":1,"schema":"33e54e07795a","response":"3797626bd17e","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_upsertSavedView","classification":"WRITE","paramCount":10,"schema":"88a0b7dfec62","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"none","paginates":false},- {"name":"users_deleteGroup","classification":"DESTRUCTIVE","paramCount":1,"schema":"c4dcdfdf8647","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:delete","paginates":false},- {"name":"users_getCompaniesForUser","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"681004346c78","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getConsoleOperators","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"42c3353a5284","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getCustomers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"79cad34eb92a","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getEmployee","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"fddbdf17260d","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getEmployees","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"42c3353a5284","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getEmployeeType","classification":"READ","paramCount":1,"schema":"dba2936b2a4e","response":"02c4f766f388","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getEmployeeTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"2851c6c5b230","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getGroup","classification":"READ","paramCount":1,"schema":"c4dcdfdf8647","response":"f06d2d858884","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getGroupEmails","classification":"READ","paramCount":1,"schema":"ab09ef9264af","response":"681004346c78","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getGroupMembers","classification":"READ","paramCount":1,"schema":"c4dcdfdf8647","response":"f218e882144b","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getGroups","classification":"READ","paramCount":4,"schema":"f382292e4c25","response":"878696d68be4","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getInvitable","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3173c3a99146","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getItarCertificationReport","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"203ea6eb1a16","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getItarCertificationStatus","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"6afd62a22e82","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getItarEntityCertification","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c5ae95ca48db","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getModules","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3f7ca035e170","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getPermissionsByEmployeeType","classification":"READ","paramCount":1,"schema":"dba2936b2a4e","response":"9b77a39f3bec","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getSuppliers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"c096e3fa1fac","injectAuth":"companyId","permission":"users:view","paginates":true,"defaults":"always"},- {"name":"users_getUnrevokedInviteEmails","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a6b0124b4410","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getUserEmails","classification":"READ","paramCount":1,"schema":"e0b0d488de80","response":"681004346c78","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getUsers","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e2e6268ff023","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getUserSelectGroupMembers","classification":"READ","paramCount":1,"schema":"c4dcdfdf8647","response":"b754519017cb","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getUserSelectGroups","classification":"READ","paramCount":4,"schema":"b459d00208b5","response":"51b54791b40a","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_getUsersWithVerifiedMfa","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"4c1fdc714231","injectAuth":"companyId","permission":"users:view","paginates":false},- {"name":"users_insertGroup","classification":"WRITE","paramCount":1,"schema":"098974972159","response":"06c8b45796ca","injectAuth":"companyId","permission":"users:create","paginates":false},- {"name":"users_resolveUserSelectIds","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"7fdfa4c9e77e","injectAuth":"companyId","permission":"users:update","paginates":false},- {"name":"users_searchUsersForSelect","classification":"READ","paramCount":4,"schema":"230b4891a4e5","response":"c9c1df9c3e28","injectAuth":"companyId+userId","permission":"users:view","paginates":false},- {"name":"users_upsertGroup","classification":"WRITE","paramCount":2,"schema":"f06d2d858884","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:create+update","paginates":false},- {"name":"users_upsertGroupMembers","classification":"DESTRUCTIVE","paramCount":2,"schema":"b32a69080685","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:create+update","paginates":false}+ {"name":"accounting_closePeriod","classification":"WRITE","schema":"7e5905ac5974","response":"7e5905ac5974","permission":"accounting:update","paginates":false},+ {"name":"accounting_closeTaskComplete","classification":"WRITE","schema":"5d2e9a90637b","response":"48f7f6d71e5b","permission":"accounting:update","paginates":false},+ {"name":"accounting_closeTaskSkip","classification":"WRITE","schema":"8d4ab2b60f5f","response":"d53c8b4f27a6","permission":"accounting:update","paginates":false},+ {"name":"accounting_createAccount","classification":"WRITE","schema":"17351d2a4ab5","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createCostCenter","classification":"WRITE","schema":"cdfac1ed1335","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createDepreciationRun","classification":"WRITE","schema":"9401c1cd4d61","response":"20eda0d52ae4","permission":"accounting:create","paginates":false},+ {"name":"accounting_createDimension","classification":"DESTRUCTIVE","schema":"9fe9f795f35e","response":"660c8bead643","permission":"accounting:create","paginates":false},+ {"name":"accounting_createFiscalYearPeriods","classification":"WRITE","schema":"96bc1e1d05f5","response":"none","permission":"accounting:create","paginates":false},+ {"name":"accounting_createFixedAssetClass","classification":"WRITE","schema":"8889fba12746","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createIntercompanyTransaction","classification":"WRITE","schema":"dc8b65b9e82b","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createJournalEntry","classification":"WRITE","schema":"31b84d65b2ac","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createPaymentTerm","classification":"WRITE","schema":"c8bd0bd44eb4","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createProject","classification":"WRITE","schema":"a20f9d5d11e5","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"accounting_createReportView","classification":"WRITE","schema":"4889a27f1969","response":"47a0e7255225","permission":"accounting:create","paginates":false},+ {"name":"accounting_createRevenueRecognitionRun","classification":"WRITE","schema":"a02c6a31de72","response":"8de1454829be","permission":"accounting:create","paginates":false},+ {"name":"accounting_createRunForPeriod","classification":"WRITE","schema":"28912dee175b","response":"1ce13dc8733f","permission":"accounting:create+update","paginates":false},+ {"name":"accounting_deleteAccount","classification":"DESTRUCTIVE","schema":"222849c8127a","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteAccountingPeriod","classification":"DESTRUCTIVE","schema":"5d9d38de5f83","response":"none","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteCostCenter","classification":"DESTRUCTIVE","schema":"478605fd0ab8","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteDepreciationRun","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteDimension","classification":"DESTRUCTIVE","schema":"b616d16ebae0","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteFixedAsset","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteFixedAssetClass","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteJournalEntry","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deletePaymentTerm","classification":"DESTRUCTIVE","schema":"e6ee32931e18","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteProject","classification":"DESTRUCTIVE","schema":"2f03472509a0","response":"3797626bd17e","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteReportView","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"accounting_deleteRevenueRecognitionRun","classification":"DESTRUCTIVE","schema":"8245d2d4cee4","response":"061737c09176","permission":"accounting:delete","paginates":false},+ {"name":"accounting_disposeFixedAsset","classification":"DESTRUCTIVE","schema":"3e2c8c66ce93","response":"91f483e6fee8","permission":"accounting:update","paginates":false},+ {"name":"accounting_generateEliminations","classification":"WRITE","schema":"27e39011ce14","response":"cddf8275afa1","permission":"accounting:create","paginates":false},+ {"name":"accounting_getAccount","classification":"READ","schema":"222849c8127a","response":"dc3cb968a42d","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountingPeriodDeletability","classification":"READ","schema":"5d9d38de5f83","response":"79634239b4bc","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountingPeriods","classification":"READ","schema":"31b84d65b2ac","response":"5de8ace458f4","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountingSyncTieOut","classification":"READ","schema":"640626a59ffa","response":"5483e69d7515","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountingSyncTieOutCell","classification":"READ","schema":"a520387e09b1","response":"a5febf12f4bd","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountLedger","classification":"READ","schema":"87322609d2e6","response":"ba2b28ce7bfa","permission":"accounting:view","paginates":true},+ {"name":"accounting_getAccountLedgerSummary","classification":"READ","schema":"758332a33a48","response":"0a28a92b28ff","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountsInScope","classification":"READ","schema":"cbb92564d684","response":"4c52cef1b6ab","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAccountsList","classification":"READ","schema":"8d4134f63d41","response":"814d9b75e8f1","permission":"accounting:view","paginates":false},+ {"name":"accounting_getActiveDimensionsWithValues","classification":"READ","schema":"31b84d65b2ac","response":"5dd5adb8dbbf","permission":"accounting:view","paginates":false},+ {"name":"accounting_getAssetDepreciationHistory","classification":"READ","schema":"61a61364de24","response":"00c2fc9fdb8b","permission":"accounting:view","paginates":false},+ {"name":"accounting_getBaseCurrency","classification":"READ","schema":"31b84d65b2ac","response":"11af3b92d80f","permission":"accounting:view","paginates":false},+ {"name":"accounting_getChartOfAccounts","classification":"READ","schema":"760cd5349e96","response":"bba294781cb0","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCompaniesInGroup","classification":"READ","schema":"31b84d65b2ac","response":"032bba337af7","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCostCenter","classification":"READ","schema":"478605fd0ab8","response":"f7b898d20847","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCostCentersList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCostCentersTree","classification":"READ","schema":"31b84d65b2ac","response":"b4505b9334e6","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCurrencies","classification":"READ","schema":"e2389bb135b5","response":"1d6055ff487c","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCurrenciesList","classification":"READ","schema":"31b84d65b2ac","response":"01628a6ebd21","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCurrency","classification":"READ","schema":"c5a03b3ef7c2","response":"6d5bae3dafd5","permission":"accounting:view","paginates":false},+ {"name":"accounting_getCurrencyByCode","classification":"READ","schema":"8775a38b3ca9","response":"300e136d14d0","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDefaultAccounts","classification":"READ","schema":"31b84d65b2ac","response":"8460f8427611","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDeferredRevenueWaterfall","classification":"READ","schema":"c26b9971346c","response":"b51e2e003282","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDepreciationRun","classification":"READ","schema":"7f8214d1083f","response":"22ccbb1556ab","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDepreciationRunLines","classification":"READ","schema":"f440962f839e","response":"9c31ce726755","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDepreciationRuns","classification":"READ","schema":"e2389bb135b5","response":"a5ca776abeec","permission":"accounting:view","paginates":true},+ {"name":"accounting_getDimension","classification":"READ","schema":"b616d16ebae0","response":"86872741fb27","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDimensionPivot","classification":"READ","schema":"5c152cd0e76b","response":"c7069f830357","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDimensionPivotLines","classification":"READ","schema":"9047d926f652","response":"100f0689af3e","permission":"accounting:view","paginates":false},+ {"name":"accounting_getDimensions","classification":"READ","schema":"e2389bb135b5","response":"ca259fd73665","permission":"accounting:view","paginates":true},+ {"name":"accounting_getExchangeRate","classification":"READ","schema":"8775a38b3ca9","response":"cddf8275afa1","permission":"accounting:view","paginates":false},+ {"name":"accounting_getExchangeRateHistory","classification":"READ","schema":"8775a38b3ca9","response":"ab784d246338","permission":"accounting:view","paginates":false},+ {"name":"accounting_getExchangeRates","classification":"READ","schema":"31b84d65b2ac","response":"7089bfe7df7a","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFinancialStatementBalances","classification":"READ","schema":"031a3bd9c34e","response":"bba294781cb0","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFinancialStatementPeriodSeries","classification":"READ","schema":"2fa2b0df3ab1","response":"5483e69d7515","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFiscalCalendarCommitted","classification":"READ","schema":"31b84d65b2ac","response":"854b90f7a9d3","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFiscalYearSettings","classification":"READ","schema":"31b84d65b2ac","response":"b9513b822ab3","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAsset","classification":"READ","schema":"7f8214d1083f","response":"cb32d8b6885b","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssetCipCosts","classification":"READ","schema":"61a61364de24","response":"03707172e0ba","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssetClass","classification":"READ","schema":"7f8214d1083f","response":"a74e56b11f76","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssetClasses","classification":"READ","schema":"e2389bb135b5","response":"458d93060a99","permission":"accounting:view","paginates":true},+ {"name":"accounting_getFixedAssetClassesList","classification":"READ","schema":"31b84d65b2ac","response":"626546da6867","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssetDisposal","classification":"READ","schema":"61a61364de24","response":"4b37a6513b87","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFixedAssets","classification":"READ","schema":"10b72218e720","response":"8a1d12afa935","permission":"accounting:view","paginates":true},+ {"name":"accounting_getFixedAssetTransfers","classification":"READ","schema":"61a61364de24","response":"42e9b68a4dcb","permission":"accounting:view","paginates":false},+ {"name":"accounting_getFleetAssets","classification":"READ","schema":"a172ea966a5a","response":"a1d2b71b7a6b","permission":"accounting:view","paginates":true},+ {"name":"accounting_getGroupAccounts","classification":"READ","schema":"31b84d65b2ac","response":"35cdc3cd0949","permission":"accounting:view","paginates":false},+ {"name":"accounting_getIntercompanyTransactions","classification":"READ","schema":"27005f872048","response":"37a244ba1bd0","permission":"accounting:view","paginates":true},+ {"name":"accounting_getJournalEntries","classification":"READ","schema":"88993a3b645a","response":"94203365d86c","permission":"accounting:view","paginates":true},+ {"name":"accounting_getJournalEntry","classification":"READ","schema":"7f8214d1083f","response":"37370aa756c4","permission":"accounting:view","paginates":false},+ {"name":"accounting_getJournalLineDimensions","classification":"READ","schema":"49b26fe1c26e","response":"b731368c1d3c","permission":"accounting:view","paginates":false},+ {"name":"accounting_getLeaseLiabilities","classification":"READ","schema":"bae0cdb5c2a5","response":"none","permission":"accounting:view","paginates":false},+ {"name":"accounting_getLeaseNetInvestment","classification":"READ","schema":"c26b9971346c","response":"8de1c4536c37","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPaymentTerm","classification":"READ","schema":"e6ee32931e18","response":"3cf7f3f31dc2","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPaymentTerms","classification":"READ","schema":"e2389bb135b5","response":"fb989e3bd774","permission":"accounting:view","paginates":true},+ {"name":"accounting_getPaymentTermsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPeriodCloseChecklist","classification":"WRITE","schema":"5d9d38de5f83","response":"6e4603e62d91","permission":"accounting:update","paginates":false},+ {"name":"accounting_getPeriodRunRelatedItems","classification":"READ","schema":"fc10f96fcd01","response":"523a70af9ece","permission":"accounting:view","paginates":false},+ {"name":"accounting_getProject","classification":"READ","schema":"2f03472509a0","response":"b9294ccc5a24","permission":"accounting:view","paginates":false},+ {"name":"accounting_getProjects","classification":"READ","schema":"e2389bb135b5","response":"22648003a5b3","permission":"accounting:view","paginates":true},+ {"name":"accounting_getPurchaseLinePivot","classification":"READ","schema":"1a8c8fa33252","response":"c7069f830357","permission":"accounting:view","paginates":false},+ {"name":"accounting_getPurchaseLinePivotLines","classification":"READ","schema":"e65393fd70a5","response":"a12b8efe2d62","permission":"accounting:view","paginates":false},+ {"name":"accounting_getRentalUtilization","classification":"READ","schema":"ed2c56398ce1","response":"80fa6e3c40ad","permission":"accounting:view","paginates":false},+ {"name":"accounting_getReportPins","classification":"READ","schema":"31b84d65b2ac","response":"3536c9c9a314","permission":"accounting:view","paginates":false},+ {"name":"accounting_getReportViews","classification":"READ","schema":"a7dc8d549b08","response":"67772a9f686d","permission":"accounting:view","paginates":false},+ {"name":"accounting_getRevenueRecognitionRun","classification":"READ","schema":"7f8214d1083f","response":"fb8cbba30867","permission":"accounting:view","paginates":false},+ {"name":"accounting_getRevenueRecognitionRunLines","classification":"READ","schema":"60d79fe0873e","response":"5622278817dc","permission":"accounting:view","paginates":false},+ {"name":"accounting_getScrapAccountIds","classification":"READ","schema":"31b84d65b2ac","response":"681004346c78","permission":"accounting:view","paginates":false},+ {"name":"accounting_getWorkCenterCapitalCost","classification":"READ","schema":"f1e2fb0e86e7","response":"8bd5c08050f0","permission":"accounting:view","paginates":false},+ {"name":"accounting_insertFixedAsset","classification":"WRITE","schema":"bc3b9496277a","response":"e0e9c463a967","permission":"accounting:create","paginates":false},+ {"name":"accounting_invokeAssetTransfer","classification":"WRITE","schema":"840df8cd1746","response":"c84f5bab4f4d","permission":"accounting:update","paginates":false},+ {"name":"accounting_lockPeriod","classification":"WRITE","schema":"7e5905ac5974","response":"225369d393b0","permission":"accounting:update","paginates":false},+ {"name":"accounting_moveAccount","classification":"WRITE","schema":"58f5301405fc","response":"ecb746f60913","permission":"accounting:update","paginates":false},+ {"name":"accounting_overrideExchangeRate","classification":"WRITE","schema":"4576f689f2fa","response":"4576f689f2fa","permission":"accounting:update","paginates":false},+ {"name":"accounting_postDepreciationRun","classification":"WRITE","schema":"e83946bf5ea7","response":"20eda0d52ae4","permission":"accounting:update","paginates":false},+ {"name":"accounting_postJournalEntry","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_postRevenueRecognitionRun","classification":"WRITE","schema":"8245d2d4cee4","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_purchaseFixedAsset","classification":"WRITE","schema":"0ef013992fdf","response":"28cffcd9d6e8","permission":"purchasing:create","paginates":false},+ {"name":"accounting_recalculateDepreciationRun","classification":"WRITE","schema":"e83946bf5ea7","response":"d325c86b5677","permission":"accounting:update","paginates":false},+ {"name":"accounting_recalculateRevenueRecognitionRun","classification":"WRITE","schema":"8245d2d4cee4","response":"1be43fc6832f","permission":"accounting:update","paginates":false},+ {"name":"accounting_registerFixedAsset","classification":"WRITE","schema":"ec5d79eeaeca","response":"91f483e6fee8","permission":"accounting:update","paginates":false},+ {"name":"accounting_repeatDepreciationRun","classification":"WRITE","schema":"e83946bf5ea7","response":"20eda0d52ae4","permission":"accounting:create","paginates":false},+ {"name":"accounting_repeatRevenueRecognitionRun","classification":"WRITE","schema":"8245d2d4cee4","response":"8de1454829be","permission":"accounting:create","paginates":false},+ {"name":"accounting_resetExchangeRate","classification":"DESTRUCTIVE","schema":"cc2bce783cc5","response":"cc2bce783cc5","permission":"accounting:update","paginates":false},+ {"name":"accounting_returnFixedAssetToService","classification":"WRITE","schema":"91f483e6fee8","response":"91f483e6fee8","permission":"accounting:update","paginates":false},+ {"name":"accounting_reverseDepreciationRun","classification":"DESTRUCTIVE","schema":"e83946bf5ea7","response":"20eda0d52ae4","permission":"accounting:update","paginates":false},+ {"name":"accounting_reverseJournalEntry","classification":"WRITE","schema":"399fe1b9a54f","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_reverseRevenueRecognitionRun","classification":"DESTRUCTIVE","schema":"8245d2d4cee4","response":"898100ba0a91","permission":"accounting:update","paginates":false},+ {"name":"accounting_runIntercompanyMatching","classification":"WRITE","schema":"31b84d65b2ac","response":"c07d47c6ac75","permission":"accounting:update","paginates":false},+ {"name":"accounting_saveJournalEntry","classification":"DESTRUCTIVE","schema":"dbc95bc1ed8a","response":"072fdafde3d3","permission":"accounting:update","paginates":false},+ {"name":"accounting_saveJournalLineDimensions","classification":"DESTRUCTIVE","schema":"7c44a0e2c058","response":"bcde375ebd4c","permission":"accounting:update","paginates":false},+ {"name":"accounting_sellFixedAsset","classification":"WRITE","schema":"120c7048d1d4","response":"d160a49d6787","permission":"sales:create","paginates":false},+ {"name":"accounting_takeFixedAssetOutOfService","classification":"WRITE","schema":"f83b81b1e0ba","response":"91f483e6fee8","permission":"accounting:update","paginates":false},+ {"name":"accounting_translateCompanyBalances","classification":"WRITE","schema":"3ee2ef8fce02","response":"be5b093fb6e6","permission":"accounting:update","paginates":false},+ {"name":"accounting_unlockPeriod","classification":"WRITE","schema":"7e5905ac5974","response":"be1ed439f12a","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateAccount","classification":"WRITE","schema":"413dd197d2e5","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateCostCenter","classification":"WRITE","schema":"8acc63c3be94","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateCurrency","classification":"WRITE","schema":"7f4f47859592","response":"0e98c276626d","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateDefaultAccounts","classification":"WRITE","schema":"7eafac321195","response":"bcde375ebd4c","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateDimension","classification":"DESTRUCTIVE","schema":"bc296a45be9e","response":"660c8bead643","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateFiscalYearSettings","classification":"WRITE","schema":"fb433e35b233","response":"bcde375ebd4c","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateFixedAsset","classification":"WRITE","schema":"7cf19679ef1c","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateFixedAssetClass","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updatePaymentTerm","classification":"WRITE","schema":"d72661dd36df","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateProject","classification":"WRITE","schema":"c6508c06eeb9","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"accounting_updateReportView","classification":"WRITE","schema":"1a8d77edd96c","response":"47a0e7255225","permission":"accounting:update","paginates":false},+ {"name":"accounting_upsertReportPin","classification":"WRITE","schema":"5451b17c4b2c","response":"bcde375ebd4c","permission":"accounting:create+update","paginates":false},+ {"name":"documents_createDocument","classification":"WRITE","schema":"6bdbd3c91adf","response":"1fd372019111","permission":"documents:create","paginates":false},+ {"name":"documents_createDocumentUploadUrl","classification":"WRITE","schema":"01e8421410da","response":"4ad76afe0777","permission":"documents:create","paginates":false},+ {"name":"documents_deleteDocument","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"documents:delete","paginates":false},+ {"name":"documents_getDocument","classification":"READ","schema":"1a362ab8a372","response":"985e02706d13","permission":"documents:view","paginates":false},+ {"name":"documents_getDocumentExtensions","classification":"READ","schema":"31b84d65b2ac","response":"a07a74ca3dd1","permission":"documents:view","paginates":false},+ {"name":"documents_getDocumentLabels","classification":"READ","schema":"31b84d65b2ac","response":"7e2eeb0066ab","permission":"documents:view","paginates":false},+ {"name":"documents_getDocuments","classification":"READ","schema":"ad54bc039c0f","response":"236702fe3f96","permission":"documents:view","paginates":true},+ {"name":"documents_insertDocumentExtraction","classification":"WRITE","schema":"2d09a729f243","response":"d181256b2684","permission":"documents:create","paginates":false},+ {"name":"documents_insertUploadedDocument","classification":"WRITE","schema":"593f625cc9b6","response":"1fd372019111","permission":"documents:create","paginates":false},+ {"name":"documents_moveDocumentToTrash","classification":"WRITE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"documents:update","paginates":false},+ {"name":"documents_restoreDocument","classification":"WRITE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"documents:update","paginates":false},+ {"name":"documents_updateDocument","classification":"WRITE","schema":"3b8acbaf3fa7","response":"1fd372019111","permission":"documents:update","paginates":false},+ {"name":"documents_updateDocumentFavorite","classification":"DESTRUCTIVE","schema":"ff73dc321969","response":"bcde375ebd4c","permission":"documents:update","paginates":false},+ {"name":"documents_updateDocumentLabels","classification":"DESTRUCTIVE","schema":"b97e2ad30e97","response":"bcde375ebd4c","permission":"documents:update","paginates":false},+ {"name":"inventory_adjustInventory","classification":"WRITE","schema":"6bea071798b4","response":"637aa3a8adf9","permission":"inventory:create+update","paginates":false},+ {"name":"inventory_assignReceiptReturnEntity","classification":"WRITE","schema":"82c3b94b252f","response":"5d58d420052a","permission":"inventory:create","paginates":false},+ {"name":"inventory_assignShipmentLineEntity","classification":"WRITE","schema":"ef225f89d1f1","response":"5d58d420052a","permission":"inventory:create","paginates":false},+ {"name":"inventory_correctStockMovement","classification":"WRITE","schema":"11e4a2d8d923","response":"baa524ddff70","permission":"inventory:update","paginates":false},+ {"name":"inventory_createInventoryCount","classification":"WRITE","schema":"2657c9ab7b5b","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createInventoryReconciliationJournal","classification":"WRITE","schema":"0f10306ad40d","response":"a9f23ceb9dc1","permission":"accounting:create","paginates":false},+ {"name":"inventory_createKanban","classification":"WRITE","schema":"9ab62082392e","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createReceipt","classification":"WRITE","schema":"12978f9841f2","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createShipment","classification":"WRITE","schema":"40665d54c304","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createShippingMethod","classification":"WRITE","schema":"35c841d658b9","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createStockTransfer","classification":"WRITE","schema":"d2eae4a05698","response":"8db339addf8f","permission":"inventory:create","paginates":false},+ {"name":"inventory_createStockTransferLine","classification":"WRITE","schema":"61a124703a26","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createStorageType","classification":"WRITE","schema":"dac43048240a","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"inventory_createStorageUnit","classification":"WRITE","schema":"8dc350e360ad","response":"3797626bd17e","permission":"inventory:create","paginates":false},+ {"name":"inventory_createWarehouseTransferLine","classification":"WRITE","schema":"1c4aec41902a","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_deleteBatchProperty","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteInventoryCount","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteKanban","classification":"DESTRUCTIVE","schema":"84ad7166f1d7","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deletePickingList","classification":"DESTRUCTIVE","schema":"06ea967dd6ad","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteReceipt","classification":"DESTRUCTIVE","schema":"85cf4fd2917f","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteReceiptLine","classification":"DESTRUCTIVE","schema":"76ee331dd860","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteShipment","classification":"DESTRUCTIVE","schema":"42e517e4587d","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteShipmentLine","classification":"DESTRUCTIVE","schema":"dc59afd93e49","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteShippingMethod","classification":"DESTRUCTIVE","schema":"b1c3932e1f43","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteStockTransfer","classification":"DESTRUCTIVE","schema":"948b16d8b971","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteStockTransferLine","classification":"DESTRUCTIVE","schema":"eed9b4ba65ee","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteStorageTypeWithCascade","classification":"DESTRUCTIVE","schema":"684fb584dd36","response":"3797626bd17e","permission":"parts:delete","paginates":false},+ {"name":"inventory_deleteWarehouseTransfer","classification":"DESTRUCTIVE","schema":"e5cf2745c429","response":"bcde375ebd4c","permission":"inventory:delete","paginates":false},+ {"name":"inventory_expandStorageUnitIdsWithDescendants","classification":"READ","schema":"5faaa8568e95","response":"681004346c78","permission":"inventory:view","paginates":false},+ {"name":"inventory_generatePickingList","classification":"DESTRUCTIVE","schema":"3af73486ff99","response":"81802516b555","permission":"inventory:create","paginates":false},+ {"name":"inventory_getAvailableTrackedEntities","classification":"READ","schema":"c77d0fdb7e5d","response":"723554a256de","permission":"inventory:view","paginates":false},+ {"name":"inventory_getBatchNumbersForItem","classification":"READ","schema":"c7f807b08655","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getBatchProperties","classification":"READ","schema":"fb8f0e541b3e","response":"549cd4e15464","permission":"inventory:view","paginates":false},+ {"name":"inventory_getEffectiveWorkCenterId","classification":"READ","schema":"cdcc95c01599","response":"00404e686415","permission":"inventory:view","paginates":false},+ {"name":"inventory_getInventoryCount","classification":"READ","schema":"7f8214d1083f","response":"635fd5c7963f","permission":"inventory:view","paginates":false},+ {"name":"inventory_getInventoryCountLines","classification":"READ","schema":"e910cf155e34","response":"8f948fe95e1e","permission":"inventory:view","paginates":true},+ {"name":"inventory_getInventoryCountLineSummary","classification":"READ","schema":"bb4fa87fa88a","response":"7a06e37fcf2a","permission":"inventory:view","paginates":false},+ {"name":"inventory_getInventoryCountMovements","classification":"READ","schema":"bb4fa87fa88a","response":"ef7ba4828665","permission":"inventory:view","paginates":false},+ {"name":"inventory_getInventoryCounts","classification":"READ","schema":"e2389bb135b5","response":"257241cd106b","permission":"inventory:view","paginates":true},+ {"name":"inventory_getInventoryItems","classification":"READ","schema":"08f57da5e2ae","response":"0ea3e86b6ae1","permission":"inventory:view","paginates":true},+ {"name":"inventory_getInventoryValuation","classification":"READ","schema":"4affbce60a61","response":"d2c7dd5f845a","permission":"accounting:view","paginates":false},+ {"name":"inventory_getInventoryValuationTieOut","classification":"READ","schema":"70fbe1224878","response":"20aee38c95a3","permission":"accounting:view","paginates":false},+ {"name":"inventory_getItemLedgerActivity","classification":"READ","schema":"019d7d34869e","response":"855f6c444e56","permission":"inventory:view","paginates":false},+ {"name":"inventory_getItemLedgerBalance","classification":"READ","schema":"798c87d1101b","response":"cddf8275afa1","permission":"inventory:view","paginates":false},+ {"name":"inventory_getKanban","classification":"READ","schema":"84ad7166f1d7","response":"a4f312fff33a","permission":"inventory:view","paginates":false},+ {"name":"inventory_getKanbanProjectedQuantities","classification":"READ","schema":"333fb45d8bc5","response":"98903cc375ce","permission":"inventory:view","paginates":false},+ {"name":"inventory_getKanbans","classification":"READ","schema":"08f57da5e2ae","response":"10c63802d01c","permission":"inventory:view","paginates":true},+ {"name":"inventory_getPickingList","classification":"READ","schema":"06ea967dd6ad","response":"bdbdc3b12cd7","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListAvailability","classification":"READ","schema":"06ea967dd6ad","response":"a2c799262a3c","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListLine","classification":"READ","schema":"e2b1df794940","response":"58364897e03b","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListLines","classification":"READ","schema":"06ea967dd6ad","response":"eb327ca3ae07","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListRecommendations","classification":"READ","schema":"06ea967dd6ad","response":"24283057a15d","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingListRelatedItems","classification":"READ","schema":"06ea967dd6ad","response":"97b485f3b5e3","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickingLists","classification":"READ","schema":"37aa61438e0f","response":"143c1acfb4cd","permission":"inventory:view","paginates":true},+ {"name":"inventory_getPickingSchedule","classification":"READ","schema":"bfb3c1ae0982","response":"ce619e8c4917","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPickOrder","classification":"READ","schema":"624646b5f0ec","response":"9f5ba8273e4a","permission":"inventory:view","paginates":false},+ {"name":"inventory_getPicksByJobMaterial","classification":"READ","schema":"ca49bc65b712","response":"b53992cb5f0c","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceipt","classification":"READ","schema":"85cf4fd2917f","response":"32c1c823ab1f","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceiptFiles","classification":"READ","schema":"72a93572f55f","response":"5483e69d7515","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceiptLines","classification":"READ","schema":"85cf4fd2917f","response":"15b7b17f7652","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceiptRelatedItems","classification":"READ","schema":"8a3528c62244","response":"2f7d31c914c3","permission":"inventory:view","paginates":false},+ {"name":"inventory_getReceipts","classification":"READ","schema":"e2389bb135b5","response":"c0e9f6bbdcad","permission":"inventory:view","paginates":true},+ {"name":"inventory_getReceiptTracking","classification":"READ","schema":"85cf4fd2917f","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getRentalReceiptLines","classification":"READ","schema":"85cf4fd2917f","response":"7fb4d944b992","permission":"inventory:view","paginates":false},+ {"name":"inventory_getRentalShipmentLines","classification":"READ","schema":"42e517e4587d","response":"81dce2e81f32","permission":"inventory:view","paginates":false},+ {"name":"inventory_getSerialNumbersForItem","classification":"READ","schema":"30ab89ff5be9","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getSerialUnitCosts","classification":"READ","schema":"d8cb61960dff","response":"97d1e7eb3966","permission":"accounting:view","paginates":false},+ {"name":"inventory_getShelfLifeForItems","classification":"READ","schema":"fb8f0e541b3e","response":"89287a5cd5c2","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShipment","classification":"READ","schema":"42e517e4587d","response":"cf4ab10c35e3","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShipmentLines","classification":"READ","schema":"42e517e4587d","response":"a8d2ad5b9993","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShipmentRelatedItems","classification":"READ","schema":"d8f45c9e7f04","response":"ced6a1949e63","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShipments","classification":"READ","schema":"e2389bb135b5","response":"496419b3de9a","permission":"inventory:view","paginates":true},+ {"name":"inventory_getShipmentTracking","classification":"READ","schema":"42e517e4587d","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShippingMethod","classification":"READ","schema":"b1c3932e1f43","response":"21907ace7452","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShippingMethods","classification":"READ","schema":"e2389bb135b5","response":"3b04f1c33636","permission":"inventory:view","paginates":true},+ {"name":"inventory_getShippingMethodsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getShippingTermsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStockMovementEffectiveQuantity","classification":"READ","schema":"be17c4d58a6a","response":"2e1967d88231","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStockMovements","classification":"READ","schema":"e2389bb135b5","response":"5a637523d776","permission":"inventory:view","paginates":true},+ {"name":"inventory_getStockTransfer","classification":"READ","schema":"948b16d8b971","response":"69c0eeefc47c","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStockTransferLines","classification":"READ","schema":"948b16d8b971","response":"bcb01288cc29","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStockTransfers","classification":"READ","schema":"f88b65daba82","response":"b4c0b46b39b5","permission":"inventory:view","paginates":true},+ {"name":"inventory_getStorageType","classification":"READ","schema":"7f8214d1083f","response":"4bbb50609deb","permission":"parts:view","paginates":false},+ {"name":"inventory_getStorageTypes","classification":"READ","schema":"e2389bb135b5","response":"f6f55833db42","permission":"parts:view","paginates":true},+ {"name":"inventory_getStorageTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageTypeUsage","classification":"READ","schema":"7f8214d1083f","response":"ce08332e0ce6","permission":"parts:view","paginates":false},+ {"name":"inventory_getStorageUnit","classification":"READ","schema":"cdcc95c01599","response":"a5bf237a9aeb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitChildren","classification":"READ","schema":"a3bb93ab688c","response":"7eea15677f40","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitDescendants","classification":"READ","schema":"cdcc95c01599","response":"3bae190e2656","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitParentIdsWithChildren","classification":"READ","schema":"75b90f67d533","response":"681004346c78","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitRoots","classification":"READ","schema":"08f57da5e2ae","response":"dd81c689cce6","permission":"inventory:view","paginates":true},+ {"name":"inventory_getStorageUnitsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitsListForLocation","classification":"READ","schema":"75b90f67d533","response":"ce08332e0ce6","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitsTreeForLocation","classification":"READ","schema":"75b90f67d533","response":"ecdf2c570468","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitSubtrees","classification":"READ","schema":"b9bea08b8fcd","response":"10e6a05f40e5","permission":"inventory:view","paginates":false},+ {"name":"inventory_getTrackedEntities","classification":"READ","schema":"e2389bb135b5","response":"15f4dee0e3cd","permission":"inventory:view","paginates":true},+ {"name":"inventory_getTrackedEntitiesByMakeMethodId","classification":"READ","schema":"7679db37b5f9","response":"ec54684c77fb","permission":"inventory:view","paginates":false},+ {"name":"inventory_getTrackedEntity","classification":"READ","schema":"461bb7f6bafb","response":"1007059c8406","permission":"inventory:view","paginates":false},+ {"name":"inventory_getTrackedEntityExpirations","classification":"READ","schema":"518b9dee6f55","response":"fff84b1ee888","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransfer","classification":"READ","schema":"e5cf2745c429","response":"97efc7703189","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransferLine","classification":"READ","schema":"e22f9f5a0cc9","response":"ff87020af237","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransferLines","classification":"READ","schema":"e5cf2745c429","response":"4cdf01fbc41c","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransferRelatedItems","classification":"READ","schema":"e5cf2745c429","response":"d866112ded31","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransfers","classification":"READ","schema":"e2389bb135b5","response":"66af9aaf6283","permission":"inventory:view","paginates":true},+ {"name":"inventory_insertWarehouseTransfer","classification":"WRITE","schema":"82ec35c02526","response":"8e9431d157a2","permission":"inventory:create","paginates":false},+ {"name":"inventory_mergeTrackedEntities","classification":"WRITE","schema":"b12fee74a91e","response":"none","permission":"inventory:update","paginates":false},+ {"name":"inventory_pickPickingListLineChecked","classification":"WRITE","schema":"f50f15524edc","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_pickPickingListLineEntity","classification":"WRITE","schema":"5a008770ac64","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_pickStockTransferLine","classification":"WRITE","schema":"0d3ec0c22afe","response":"7ad8a3f49853","permission":"inventory:create","paginates":false},+ {"name":"inventory_pickStockTransferLineEntity","classification":"WRITE","schema":"d077ae617fd9","response":"7ad8a3f49853","permission":"inventory:update","paginates":false},+ {"name":"inventory_postInventoryCount","classification":"WRITE","schema":"e354150046fe","response":"c65e556842f4","permission":"inventory:update","paginates":false},+ {"name":"inventory_postReceipt","classification":"WRITE","schema":"748c476fdf2b","response":"727cf771e24b","permission":"inventory:update","paginates":false},+ {"name":"inventory_postShipment","classification":"WRITE","schema":"c5945bba6ca6","response":"d2fbdd9c8de9","permission":"inventory:update","paginates":false},+ {"name":"inventory_recostSerialUnit","classification":"WRITE","schema":"c3f4c85c02d3","response":"1791201245a6","permission":"accounting:update","paginates":false},+ {"name":"inventory_removeReceiptReturnEntity","classification":"WRITE","schema":"727806547880","response":"5d58d420052a","permission":"inventory:create","paginates":false},+ {"name":"inventory_removeStorageUnit","classification":"DESTRUCTIVE","schema":"35393c22f425","response":"2483090811c4","permission":"inventory:delete","paginates":false},+ {"name":"inventory_removeWarehouseTransferLine","classification":"DESTRUCTIVE","schema":"e969960c72a3","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_searchStorageUnitsWithAncestors","classification":"READ","schema":"60d210afc3c8","response":"bcde375ebd4c","permission":"inventory:view","paginates":false},+ {"name":"inventory_setPickingListStatus","classification":"WRITE","schema":"ccde50ab0ad1","response":"f08c04238f16","permission":"inventory:update","paginates":false},+ {"name":"inventory_setReceiptLineBatch","classification":"WRITE","schema":"9e81223e8999","response":"17337505bb69","permission":"inventory:create","paginates":false},+ {"name":"inventory_setReceiptLineSerial","classification":"WRITE","schema":"0993bde06f1d","response":"535137f2982a","permission":"inventory:create","paginates":false},+ {"name":"inventory_setStockTransferStatus","classification":"WRITE","schema":"afbc91bb3596","response":"734f52cb2f24","permission":"inventory:update","paginates":false},+ {"name":"inventory_setWarehouseTransferStatus","classification":"WRITE","schema":"9a60ace036e6","response":"5ca40ef79448","permission":"inventory:update","paginates":false},+ {"name":"inventory_splitReceiptLine","classification":"WRITE","schema":"9530619bf74b","response":"17337505bb69","permission":"inventory:update","paginates":false},+ {"name":"inventory_splitShipmentLine","classification":"WRITE","schema":"34f9c93ce7da","response":"84320a09c1ac","permission":"inventory:update","paginates":false},+ {"name":"inventory_unpickStockTransferLine","classification":"WRITE","schema":"9caff79be87e","response":"7ad8a3f49853","permission":"inventory:create","paginates":false},+ {"name":"inventory_updateBatchPropertyOrder","classification":"WRITE","schema":"12f0062fbf60","response":"bcde375ebd4c","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateInventoryCountLine","classification":"WRITE","schema":"e59c475ac625","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateInventoryCountStatus","classification":"WRITE","schema":"7ef2505ff688","response":"7ef2505ff688","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateKanban","classification":"WRITE","schema":"1e2cc24f8ebc","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updatePickingList","classification":"WRITE","schema":"cb8e9e110bfa","response":"0a4ec3e7319b","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateReceipt","classification":"WRITE","schema":"02e274bc337e","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateReceiptFixedAssetLine","classification":"WRITE","schema":"a7515d002c5d","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateReceiptLines","classification":"WRITE","schema":"3a91317efcce","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateShipment","classification":"WRITE","schema":"14ecca1fc57d","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateShipmentFixedAssetLine","classification":"WRITE","schema":"ab168f9d9366","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateShipmentLines","classification":"WRITE","schema":"3a4fe03b9c85","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateShippingMethod","classification":"WRITE","schema":"80d74aa65965","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateStockTransferLine","classification":"WRITE","schema":"0d0980429702","response":"3797626bd17e","permission":"inventory:create+update","paginates":false},+ {"name":"inventory_updateStockTransferLines","classification":"WRITE","schema":"17ef89b7d868","response":"0eb0c2be01ed","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateStorageType","classification":"WRITE","schema":"5f39e7b61b61","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"inventory_updateStorageUnit","classification":"WRITE","schema":"c3764f79a859","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateTrackedEntityExpiry","classification":"WRITE","schema":"80b2e16440b3","response":"bcde375ebd4c","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateWarehouseTransfer","classification":"WRITE","schema":"34bffa7fa259","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_updateWarehouseTransferLine","classification":"WRITE","schema":"83d5ec885100","response":"3797626bd17e","permission":"inventory:update","paginates":false},+ {"name":"inventory_upsertBatchProperty","classification":"WRITE","schema":"f0713a3f9fb4","response":"bcde375ebd4c","permission":"inventory:update","paginates":false},+ {"name":"inventory_voidReceipt","classification":"DESTRUCTIVE","schema":"e00a9764517d","response":"e00a9764517d","permission":"inventory:update","paginates":false},+ {"name":"inventory_voidShipment","classification":"DESTRUCTIVE","schema":"2e39a760a5ca","response":"2e39a760a5ca","permission":"inventory:update","paginates":false},+ {"name":"invoicing_adjustPayables","classification":"WRITE","schema":"783894538b85","response":"7e2279b19577","permission":"accounting:create","paginates":false},+ {"name":"invoicing_adjustReceivables","classification":"WRITE","schema":"783894538b85","response":"7e2279b19577","permission":"accounting:create","paginates":false},+ {"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","schema":"44fe03d8575b","response":"none","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_createMemo","classification":"WRITE","schema":"37857c88159d","response":"1e0d0fa1a854","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createPayment","classification":"WRITE","schema":"655768d847ef","response":"9afa42aa85f3","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createPurchaseInvoice","classification":"WRITE","schema":"9de21d765491","response":"24b4b1602470","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","schema":"47850e9f092b","response":"873673b16fc8","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createPurchaseInvoiceLine","classification":"WRITE","schema":"ba464cd8849c","response":"3797626bd17e","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","schema":"6e4655763b3f","response":"873673b16fc8","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createSalesInvoiceFromShipment","classification":"WRITE","schema":"42e517e4587d","response":"873673b16fc8","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_createSalesInvoiceLine","classification":"WRITE","schema":"7cf0f0de23bd","response":"2f2c2a380211","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_deleteDraftMemo","classification":"DESTRUCTIVE","schema":"188417093a55","response":"dc19b5347651","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deleteDraftPurchaseInvoice","classification":"DESTRUCTIVE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deleteDraftPurchaseInvoiceLine","classification":"DESTRUCTIVE","schema":"97778f2244c8","response":"97778f2244c8","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deleteDraftSalesInvoice","classification":"DESTRUCTIVE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deleteDraftSalesInvoiceLine","classification":"DESTRUCTIVE","schema":"97778f2244c8","response":"97778f2244c8","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_deletePayment","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"invoicing:delete","paginates":false},+ {"name":"invoicing_getApAging","classification":"READ","schema":"022511e83f02","response":"eca97da3238d","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getApOpenBySupplier","classification":"READ","schema":"0f10306ad40d","response":"cfaa2af435c0","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getApTieOut","classification":"READ","schema":"0f10306ad40d","response":"194f80599d96","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getArAging","classification":"READ","schema":"022511e83f02","response":"10729e9f1c72","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getArOpenByCustomer","classification":"READ","schema":"0f10306ad40d","response":"8cd731dddf0d","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getArTieOut","classification":"READ","schema":"0f10306ad40d","response":"194f80599d96","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getAvailableCreditsForParty","classification":"READ","schema":"1724f4d913e4","response":"f8e7a5443d43","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getAvailableOnAccountCreditSources","classification":"READ","schema":"0da34ef6d281","response":"6d10888c4cf8","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getCharge","classification":"READ","schema":"7f8214d1083f","response":"9429143db43f","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getCharges","classification":"READ","schema":"76b98034f8cb","response":"8b1485171a5a","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getCompanyHasOpenCredits","classification":"READ","schema":"75e0842dae15","response":"4a5fff977a84","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getInvoiceSettlements","classification":"READ","schema":"b4184c2c9476","response":"5483e69d7515","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getInvoiceSettlementsForInvoice","classification":"READ","schema":"3ec6c9a760cc","response":"a334c4e05d56","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getMemo","classification":"READ","schema":"7f8214d1083f","response":"98fffe52edef","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getMemoApplications","classification":"READ","schema":"b41339a8c21f","response":"8b54c25de723","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getMemos","classification":"READ","schema":"e910e5c462ff","response":"ec5a471a7216","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","schema":"eeadc5002c42","response":"a16080b3cb31","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getOpenReimbursementsForEmployee","classification":"READ","schema":"3cea1230c460","response":"84fe5db303b4","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","schema":"0de5d59cc116","response":"a16080b3cb31","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPayment","classification":"READ","schema":"7f8214d1083f","response":"f122ccd210ed","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPaymentCurrencyConfiguration","classification":"READ","schema":"8775a38b3ca9","response":"35b15cbf37ce","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPayments","classification":"READ","schema":"cdc85fab2e0e","response":"ba894f328d1f","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getPurchaseInvoice","classification":"READ","schema":"0f5da439c637","response":"b6cde92056ff","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPurchaseInvoiceDelivery","classification":"READ","schema":"0f5da439c637","response":"cf43c4365a30","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPurchaseInvoiceLine","classification":"READ","schema":"103b0006e8d5","response":"8c0b6537bf26","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPurchaseInvoiceLines","classification":"READ","schema":"0f5da439c637","response":"34789e863e7e","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getPurchaseInvoices","classification":"READ","schema":"40d81af5aff8","response":"1f74efb3e9eb","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getReimbursement","classification":"READ","schema":"7f8214d1083f","response":"c1191896ef6c","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getReimbursementRelatedItems","classification":"READ","schema":"a4fa008a9ff4","response":"b44573ee4608","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getReimbursements","classification":"READ","schema":"6499db3a7b41","response":"15d72f6aca0c","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getSalesInvoice","classification":"READ","schema":"881060cc8281","response":"3fd5b06e1335","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getSalesInvoiceLine","classification":"READ","schema":"943ed3109227","response":"94dbec26018a","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getSalesInvoiceLines","classification":"READ","schema":"881060cc8281","response":"e5d8bd13c859","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getSalesInvoices","classification":"READ","schema":"e410e96b4ae8","response":"2713f6338edb","permission":"invoicing:view","paginates":true},+ {"name":"invoicing_getSalesInvoiceShipment","classification":"READ","schema":"881060cc8281","response":"64ebc394caae","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_getStagedCreditsForPayment","classification":"READ","schema":"2d0fe8b55e39","response":"5a23b05562f4","permission":"invoicing:view","paginates":false},+ {"name":"invoicing_insertSalesInvoice","classification":"DESTRUCTIVE","schema":"bfaa3332658d","response":"24b4b1602470","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_mapPurchaseInvoiceLines","classification":"WRITE","schema":"f92e77ef6854","response":"2132422b3a2d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_payReimbursement","classification":"WRITE","schema":"d5ace743aeb9","response":"6abc9e87bdd2","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_postMemo","classification":"WRITE","schema":"188417093a55","response":"188417093a55","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_postPayment","classification":"WRITE","schema":"bd163ca304cd","response":"bd163ca304cd","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_postPurchaseInvoice","classification":"WRITE","schema":"5710b96a8949","response":"2d07f638a2bb","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_postReimbursement","classification":"WRITE","schema":"1440dbb5599d","response":"1440dbb5599d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_postSalesInvoice","classification":"WRITE","schema":"4b9809c93c34","response":"aa004f6905a5","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_replaceInvoiceSettlements","classification":"DESTRUCTIVE","schema":"e0be02846a7a","response":"none","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_saveAndPostReimbursement","classification":"WRITE","schema":"f7e0727ee74c","response":"1440dbb5599d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_saveReimbursement","classification":"WRITE","schema":"f7e0727ee74c","response":"1440dbb5599d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_sendSalesInvoice","classification":"WRITE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updateMemo","classification":"WRITE","schema":"f66d6582821f","response":"1e0d0fa1a854","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePayment","classification":"WRITE","schema":"9201cc5406b9","response":"1a922c685a61","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePurchaseInvoice","classification":"WRITE","schema":"c797b53746b5","response":"3797626bd17e","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePurchaseInvoiceExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePurchaseInvoiceLine","classification":"WRITE","schema":"ef8b2133bf96","response":"3797626bd17e","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updatePurchaseInvoiceLineOrder","classification":"WRITE","schema":"536a93fbc84a","response":"none","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updateSalesInvoiceExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_updateSalesInvoiceLine","classification":"WRITE","schema":"2dbb4b6a4ebe","response":"2f2c2a380211","permission":"invoicing:create","paginates":false},+ {"name":"invoicing_updateSalesInvoiceLineOrder","classification":"WRITE","schema":"536a93fbc84a","response":"none","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_upsertPurchaseInvoiceDelivery","classification":"WRITE","schema":"3f1b55f12045","response":"3797626bd17e","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_upsertSalesInvoiceShipment","classification":"WRITE","schema":"f786af7dbb23","response":"3797626bd17e","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidCharge","classification":"DESTRUCTIVE","schema":"e766b8931d7d","response":"e766b8931d7d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidMemo","classification":"DESTRUCTIVE","schema":"188417093a55","response":"188417093a55","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidPayment","classification":"DESTRUCTIVE","schema":"bd163ca304cd","response":"bd163ca304cd","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidPurchaseInvoice","classification":"DESTRUCTIVE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidReimbursement","classification":"DESTRUCTIVE","schema":"1440dbb5599d","response":"1440dbb5599d","permission":"invoicing:update","paginates":false},+ {"name":"invoicing_voidSalesInvoice","classification":"DESTRUCTIVE","schema":"79cd487d4e95","response":"79cd487d4e95","permission":"invoicing:update","paginates":false},+ {"name":"items_activateMethodVersion","classification":"WRITE","schema":"7f8214d1083f","response":"873673b16fc8","permission":"parts:update","paginates":false},+ {"name":"items_addChangeNoticeAffectedItem","classification":"DESTRUCTIVE","schema":"624f956839eb","response":"3cc309ba4541","permission":"parts:create","paginates":false},+ {"name":"items_addItemPredecessor","classification":"WRITE","schema":"62c99356d14b","response":"c838ffde6390","permission":"parts:update","paginates":false},+ {"name":"items_assertMethodOperationIsDraft","classification":"WRITE","schema":"3561ad8e0d42","response":"c407a9edb930","permission":"parts:update","paginates":false},+ {"name":"items_copyMethod","classification":"DESTRUCTIVE","schema":"149990a9b059","response":"d12019e0a561","permission":"parts:update","paginates":false},+ {"name":"items_createChangeNotice","classification":"WRITE","schema":"4ba09c051d82","response":"8e58a21e4c94","permission":"parts:create","paginates":false},+ {"name":"items_createChangeNoticeForItem","classification":"WRITE","schema":"4fe1ddc95e07","response":"a443ac9aa1f1","permission":"parts:create","paginates":false},+ {"name":"items_createChangeNoticeType","classification":"WRITE","schema":"dac43048240a","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createConsumable","classification":"WRITE","schema":"433b52bae6a3","response":"none","permission":"parts:create","paginates":false},+ {"name":"items_createItemDocumentUploadUrl","classification":"WRITE","schema":"c99d2620a4f0","response":"4ad76afe0777","permission":"parts:create","paginates":false},+ {"name":"items_createItemPostingGroup","classification":"WRITE","schema":"84e2df529d4e","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createItemThumbnailUploadUrl","classification":"WRITE","schema":"6dcd390c3681","response":"e7dd9ea63165","permission":"parts:update","paginates":false},+ {"name":"items_createMaterial","classification":"WRITE","schema":"589547ce04ca","response":"none","permission":"parts:create","paginates":false},+ {"name":"items_createMaterialForm","classification":"WRITE","schema":"860d7b0dca51","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMaterialSubstance","classification":"WRITE","schema":"860d7b0dca51","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodMaterial","classification":"WRITE","schema":"e0c1a6885f91","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperation","classification":"WRITE","schema":"f94a54edce25","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperationParameter","classification":"WRITE","schema":"fd33201b6404","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperationStep","classification":"WRITE","schema":"47d8a0a8b0c2","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperationStepSlide","classification":"WRITE","schema":"4c0b7fbb41fe","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodOperationTool","classification":"WRITE","schema":"b4ca2f2a0605","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createMethodVersion","classification":"WRITE","schema":"cd53dc57847a","response":"e83987f24b08","permission":"parts:create","paginates":false},+ {"name":"items_createModelUploadUrl","classification":"WRITE","schema":"098974972159","response":"56f546fd3bc7","permission":"parts:create+update","paginates":false},+ {"name":"items_createPart","classification":"WRITE","schema":"4206b71c74bb","response":"baa524ddff70","permission":"parts:create","paginates":false},+ {"name":"items_createPickMethod","classification":"WRITE","schema":"17f3be4ef104","response":"bcde375ebd4c","permission":"parts:create","paginates":false},+ {"name":"items_createRevision","classification":"WRITE","schema":"3488d3b3792b","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createService","classification":"WRITE","schema":"b2e0cbbb8346","response":"9b123283f2f8","permission":"parts:create","paginates":false},+ {"name":"items_createSupplierPart","classification":"WRITE","schema":"7581bda3d7fb","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_createTool","classification":"WRITE","schema":"03346d16b685","response":"none","permission":"parts:create","paginates":false},+ {"name":"items_createUnitOfMeasure","classification":"WRITE","schema":"f6380dbe504f","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_decideChangeNoticeApproval","classification":"WRITE","schema":"b9b5aeddd8c9","response":"7656db048f90","permission":"parts:update","paginates":false},+ {"name":"items_deleteChangeNotice","classification":"DESTRUCTIVE","schema":"ceb3bf7aba37","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteChangeNoticeAction","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteChangeNoticeRequiredAction","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteChangeNoticeType","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteConfigurationParameter","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteConfigurationParameterGroup","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteConfigurationRule","classification":"DESTRUCTIVE","schema":"5f4af67f6096","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteItem","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteItemCustomerPart","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteItemPostingGroup","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialDimension","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialFinish","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialForm","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialGrade","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialSubstance","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMaterialType","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodMaterial","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperation","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"c3ca3a3cb7fc","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperationParameter","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperationStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperationStepSlide","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteMethodOperationTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteSupplierPart","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_deleteUnitOfMeasure","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_duplicateMethodOperationStep","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"parts:create","paginates":false},+ {"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","schema":"30ab89ff5be9","response":"4a5fff977a84","permission":"parts:view","paginates":false},+ {"name":"items_getBomItemAttributes","classification":"READ","schema":"fb8f0e541b3e","response":"a2c799262a3c","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNotice","classification":"READ","schema":"ceb3bf7aba37","response":"1a1262d4cc54","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeActions","classification":"READ","schema":"ceb3bf7aba37","response":"b7e9332382ae","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeAffectedItems","classification":"READ","schema":"ceb3bf7aba37","response":"5483e69d7515","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeDiff","classification":"READ","schema":"ceb3bf7aba37","response":"e8b6cfecb257","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeRequiredAction","classification":"READ","schema":"7f8214d1083f","response":"a76ce814b1b8","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeRequiredActions","classification":"READ","schema":"e2389bb135b5","response":"02b33c1a9497","permission":"parts:view","paginates":true},+ {"name":"items_getChangeNoticeRequiredActionsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNotices","classification":"READ","schema":"e2389bb135b5","response":"6421ab92a21e","permission":"parts:view","paginates":true},+ {"name":"items_getChangeNoticesForNonConformance","classification":"READ","schema":"9a315debddd5","response":"f1df16d41df5","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeType","classification":"READ","schema":"7f8214d1083f","response":"d15ce193a0df","permission":"parts:view","paginates":false},+ {"name":"items_getChangeNoticeTypes","classification":"READ","schema":"e2389bb135b5","response":"336d9d3523bb","permission":"parts:view","paginates":true},+ {"name":"items_getChangeNoticeTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"parts:view","paginates":false},+ {"name":"items_getConfigurationParameters","classification":"READ","schema":"30ab89ff5be9","response":"4dc7e9b6cbc3","permission":"parts:view","paginates":false},+ {"name":"items_getConfigurationRules","classification":"READ","schema":"30ab89ff5be9","response":"530f6f787ce7","permission":"parts:view","paginates":false},+ {"name":"items_getConsumable","classification":"READ","schema":"30ab89ff5be9","response":"7cef8bd2c0a7","permission":"parts:view","paginates":false},+ {"name":"items_getConsumables","classification":"READ","schema":"40d81af5aff8","response":"ae2e9a889c25","permission":"parts:view","paginates":true},+ {"name":"items_getDemandForecastSources","classification":"READ","schema":"fb1a8cd5199a","response":"dcd470bf07a6","permission":"parts:view","paginates":false},+ {"name":"items_getItem","classification":"READ","schema":"7f8214d1083f","response":"6a9155217648","permission":"parts:view","paginates":false},+ {"name":"items_getItemCost","classification":"READ","schema":"30ab89ff5be9","response":"10e413636da7","permission":"parts:view","paginates":false},+ {"name":"items_getItemCostHistory","classification":"READ","schema":"30ab89ff5be9","response":"082f2602a5cd","permission":"parts:view","paginates":false},+ {"name":"items_getItemCustomerPart","classification":"READ","schema":"7f8214d1083f","response":"4c6e08919580","permission":"parts:view","paginates":false},+ {"name":"items_getItemCustomerParts","classification":"READ","schema":"30ab89ff5be9","response":"458a8cdb47f2","permission":"parts:view","paginates":false},+ {"name":"items_getItemDemand","classification":"READ","schema":"fb1a8cd5199a","response":"bcde375ebd4c","permission":"parts:view","paginates":false},+ {"name":"items_getItemFiles","classification":"READ","schema":"30ab89ff5be9","response":"6351756c9816","permission":"parts:view","paginates":false},+ {"name":"items_getItemManufacturing","classification":"READ","schema":"7f8214d1083f","response":"f399bb7eda67","permission":"parts:view","paginates":false},+ {"name":"items_getItemMpnsList","classification":"READ","schema":"31b84d65b2ac","response":"3ff28fd20707","permission":"parts:view","paginates":false},+ {"name":"items_getItemPlanning","classification":"READ","schema":"624646b5f0ec","response":"41dfd5d2df83","permission":"parts:view","paginates":false},+ {"name":"items_getItemPostingGroup","classification":"READ","schema":"7f8214d1083f","response":"d38ff3570b60","permission":"parts:view","paginates":false},+ {"name":"items_getItemPostingGroups","classification":"READ","schema":"e2389bb135b5","response":"7e71cc335d29","permission":"parts:view","paginates":true},+ {"name":"items_getItemPostingGroupsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"parts:view","paginates":false},+ {"name":"items_getItemQuantities","classification":"READ","schema":"624646b5f0ec","response":"3ea7d7161a8d","permission":"parts:view","paginates":false},+ {"name":"items_getItemReplenishment","classification":"READ","schema":"30ab89ff5be9","response":"f399bb7eda67","permission":"parts:view","paginates":false},+ {"name":"items_getItemShelfLife","classification":"READ","schema":"30ab89ff5be9","response":"7382c0121cdc","permission":"parts:view","paginates":false},+ {"name":"items_getItemStockQuantitiesByLocation","classification":"READ","schema":"75b90f67d533","response":"96915ea19193","permission":"parts:view","paginates":false},+ {"name":"items_getItemStorageUnitQuantities","classification":"READ","schema":"624646b5f0ec","response":"880fa3aa7279","permission":"parts:view","paginates":false},+ {"name":"items_getItemSupersession","classification":"READ","schema":"30ab89ff5be9","response":"ef0e933fa9cc","permission":"parts:view","paginates":false},+ {"name":"items_getItemSupersessionsForItems","classification":"READ","schema":"fb8f0e541b3e","response":"d8065aede59f","permission":"parts:view","paginates":false},+ {"name":"items_getItemUnitSalePrice","classification":"READ","schema":"7f8214d1083f","response":"7281903c959e","permission":"parts:view","paginates":false},+ {"name":"items_getMakeMethodById","classification":"READ","schema":"16229db592c2","response":"7a9bf3834cea","permission":"parts:view","paginates":false},+ {"name":"items_getMakeMethods","classification":"READ","schema":"30ab89ff5be9","response":"f51c646717be","permission":"parts:view","paginates":false},+ {"name":"items_getMaterial","classification":"READ","schema":"30ab89ff5be9","response":"533d0f3a68ac","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialDimension","classification":"READ","schema":"7f8214d1083f","response":"5a634d31e2f3","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialDimensionList","classification":"READ","schema":"f70b4501b7f5","response":"b72364e0a391","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialDimensions","classification":"READ","schema":"3924290d09e8","response":"aae4fbda0883","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialFinish","classification":"READ","schema":"7f8214d1083f","response":"07a225161151","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialFinishes","classification":"READ","schema":"e2389bb135b5","response":"2cf1f67d0e1d","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialFinishList","classification":"READ","schema":"5d07d00bcb2e","response":"b57774d02b4d","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialForm","classification":"READ","schema":"7f8214d1083f","response":"f69bdbb31d76","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialForms","classification":"READ","schema":"e2389bb135b5","response":"2918b7c99162","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialFormsList","classification":"READ","schema":"31b84d65b2ac","response":"a59b0ccd150e","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialGrade","classification":"READ","schema":"7f8214d1083f","response":"07a225161151","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialGradeList","classification":"READ","schema":"5d07d00bcb2e","response":"b57774d02b4d","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialGrades","classification":"READ","schema":"e2389bb135b5","response":"2cf1f67d0e1d","permission":"parts:view","paginates":true},+ {"name":"items_getMaterials","classification":"READ","schema":"40d81af5aff8","response":"0bbba9542e45","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialSubstance","classification":"READ","schema":"7f8214d1083f","response":"f69bdbb31d76","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialSubstances","classification":"READ","schema":"e2389bb135b5","response":"2918b7c99162","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialSubstancesList","classification":"READ","schema":"31b84d65b2ac","response":"a59b0ccd150e","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialType","classification":"READ","schema":"7f8214d1083f","response":"0cc848ca86e3","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialTypeList","classification":"READ","schema":"7b7914a63732","response":"c3dfbc0fdf89","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialTypes","classification":"READ","schema":"e2389bb135b5","response":"2b35eb66c27c","permission":"parts:view","paginates":true},+ {"name":"items_getMaterialUsedIn","classification":"READ","schema":"30ab89ff5be9","response":"5bc3cafcb138","permission":"parts:view","paginates":false},+ {"name":"items_getMethodMaterials","classification":"READ","schema":"e2389bb135b5","response":"beed367b0416","permission":"parts:view","paginates":true},+ {"name":"items_getMethodMaterialsByMakeMethod","classification":"READ","schema":"16229db592c2","response":"ad8b0c4300d6","permission":"parts:view","paginates":false},+ {"name":"items_getMethodOperations","classification":"READ","schema":"e2389bb135b5","response":"4241b530a8a2","permission":"parts:view","paginates":true},+ {"name":"items_getMethodOperationsByMakeMethodId","classification":"READ","schema":"16229db592c2","response":"5ecfa08f9596","permission":"parts:view","paginates":false},+ {"name":"items_getMethodTree","classification":"READ","schema":"16229db592c2","response":"a3500aed1d64","permission":"parts:view","paginates":false},+ {"name":"items_getOpenJobMaterials","classification":"READ","schema":"624646b5f0ec","response":"3df5c33eb3a4","permission":"parts:view","paginates":false},+ {"name":"items_getOpenProductionOrders","classification":"READ","schema":"624646b5f0ec","response":"e19f7b8a489c","permission":"parts:view","paginates":false},+ {"name":"items_getOpenPurchaseOrderLines","classification":"READ","schema":"624646b5f0ec","response":"c53a83bc1272","permission":"parts:view","paginates":false},+ {"name":"items_getOpenSalesOrderLines","classification":"READ","schema":"624646b5f0ec","response":"ee9244a3a03b","permission":"parts:view","paginates":false},+ {"name":"items_getPart","classification":"READ","schema":"30ab89ff5be9","response":"864fb912a091","permission":"parts:view","paginates":false},+ {"name":"items_getParts","classification":"READ","schema":"40d81af5aff8","response":"a53fabc5de22","permission":"parts:view","paginates":true},+ {"name":"items_getPartsList","classification":"READ","schema":"31b84d65b2ac","response":"f674f76b8278","permission":"parts:view","paginates":false},+ {"name":"items_getPartUsedIn","classification":"READ","schema":"30ab89ff5be9","response":"e205f0dd9382","permission":"parts:view","paginates":false},+ {"name":"items_getPickMethod","classification":"READ","schema":"624646b5f0ec","response":"34ef9a32bf3f","permission":"parts:view","paginates":false},+ {"name":"items_getPickMethods","classification":"READ","schema":"30ab89ff5be9","response":"d3eda5bbd434","permission":"parts:view","paginates":false},+ {"name":"items_getRecipeProcessIdsForItem","classification":"READ","schema":"30ab89ff5be9","response":"681004346c78","permission":"parts:view","paginates":false},+ {"name":"items_getService","classification":"READ","schema":"30ab89ff5be9","response":"864fb912a091","permission":"parts:view","paginates":false},+ {"name":"items_getServices","classification":"READ","schema":"941eb9e8acdf","response":"c4e137bd4e22","permission":"parts:view","paginates":true},+ {"name":"items_getServicesList","classification":"READ","schema":"31b84d65b2ac","response":"f674f76b8278","permission":"parts:view","paginates":false},+ {"name":"items_getSupersessionChain","classification":"READ","schema":"30ab89ff5be9","response":"2897bd7c0865","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierParts","classification":"READ","schema":"7f8214d1083f","response":"77be6c5a4141","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierPartsBySupplier","classification":"READ","schema":"47ea6a43aa68","response":"3b8b6029196a","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierPriceBreaksForItems","classification":"READ","schema":"fb8f0e541b3e","response":"dc0d300695e0","permission":"parts:view","paginates":false},+ {"name":"items_getTool","classification":"READ","schema":"30ab89ff5be9","response":"864fb912a091","permission":"parts:view","paginates":false},+ {"name":"items_getTools","classification":"READ","schema":"40d81af5aff8","response":"12037af61162","permission":"parts:view","paginates":true},+ {"name":"items_getUnitOfMeasure","classification":"READ","schema":"7f8214d1083f","response":"124234df769c","permission":"parts:view","paginates":false},+ {"name":"items_getUnitOfMeasures","classification":"READ","schema":"e2389bb135b5","response":"52562a2400a4","permission":"parts:view","paginates":true},+ {"name":"items_getUnitOfMeasuresList","classification":"READ","schema":"31b84d65b2ac","response":"1333b6f93ca5","permission":"parts:view","paginates":false},+ {"name":"items_getUnitOfMeasureUsage","classification":"READ","schema":"7f8214d1083f","response":"bf91be568e5a","permission":"parts:view","paginates":false},+ {"name":"items_insertModelUpload","classification":"WRITE","schema":"22ea49929c8c","response":"277f7d872d8c","permission":"parts:create+update","paginates":false},+ {"name":"items_recalculateItemCost","classification":"WRITE","schema":"623ca47a6c74","response":"c7c3dd8e466d","permission":"parts:update","paginates":false},+ {"name":"items_removeChangeNoticeAffectedItem","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"parts:delete","paginates":false},+ {"name":"items_renameService","classification":"WRITE","schema":"6dcd390c3681","response":"6680d0e1a37f","permission":"parts:update","paginates":false},+ {"name":"items_resolveItemIdFromExtractedText","classification":"WRITE","schema":"1ec7a4a4f756","response":"00404e686415","permission":"parts:update","paginates":false},+ {"name":"items_setChangeNoticeActionTasks","classification":"DESTRUCTIVE","schema":"d253fbec6a67","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_setChangeNoticeStatus","classification":"WRITE","schema":"402b7d406dcf","response":"3e0f6db57d1a","permission":"parts:update","paginates":false},+ {"name":"items_setItemActive","classification":"WRITE","schema":"c6b56d22bedc","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setItemFields","classification":"WRITE","schema":"6e9bb11463fb","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setItemPostingGroup","classification":"WRITE","schema":"bba153a62986","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setItemReadableId","classification":"WRITE","schema":"3c4b03c24337","response":"20eda0d52ae4","permission":"parts:update","paginates":false},+ {"name":"items_setItemSourcing","classification":"WRITE","schema":"5a836bc5d9a8","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setItemSupersession","classification":"DESTRUCTIVE","schema":"1b0546d69db3","response":"623ca47a6c74","permission":"parts:update","paginates":false},+ {"name":"items_setItemTrackingType","classification":"WRITE","schema":"6ac655073ce2","response":"0eb0c2be01ed","permission":"parts:update","paginates":false},+ {"name":"items_setMaterialProperties","classification":"WRITE","schema":"b768c3d49572","response":"94b3f717a27e","permission":"parts:update","paginates":false},+ {"name":"items_setMethodMaterialStepLink","classification":"DESTRUCTIVE","schema":"17d57d014843","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_setMethodOperationToolStepLink","classification":"DESTRUCTIVE","schema":"0205115c2a9c","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNotice","classification":"WRITE","schema":"bc0a8bcfbdb8","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeActionOrder","classification":"WRITE","schema":"582d2c771eaa","response":"none","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeActionStatus","classification":"WRITE","schema":"7f9d94960d15","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeAffectedItemChangeType","classification":"WRITE","schema":"fd1f74726c79","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeAffectedItemCutover","classification":"WRITE","schema":"9e6fed8b61dc","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateChangeNoticeType","classification":"WRITE","schema":"cf1d57f4963e","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateConfigurationParameterGroupOrder","classification":"WRITE","schema":"29eba0ee8062","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateConfigurationParameterOrder","classification":"WRITE","schema":"b4f1f31e0f60","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateConsumable","classification":"WRITE","schema":"433b52bae6a3","response":"none","permission":"parts:update","paginates":false},+ {"name":"items_updateDefaultRevision","classification":"WRITE","schema":"7f8214d1083f","response":"d02966b20664","permission":"parts:update","paginates":false},+ {"name":"items_updateItem","classification":"WRITE","schema":"ce8e8f42c401","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateItemCost","classification":"WRITE","schema":"77edb4dfa70e","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateItemManufacturing","classification":"WRITE","schema":"8f541b0237ee","response":"623ca47a6c74","permission":"parts:update","paginates":false},+ {"name":"items_updateItemPlanning","classification":"WRITE","schema":"45e5182283f4","response":"ade4704d7338","permission":"parts:update","paginates":false},+ {"name":"items_updateItemPostingGroup","classification":"WRITE","schema":"cba659cc6c3c","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateItemThumbnail","classification":"WRITE","schema":"023aafe5b1be","response":"f806de8159c8","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterial","classification":"WRITE","schema":"589547ce04ca","response":"none","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterialForm","classification":"WRITE","schema":"2bdaab28eafc","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterialOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"f9f1ba0210e3","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterialSubstance","classification":"WRITE","schema":"2bdaab28eafc","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMethodMaterial","classification":"WRITE","schema":"e0c1a6885f91","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_updateMethodOperation","classification":"WRITE","schema":"5079d0b86e77","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_updateMethodOperationParameter","classification":"WRITE","schema":"3d26db99a28d","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMethodOperationStep","classification":"WRITE","schema":"4ba3e76e5486","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMethodOperationStepSlide","classification":"WRITE","schema":"c5583b5b9e1f","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateMethodOperationTool","classification":"WRITE","schema":"e41cd4d18607","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateOperationOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"f9f1ba0210e3","permission":"parts:update","paginates":false},+ {"name":"items_updatePart","classification":"WRITE","schema":"4206b71c74bb","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updatePickMethod","classification":"WRITE","schema":"17f3be4ef104","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateRevision","classification":"WRITE","schema":"959ca7bb400f","response":"bcde375ebd4c","permission":"parts:update","paginates":false},+ {"name":"items_updateService","classification":"WRITE","schema":"74ab79b04f6e","response":"9b123283f2f8","permission":"parts:update","paginates":false},+ {"name":"items_updateSupplierPart","classification":"WRITE","schema":"da1b4d36d0d8","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateTool","classification":"WRITE","schema":"5d9952d97f09","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_updateUnitOfMeasure","classification":"WRITE","schema":"24b44d837617","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_upsertChangeNoticeRequiredAction","classification":"WRITE","schema":"10095195c05f","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConfigurationParameter","classification":"WRITE","schema":"afbee02c34bb","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConfigurationParameterGroup","classification":"WRITE","schema":"30ab89ff5be9","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertConfigurationRule","classification":"WRITE","schema":"2161bfd2d936","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemCost","classification":"WRITE","schema":"26926957800b","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemCustomerPart","classification":"WRITE","schema":"e27e2f57458a","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemPurchasing","classification":"WRITE","schema":"48133cff6c95","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertItemUnitSalePrice","classification":"WRITE","schema":"6e0097529573","response":"bcde375ebd4c","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialDimension","classification":"WRITE","schema":"fe4a810d30fa","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialFinish","classification":"WRITE","schema":"3986f5cee7dd","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialGrade","classification":"WRITE","schema":"3986f5cee7dd","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertMaterialType","classification":"WRITE","schema":"941d8e132060","response":"3797626bd17e","permission":"parts:create+update","paginates":false},+ {"name":"items_upsertPickMethodWithShelfLife","classification":"DESTRUCTIVE","schema":"75ae61cf2fb5","response":"none","permission":"parts:create+update","paginates":false},+ {"name":"people_createDepartment","classification":"WRITE","schema":"b80e47a08bd0","response":"10600fcaa49e","permission":"people:create","paginates":false},+ {"name":"people_createHoliday","classification":"WRITE","schema":"b46de823f50e","response":"8d2b62b6a13b","permission":"people:create","paginates":false},+ {"name":"people_createShift","classification":"WRITE","schema":"8cf7a72c369e","response":"3797626bd17e","permission":"people:create","paginates":false},+ {"name":"people_createTimeCardEntry","classification":"WRITE","schema":"2d56564c17f3","response":"3797626bd17e","permission":"people:create","paginates":false},+ {"name":"people_deleteAttribute","classification":"DESTRUCTIVE","schema":"f94e117ebbcc","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteAttributeCategory","classification":"DESTRUCTIVE","schema":"f621bbe3888e","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteDepartment","classification":"DESTRUCTIVE","schema":"2374948818e7","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteHoliday","classification":"DESTRUCTIVE","schema":"19ad69e7168b","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteShift","classification":"DESTRUCTIVE","schema":"7830c71fa7a3","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_deleteTimeCardEntry","classification":"DESTRUCTIVE","schema":"137e8d26e1e1","response":"bcde375ebd4c","permission":"people:delete","paginates":false},+ {"name":"people_getAttribute","classification":"READ","schema":"f94e117ebbcc","response":"9c635d811516","permission":"people:view","paginates":false},+ {"name":"people_getAttributeCategories","classification":"READ","schema":"e2389bb135b5","response":"58a57d3f8d71","permission":"people:view","paginates":true},+ {"name":"people_getAttributeCategory","classification":"READ","schema":"7f8214d1083f","response":"a52b87433b3b","permission":"people:view","paginates":false},+ {"name":"people_getAttributeDataTypes","classification":"READ","schema":"31b84d65b2ac","response":"dd6f3a6f89d0","permission":"people:view","paginates":false},+ {"name":"people_getDepartment","classification":"READ","schema":"2374948818e7","response":"10600fcaa49e","permission":"people:view","paginates":false},+ {"name":"people_getDepartmentsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"people:view","paginates":false},+ {"name":"people_getDepartmentsTree","classification":"READ","schema":"31b84d65b2ac","response":"8476e48a3c04","permission":"people:view","paginates":false},+ {"name":"people_getEmployeeDepartments","classification":"READ","schema":"31b84d65b2ac","response":"94b797b98edf","permission":"people:view","paginates":false},+ {"name":"people_getEmployeeJob","classification":"READ","schema":"f77d5ceb3fe7","response":"4a3b9b98079b","permission":"people:view","paginates":false},+ {"name":"people_getEmployeeShifts","classification":"READ","schema":"31b84d65b2ac","response":"68279ed68276","permission":"people:view","paginates":false},+ {"name":"people_getEmployeeSummary","classification":"READ","schema":"f77d5ceb3fe7","response":"afd28b3efe9e","permission":"people:view","paginates":false},+ {"name":"people_getHoliday","classification":"READ","schema":"19ad69e7168b","response":"8d2b62b6a13b","permission":"people:view","paginates":false},+ {"name":"people_getHolidays","classification":"READ","schema":"e2389bb135b5","response":"1444dd4d5bec","permission":"people:view","paginates":true},+ {"name":"people_getHolidayYears","classification":"READ","schema":"31b84d65b2ac","response":"5aa0e0e1a152","permission":"people:view","paginates":false},+ {"name":"people_getOpenClockEntry","classification":"READ","schema":"f77d5ceb3fe7","response":"48d1ac3381b4","permission":"people:view","paginates":false},+ {"name":"people_getPeople","classification":"READ","schema":"e2389bb135b5","response":"5483e69d7515","permission":"people:view","paginates":false},+ {"name":"people_getShift","classification":"READ","schema":"7830c71fa7a3","response":"86e4039d95bd","permission":"people:view","paginates":false},+ {"name":"people_getShifts","classification":"READ","schema":"e2389bb135b5","response":"393deb9a5a59","permission":"people:view","paginates":true},+ {"name":"people_getShiftsList","classification":"READ","schema":"3b0300fd8f72","response":"ce08332e0ce6","permission":"people:view","paginates":false},+ {"name":"people_getShiftsWithTimes","classification":"READ","schema":"75b90f67d533","response":"5b99e0634dc7","permission":"people:view","paginates":false},+ {"name":"people_getTimecardEntries","classification":"READ","schema":"e2389bb135b5","response":"eaf533dd012a","permission":"people:view","paginates":true},+ {"name":"people_getTimeCardEntries","classification":"READ","schema":"2ea54a2d0332","response":"f6358cdc55d3","permission":"people:view","paginates":false},+ {"name":"people_getTimeCardEntry","classification":"READ","schema":"137e8d26e1e1","response":"48d1ac3381b4","permission":"people:view","paginates":false},+ {"name":"people_insertAttribute","classification":"WRITE","schema":"f4fd141332d9","response":"3797626bd17e","permission":"people:create","paginates":false},+ {"name":"people_insertAttributeCategory","classification":"WRITE","schema":"98fdf8fdc426","response":"3797626bd17e","permission":"people:create","paginates":false},+ {"name":"people_insertEmployeeJob","classification":"WRITE","schema":"6a5f82638b72","response":"4a3b9b98079b","permission":"people:create","paginates":false},+ {"name":"people_updateAttribute","classification":"WRITE","schema":"1618edb64e98","response":"bcde375ebd4c","permission":"people:update","paginates":false},+ {"name":"people_updateAttributeCategory","classification":"WRITE","schema":"4b94432e3f1e","response":"bcde375ebd4c","permission":"people:update","paginates":false},+ {"name":"people_updateAttributeSortOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"people:update","paginates":false},+ {"name":"people_updateDepartment","classification":"WRITE","schema":"d763f91f263b","response":"10600fcaa49e","permission":"people:update","paginates":false},+ {"name":"people_updateHoliday","classification":"WRITE","schema":"744d6d7901a1","response":"8d2b62b6a13b","permission":"people:update","paginates":false},+ {"name":"people_updatePersonJob","classification":"WRITE","schema":"446acac592dd","response":"3d90cb5d0437","permission":"people:update","paginates":false},+ {"name":"people_updateShift","classification":"WRITE","schema":"838190f4ad9e","response":"3797626bd17e","permission":"people:create+update","paginates":false},+ {"name":"people_updateTimeCardEntry","classification":"WRITE","schema":"bdc65b281270","response":"bcde375ebd4c","permission":"people:update","paginates":false},+ {"name":"production_activateAssemblyInstructionVersion","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_applyPlanningActions","classification":"WRITE","schema":"79dab5513239","response":"a217bafc5309","permission":"production:update","paginates":false},+ {"name":"production_assignPerson","classification":"WRITE","schema":"1e2fd21c16fd","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_assignPersonWeek","classification":"WRITE","schema":"6e0908453d4b","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_assignProductionPlanningActions","classification":"WRITE","schema":"a18b4088f112","response":"2a69a1e7d58b","permission":"production:update","paginates":false},+ {"name":"production_cancelAssemblyJob","classification":"DESTRUCTIVE","schema":"0812c2c1736b","response":"fee5c53bb83d","permission":"production:update","paginates":false},+ {"name":"production_cancelJob","classification":"WRITE","schema":"e9ad3b418621","response":"6d52a19440e7","permission":"production:update","paginates":false},+ {"name":"production_clearPersonAbsence","classification":"DESTRUCTIVE","schema":"6e16b6a2487f","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_closeJob","classification":"WRITE","schema":"4999bd4be598","response":"eecc1bc3f4f6","permission":"production:update","paginates":false},+ {"name":"production_completeJob","classification":"WRITE","schema":"6cc84af4993e","response":"6d52a19440e7","permission":"production:update","paginates":false},+ {"name":"production_completeOperation","classification":"WRITE","schema":"92c192733c55","response":"665690c509e5","permission":"production:create+update","paginates":false},+ {"name":"production_configureJob","classification":"WRITE","schema":"d7a30b2c4e67","response":"4999bd4be598","permission":"production:update","paginates":false},+ {"name":"production_convertAssemblyModel","classification":"WRITE","schema":"3797626bd17e","response":"277f7d872d8c","permission":"production:update","paginates":false},+ {"name":"production_convertSalesOrderLinesToJobs","classification":"WRITE","schema":"94c4cbf5579d","response":"94c4cbf5579d","permission":"production:create","paginates":false},+ {"name":"production_copyAssemblyInstructionAsVersion","classification":"WRITE","schema":"a4568aa19857","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_copyMethodToJob","classification":"WRITE","schema":"398de2ffb61a","response":"4999bd4be598","permission":"production:update","paginates":false},+ {"name":"production_copyMethodToMaterial","classification":"WRITE","schema":"d184c854f615","response":"c32158774ba3","permission":"production:update","paginates":false},+ {"name":"production_copyPeopleDay","classification":"WRITE","schema":"eab08fa3c9e8","response":"cbf943bfb8ed","permission":"production:update","paginates":false},+ {"name":"production_copyPeopleWeekBoard","classification":"WRITE","schema":"adb62afbceb4","response":"cbf943bfb8ed","permission":"production:update","paginates":false},+ {"name":"production_createAssemblyInstruction","classification":"WRITE","schema":"b4c98ec19282","response":"baecc665b224","permission":"production:create","paginates":false},+ {"name":"production_createAssemblyInstructionStepSlide","classification":"WRITE","schema":"4c0b7fbb41fe","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createBatch","classification":"WRITE","schema":"e4cb11866b3a","response":"d6f069964d23","permission":"production:update","paginates":false},+ {"name":"production_createFailureMode","classification":"WRITE","schema":"d73822329fe1","response":"8394fbabd845","permission":"production:create","paginates":false},+ {"name":"production_createJob","classification":"WRITE","schema":"841ed7f7a528","response":"4999bd4be598","permission":"production:create","paginates":false},+ {"name":"production_createJobDocumentUploadUrl","classification":"WRITE","schema":"685f6d6e5714","response":"4ad76afe0777","permission":"production:create","paginates":false},+ {"name":"production_createJobMaterial","classification":"WRITE","schema":"92eaf1e6fefe","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperation","classification":"WRITE","schema":"7753bcafccc4","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperationParameter","classification":"WRITE","schema":"fd33201b6404","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperationStep","classification":"WRITE","schema":"47d8a0a8b0c2","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperationStepSlide","classification":"WRITE","schema":"4c0b7fbb41fe","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobOperationTool","classification":"WRITE","schema":"b4ca2f2a0605","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createJobs","classification":"WRITE","schema":"d12e26631b3e","response":"267b4780c1d3","permission":"production:create","paginates":false},+ {"name":"production_createMaintenanceDispatchComment","classification":"WRITE","schema":"a60a4f3b168c","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createMaintenanceDispatchEvent","classification":"WRITE","schema":"7d6ca995370a","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createMaintenanceDispatchItem","classification":"WRITE","schema":"640f1f8d4c72","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createMaintenanceSchedule","classification":"WRITE","schema":"8eff562c345b","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createProcedure","classification":"WRITE","schema":"982607cc15a9","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createProcedureParameter","classification":"WRITE","schema":"b8944df35a73","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createProcedureStep","classification":"WRITE","schema":"8e350b1c98b9","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createProductionEvent","classification":"WRITE","schema":"d55db96dfe94","response":"acb6e3edad0f","permission":"production:create","paginates":false},+ {"name":"production_createProductionQuantity","classification":"WRITE","schema":"aeaea19fd65e","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_createScrapReason","classification":"WRITE","schema":"d73822329fe1","response":"8394fbabd845","permission":"production:create","paginates":false},+ {"name":"production_deleteAssemblyComponentMapping","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstruction","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstructionStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstructionStepMaterial","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstructionStepSlide","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyInstructionStepTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblySubAssembly","classification":"DESTRUCTIVE","schema":"bffc08aa14a9","response":"none","permission":"production:delete","paginates":false},+ {"name":"production_deleteAssemblyUnit","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteFailureMode","classification":"DESTRUCTIVE","schema":"2557649b1a5e","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobMaterial","classification":"DESTRUCTIVE","schema":"c8cc308934ba","response":"3797626bd17e","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperation","classification":"DESTRUCTIVE","schema":"c8cc308934ba","response":"3797626bd17e","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperationParameter","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperationStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperationStepSlide","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobOperationTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteJobs","classification":"DESTRUCTIVE","schema":"0eb0c2be01ed","response":"0eb0c2be01ed","permission":"production:delete","paginates":false},+ {"name":"production_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","schema":"74a8a528c9d8","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteMaintenanceDispatchEvent","classification":"DESTRUCTIVE","schema":"8dc062233861","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","schema":"093d449cdac0","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProcedure","classification":"DESTRUCTIVE","schema":"0392041512ee","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProcedureParameter","classification":"DESTRUCTIVE","schema":"c91ee8fbe23a","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProcedureStep","classification":"DESTRUCTIVE","schema":"58f4f51fca4d","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProductionEvent","classification":"DESTRUCTIVE","schema":"b8e23d6f34f4","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteProductionQuantity","classification":"DESTRUCTIVE","schema":"2808b0bf7a67","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_deleteScrapReason","classification":"DESTRUCTIVE","schema":"d925769fba07","response":"bcde375ebd4c","permission":"production:delete","paginates":false},+ {"name":"production_dismissProductionPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"2a69a1e7d58b","permission":"production:update","paginates":false},+ {"name":"production_duplicateJobOperationStep","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_generateAssemblySteps","classification":"DESTRUCTIVE","schema":"47b83ea765a6","response":"ce107c5cf849","permission":"production:update","paginates":false},+ {"name":"production_getActiveEmployeeAbilities","classification":"READ","schema":"31b84d65b2ac","response":"123f68c94eac","permission":"production:view","paginates":false},+ {"name":"production_getActiveJobOperationByJobId","classification":"READ","schema":"ca49bc65b712","response":"d1d76189e471","permission":"production:view","paginates":false},+ {"name":"production_getActiveJobOperationsByLocation","classification":"READ","schema":"98cf602352a0","response":"a3fa2c06d591","permission":"production:view","paginates":false},+ {"name":"production_getActiveProductionEvents","classification":"READ","schema":"31b84d65b2ac","response":"9d447facd100","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyComponentMappings","classification":"READ","schema":"dfce1b9bc52e","response":"da74e5f4208a","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstruction","classification":"READ","schema":"7f8214d1083f","response":"4080592cc20d","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructions","classification":"READ","schema":"ad4033782f45","response":"79381095f84d","permission":"production:view","paginates":true},+ {"name":"production_getAssemblyInstructionsForItem","classification":"READ","schema":"30ab89ff5be9","response":"89a844d50556","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionStepMaterials","classification":"READ","schema":"c478d26d5ff3","response":"89a5f52bebf8","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionSteps","classification":"READ","schema":"bb717127b6f6","response":"c63a220ac834","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionStepSlides","classification":"READ","schema":"c478d26d5ff3","response":"60aa9b57a118","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionStepTools","classification":"READ","schema":"c478d26d5ff3","response":"d771814f7578","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyInstructionVersions","classification":"READ","schema":"f58b3e337974","response":"d6491c78edc9","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyPlanJson","classification":"READ","schema":"dfce1b9bc52e","response":"5708d3b25e58","permission":"production:view","paginates":false},+ {"name":"production_getAssemblyUnits","classification":"READ","schema":"dfce1b9bc52e","response":"7224ef8546c1","permission":"production:view","paginates":false},+ {"name":"production_getBatchableOperations","classification":"READ","schema":"45d95a2d3af4","response":"1c2a1e7a3a05","permission":"production:view","paginates":false},+ {"name":"production_getBatchableProcesses","classification":"READ","schema":"31b84d65b2ac","response":"b0ab8957f96e","permission":"production:view","paginates":false},+ {"name":"production_getBatchOutputLots","classification":"READ","schema":"1a62d6c430a5","response":"7783e113d7a1","permission":"production:view","paginates":false},+ {"name":"production_getCapacityReservationsForResources","classification":"READ","schema":"c113bbf3734f","response":"a491299c2657","permission":"production:view","paginates":false},+ {"name":"production_getCompletionJobs","classification":"READ","schema":"a7b47bee6c23","response":"7bef4749f130","permission":"production:view","paginates":false},+ {"name":"production_getDemandProjections","classification":"READ","schema":"1f5f7428664d","response":"f963e0e91868","permission":"production:view","paginates":false},+ {"name":"production_getFailureMode","classification":"READ","schema":"2557649b1a5e","response":"412854326fc3","permission":"production:view","paginates":false},+ {"name":"production_getFailureModes","classification":"READ","schema":"e2389bb135b5","response":"b5d9b684eccd","permission":"production:view","paginates":true},+ {"name":"production_getFailureModesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"production:view","paginates":false},+ {"name":"production_getFlattenedBomMaterials","classification":"READ","schema":"30ab89ff5be9","response":"7f3fb0d1aeb3","permission":"production:view","paginates":false},+ {"name":"production_getJob","classification":"READ","schema":"7f8214d1083f","response":"30608e61a4dd","permission":"production:view","paginates":false},+ {"name":"production_getJobByOperationId","classification":"READ","schema":"3561ad8e0d42","response":"07382c86b3b8","permission":"production:view","paginates":false},+ {"name":"production_getJobDocuments","classification":"READ","schema":"39628e1613b1","response":"5483e69d7515","permission":"production:view","paginates":false},+ {"name":"production_getJobDocumentsWithItemId","classification":"READ","schema":"655ace094495","response":"5483e69d7515","permission":"production:view","paginates":false},+ {"name":"production_getJobExpediteForecast","classification":"READ","schema":"ca49bc65b712","response":"d377dc3a1fd5","permission":"production:view","paginates":false},+ {"name":"production_getJobMakeMethodById","classification":"READ","schema":"7679db37b5f9","response":"ec2dc329264c","permission":"production:view","paginates":false},+ {"name":"production_getJobMaterialItemIds","classification":"READ","schema":"ca49bc65b712","response":"32068a500dfe","permission":"production:view","paginates":false},+ {"name":"production_getJobMaterialsByMethodId","classification":"READ","schema":"7679db37b5f9","response":"f2854a3bd7f8","permission":"production:view","paginates":false},+ {"name":"production_getJobMaterialsWithQuantityOnHand","classification":"READ","schema":"7f300608525e","response":"839ec8fc28ff","permission":"production:view","paginates":false},+ {"name":"production_getJobMethodTree","classification":"READ","schema":"ca49bc65b712","response":"b65b4600c0ec","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationAttachments","classification":"READ","schema":"cf62af6a7d5a","response":"9a8b9c571a6b","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationBatches","classification":"READ","schema":"e2389bb135b5","response":"505156d91e5d","permission":"production:view","paginates":true},+ {"name":"production_getJobOperationBatchEvents","classification":"READ","schema":"1a62d6c430a5","response":"031cdafdafbd","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationBatchMembers","classification":"READ","schema":"d429e4a46057","response":"66bcdc105c00","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationBatchMemberStats","classification":"READ","schema":"d429e4a46057","response":"03aaee65a70b","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationBatchWithMembers","classification":"READ","schema":"1a62d6c430a5","response":"520bac578dba","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationDependencies","classification":"READ","schema":"ca49bc65b712","response":"9214ed6d51dd","permission":"production:view","paginates":false},+ {"name":"production_getJobOperations","classification":"READ","schema":"3df622256c30","response":"7f24f7881568","permission":"production:view","paginates":true},+ {"name":"production_getJobOperationsByMethodId","classification":"READ","schema":"7679db37b5f9","response":"db1f7927f373","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationsList","classification":"READ","schema":"ca49bc65b712","response":"4e5425835530","permission":"production:view","paginates":false},+ {"name":"production_getJobOperationStepRecords","classification":"READ","schema":"3df622256c30","response":"7bd4e5876d03","permission":"production:view","paginates":true},+ {"name":"production_getJobOrderStatusMap","classification":"READ","schema":"cc93d4900988","response":"5a380f81ad00","permission":"production:view","paginates":false},+ {"name":"production_getJobPurchaseOrderLines","classification":"READ","schema":"ca49bc65b712","response":"f0dff75b384d","permission":"production:view","paginates":false},+ {"name":"production_getJobReceiptSnapshot","classification":"READ","schema":"ca49bc65b712","response":"60e9609498b0","permission":"production:view","paginates":false},+ {"name":"production_getJobReleaseReadiness","classification":"READ","schema":"bd58e48cf49b","response":"2a2deafa81ab","permission":"production:view","paginates":false},+ {"name":"production_getJobs","classification":"READ","schema":"e2389bb135b5","response":"418c2732d3b9","permission":"production:view","paginates":true},+ {"name":"production_getJobsByDateRange","classification":"READ","schema":"c4a3c6cdab79","response":"94688560d7de","permission":"production:view","paginates":false},+ {"name":"production_getJobsBySalesOrderLine","classification":"READ","schema":"fbe78064dbd7","response":"70526fffc19e","permission":"production:view","paginates":false},+ {"name":"production_getJobsList","classification":"READ","schema":"c47cc3e0c427","response":"232ee7305e73","permission":"production:view","paginates":false},+ {"name":"production_getLatestAssemblyPlanJob","classification":"READ","schema":"dfce1b9bc52e","response":"50ae0e7e58d9","permission":"production:view","paginates":false},+ {"name":"production_getLocationEmployees","classification":"READ","schema":"75b90f67d533","response":"72ccccdcfc21","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDispatch","classification":"READ","schema":"74a8a528c9d8","response":"df5a8ae945c2","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDispatchComments","classification":"READ","schema":"74a8a528c9d8","response":"7df6d6b7ba88","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDispatchEvents","classification":"READ","schema":"74a8a528c9d8","response":"fc0af15629d8","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDispatchItems","classification":"READ","schema":"74a8a528c9d8","response":"7d22c1b8235d","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDowntimeForResources","classification":"READ","schema":"74adac8c0e6d","response":"c9ce440846e1","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceSchedule","classification":"READ","schema":"093d449cdac0","response":"2ea53f4f72d0","permission":"production:view","paginates":false},+ {"name":"production_getOutsideOperationsByJobId","classification":"READ","schema":"ca49bc65b712","response":"b75ab9ed0211","permission":"production:view","paginates":false},+ {"name":"production_getPeopleAbsences","classification":"READ","schema":"be8ac1c6fb6c","response":"f98df1954626","permission":"production:view","paginates":false},+ {"name":"production_getPeopleAbsencesRange","classification":"READ","schema":"1474d371d593","response":"90f4a38d3460","permission":"production:view","paginates":false},+ {"name":"production_getPeopleAssignments","classification":"READ","schema":"b8f638bb77e8","response":"6bf01853c73a","permission":"production:view","paginates":false},+ {"name":"production_getPeopleAssignmentsRange","classification":"READ","schema":"c4a3c6cdab79","response":"ba9f9d495de9","permission":"production:view","paginates":false},+ {"name":"production_getPeopleCapacityOperations","classification":"READ","schema":"60e910dcc131","response":"9bbc101347c4","permission":"production:view","paginates":false},+ {"name":"production_getProcedure","classification":"READ","schema":"7f8214d1083f","response":"034de4441d04","permission":"production:view","paginates":false},+ {"name":"production_getProcedures","classification":"READ","schema":"e2389bb135b5","response":"419cf56f7e7d","permission":"production:view","paginates":true},+ {"name":"production_getProceduresList","classification":"READ","schema":"31b84d65b2ac","response":"fe6a24448aaa","permission":"production:view","paginates":false},+ {"name":"production_getProcedureVersions","classification":"READ","schema":"b6064496c216","response":"eb2d49754db3","permission":"production:view","paginates":false},+ {"name":"production_getProductionDataByOperations","classification":"READ","schema":"cf62af6a7d5a","response":"59e4b3d639e6","permission":"production:view","paginates":false},+ {"name":"production_getProductionEvent","classification":"READ","schema":"7f8214d1083f","response":"d9f9d9fcef6a","permission":"production:view","paginates":false},+ {"name":"production_getProductionEvents","classification":"READ","schema":"3cc406b67375","response":"6a1dd7219526","permission":"production:view","paginates":true},+ {"name":"production_getProductionPlanning","classification":"READ","schema":"cffbfff1a7d6","response":"f537e33d5ca9","permission":"production:view","paginates":true},+ {"name":"production_getProductionProjections","classification":"READ","schema":"db561804dc3a","response":"9d7a2b5ba76f","permission":"production:view","paginates":true},+ {"name":"production_getProductionQuantities","classification":"READ","schema":"3cc406b67375","response":"3328b61208d3","permission":"production:view","paginates":true},+ {"name":"production_getProductionQuantity","classification":"READ","schema":"7f8214d1083f","response":"8d4e9959e193","permission":"production:view","paginates":false},+ {"name":"production_getRootMakeMethod","classification":"READ","schema":"ca49bc65b712","response":"ec2dc329264c","permission":"production:view","paginates":false},+ {"name":"production_getScrapReason","classification":"READ","schema":"d925769fba07","response":"4bbb50609deb","permission":"production:view","paginates":false},+ {"name":"production_getScrapReasons","classification":"READ","schema":"e2389bb135b5","response":"254774c57849","permission":"production:view","paginates":true},+ {"name":"production_getScrapReasonsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"production:view","paginates":false},+ {"name":"production_getTrackedEntitiesByJobId","classification":"READ","schema":"ca49bc65b712","response":"ec54684c77fb","permission":"production:view","paginates":false},+ {"name":"production_getTrackedEntityByJobId","classification":"READ","schema":"ca49bc65b712","response":"1007059c8406","permission":"production:view","paginates":false},+ {"name":"production_getUnbatchedBatchableOperationCount","classification":"READ","schema":"31b84d65b2ac","response":"683e4ed05232","permission":"production:view","paginates":false},+ {"name":"production_getUnscheduledJobs","classification":"READ","schema":"75b90f67d533","response":"eb77a38acf19","permission":"production:view","paginates":false},+ {"name":"production_getWorkCenterRequiredAbilities","classification":"READ","schema":"75b90f67d533","response":"7418ea1fc0a7","permission":"production:view","paginates":false},+ {"name":"production_getWorkCenterReservationsRange","classification":"READ","schema":"c310a7ca038d","response":"a7e9bc09d2ab","permission":"production:view","paginates":false},+ {"name":"production_getWorkCenterShifts","classification":"READ","schema":"ef138c43c92c","response":"2b4835f80e6c","permission":"production:view","paginates":false},+ {"name":"production_insertAssemblyInstructionStep","classification":"WRITE","schema":"bf4512d170cc","response":"00404e686415","permission":"production:create","paginates":false},+ {"name":"production_insertJob","classification":"WRITE","schema":"f450754aacd3","response":"ad63dfd9d877","permission":"production:create","paginates":false},+ {"name":"production_makeAssemblySubAssembly","classification":"WRITE","schema":"bd69d909a2e4","response":"00404e686415","permission":"production:update","paginates":false},+ {"name":"production_mapAssemblyComponent","classification":"WRITE","schema":"4b0e8ad9fe70","response":"3189c67145d5","permission":"production:update","paginates":false},+ {"name":"production_markPersonAbsent","classification":"WRITE","schema":"16a1cd418a2e","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_markPersonAbsentRange","classification":"WRITE","schema":"d83feea8f8c7","response":"9859df3143fe","permission":"production:update","paginates":false},+ {"name":"production_matchAssemblyBom","classification":"WRITE","schema":"3797626bd17e","response":"7d2129b72e71","permission":"production:update","paginates":false},+ {"name":"production_mergeBatchOutputs","classification":"WRITE","schema":"49385ebfc807","response":"305ef06ceb72","permission":"production:update","paginates":false},+ {"name":"production_movePerson","classification":"WRITE","schema":"a726aa587ccc","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_movePersonWeek","classification":"WRITE","schema":"c790955c93cc","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_moveScheduleJob","classification":"WRITE","schema":"6e18ba72229f","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_notifyScheduleInputsChanged","classification":"WRITE","schema":"a2cb3b753e9c","response":"b520ca8e3ab4","permission":"production:update","paginates":false},+ {"name":"production_orderPlannedJobs","classification":"WRITE","schema":"145543a6765b","response":"2519eb8f6e46","permission":"production:create","paginates":false},+ {"name":"production_pauseJob","classification":"WRITE","schema":"4999bd4be598","response":"64aaffa78287","permission":"production:update","paginates":false},+ {"name":"production_planJobFromPlanning","classification":"WRITE","schema":"863c89f4ad8e","response":"8e58a21e4c94","permission":"production:update","paginates":false},+ {"name":"production_reassignAssemblyComponents","classification":"DESTRUCTIVE","schema":"71d135315dea","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_recalculateJobRequirements","classification":"WRITE","schema":"7f8214d1083f","response":"9e056a59d695","permission":"production:update","paginates":false},+ {"name":"production_reconvertAssemblyModel","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"277f7d872d8c","permission":"production:update","paginates":false},+ {"name":"production_releaseBatches","classification":"WRITE","schema":"cdc90750ed35","response":"3c7bc982eae0","permission":"production:update","paginates":false},+ {"name":"production_releaseJobs","classification":"WRITE","schema":"9d50f93189c8","response":"9655f6ea4d0d","permission":"production:update","paginates":false},+ {"name":"production_reopenJob","classification":"WRITE","schema":"4999bd4be598","response":"64aaffa78287","permission":"production:update","paginates":false},+ {"name":"production_reopenProductionPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"2a69a1e7d58b","permission":"production:update","paginates":false},+ {"name":"production_reorderJobOperations","classification":"WRITE","schema":"c25fc63725f5","response":"4999bd4be598","permission":"production:update","paginates":false},+ {"name":"production_reorderScheduleOperations","classification":"WRITE","schema":"6c26805d2cdb","response":"2ad56d1b8c6e","permission":"production:update","paginates":false},+ {"name":"production_replanAssembly","classification":"WRITE","schema":"6e2c068fb7ee","response":"03b7f8cb8bd5","permission":"production:update","paginates":false},+ {"name":"production_reprioritizeBatch","classification":"WRITE","schema":"fac2b7e1e76b","response":"979f64cb9229","permission":"production:update","paginates":false},+ {"name":"production_resumeJob","classification":"WRITE","schema":"4999bd4be598","response":"64aaffa78287","permission":"production:update","paginates":false},+ {"name":"production_runMRP","classification":"WRITE","schema":"20590ee6ce3b","response":"9e056a59d695","permission":"inventory:update","paginates":false},+ {"name":"production_setAssemblyStepComponents","classification":"WRITE","schema":"1a4ba7a541ab","response":"e3fc07878bc9","permission":"production:update","paginates":false},+ {"name":"production_setJobDeadline","classification":"WRITE","schema":"e616bfea48ce","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setJobFields","classification":"WRITE","schema":"ed7f018b035c","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setJobItem","classification":"WRITE","schema":"8d049fdf053e","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setJobMaterialStepLink","classification":"DESTRUCTIVE","schema":"58cc0a5390d5","response":"bcde375ebd4c","permission":"production:update","paginates":false},+ {"name":"production_setJobOperationDueDate","classification":"WRITE","schema":"e04478fc58f7","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_setJobOperationStatus","classification":"WRITE","schema":"c7c4e9005478","response":"a443ac9aa1f1","permission":"production:update","paginates":false},+ {"name":"production_setJobOperationToolStepLink","classification":"DESTRUCTIVE","schema":"b48f94032fe6","response":"bcde375ebd4c","permission":"production:update","paginates":false},+ {"name":"production_setJobQuantity","classification":"WRITE","schema":"14db87743cc7","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setJobSalesOrderLine","classification":"WRITE","schema":"9b91d34f8382","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_setPeopleOvertime","classification":"WRITE","schema":"89851b04ba54","response":"393a0d83325c","permission":"production:update","paginates":false},+ {"name":"production_setPersonDay","classification":"WRITE","schema":"b2bcad277f44","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_setPersonHours","classification":"WRITE","schema":"c99328071885","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_setProcedureFields","classification":"WRITE","schema":"e76f126b5b16","response":"0eb0c2be01ed","permission":"production:update","paginates":false},+ {"name":"production_syncAssemblyToOperation","classification":"DESTRUCTIVE","schema":"da43bcac38a0","response":"4348d3bad80b","permission":"production:update","paginates":false},+ {"name":"production_syncJobOperationProcedure","classification":"WRITE","schema":"4db296880a62","response":"c407a9edb930","permission":"production:update","paginates":false},+ {"name":"production_unassignPerson","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_unassignPersonWeek","classification":"DESTRUCTIVE","schema":"890a7a5b9f83","response":"3d90cb5d0437","permission":"production:update","paginates":false},+ {"name":"production_ungroupAssemblySubAssembly","classification":"DESTRUCTIVE","schema":"bffc08aa14a9","response":"none","permission":"production:update","paginates":false},+ {"name":"production_unreleaseBatch","classification":"WRITE","schema":"979f64cb9229","response":"979f64cb9229","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStatus","classification":"WRITE","schema":"8bc986702703","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepMaterialOrder","classification":"WRITE","schema":"cbc4567c4881","response":"none","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepOrder","classification":"WRITE","schema":"c46e7002c837","response":"none","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepSlide","classification":"WRITE","schema":"c5583b5b9e1f","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyInstructionStepStatus","classification":"WRITE","schema":"aa7e8ba34a64","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyStepHiddenComponents","classification":"WRITE","schema":"e76e43cb8530","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblyStepMotion","classification":"WRITE","schema":"c70122f65e35","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateAssemblySubAssembly","classification":"WRITE","schema":"c5f26f0d922a","response":"none","permission":"production:update","paginates":false},+ {"name":"production_updateBatch","classification":"WRITE","schema":"c54fb480a6d1","response":"979f64cb9229","permission":"production:update","paginates":false},+ {"name":"production_updateFailureMode","classification":"WRITE","schema":"5f39e7b61b61","response":"8394fbabd845","permission":"production:update","paginates":false},+ {"name":"production_updateJobBatchNumber","classification":"WRITE","schema":"6e1e7ec3a9f5","response":"f7a40899c090","permission":"production:update","paginates":false},+ {"name":"production_updateJobDetails","classification":"WRITE","schema":"bcbce6ae7798","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateJobMaterial","classification":"WRITE","schema":"92eaf1e6fefe","response":"4ea32bd70246","permission":"production:create","paginates":false},+ {"name":"production_updateJobMaterialOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"60cd1f553572","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperation","classification":"WRITE","schema":"7753bcafccc4","response":"3797626bd17e","permission":"production:create","paginates":false},+ {"name":"production_updateJobOperationParameter","classification":"WRITE","schema":"3d26db99a28d","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationStep","classification":"WRITE","schema":"4ba3e76e5486","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationStepOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationStepSlide","classification":"WRITE","schema":"c5583b5b9e1f","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationTool","classification":"WRITE","schema":"e41cd4d18607","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateKanbanJob","classification":"WRITE","schema":"9c2f9da91736","response":"bcde375ebd4c","permission":"production:update","paginates":false},+ {"name":"production_updateMaintenanceDispatchComment","classification":"WRITE","schema":"9381cafe0efa","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateMaintenanceDispatchEvent","classification":"WRITE","schema":"e697a79e9889","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateMaintenanceDispatchItem","classification":"WRITE","schema":"871ab6aba5a8","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateMaintenanceSchedule","classification":"WRITE","schema":"a629cde039f7","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateMethodOperationStepOrder","classification":"WRITE","schema":"4289859b65d6","response":"c407a9edb930","permission":"none","paginates":false},+ {"name":"production_updatePlannedJob","classification":"WRITE","schema":"36a2dd1a51c5","response":"8e58a21e4c94","permission":"production:update","paginates":false},+ {"name":"production_updateProcedure","classification":"WRITE","schema":"86f83e2e1ab3","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateProcedureParameter","classification":"WRITE","schema":"3eb1ccdb1dc5","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateProcedureStep","classification":"WRITE","schema":"f6868b377bd0","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_updateProcedureStepOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"production:update","paginates":false},+ {"name":"production_updateProductionEvent","classification":"WRITE","schema":"5ae7126208e7","response":"acb6e3edad0f","permission":"production:update","paginates":false},+ {"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","schema":"4289859b65d6","response":"c407a9edb930","permission":"none","paginates":false},+ {"name":"production_updateScrapReason","classification":"WRITE","schema":"5f39e7b61b61","response":"8394fbabd845","permission":"production:update","paginates":false},+ {"name":"production_upsertAssemblyInstruction","classification":"WRITE","schema":"140b31338c4e","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","schema":"69932a4f176d","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyInstructionStepMaterial","classification":"WRITE","schema":"cec21b948809","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyInstructionStepTool","classification":"WRITE","schema":"f7254eb12e98","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertAssemblyUnit","classification":"WRITE","schema":"6755e4574f31","response":"3797626bd17e","permission":"production:create+update","paginates":false},+ {"name":"production_upsertMakeMethodFromJob","classification":"DESTRUCTIVE","schema":"32b3a0f5efa0","response":"4e1a8f1febce","permission":"none","paginates":false},+ {"name":"production_upsertMakeMethodFromJobMethod","classification":"DESTRUCTIVE","schema":"32b3a0f5efa0","response":"bcde375ebd4c","permission":"none","paginates":false},+ {"name":"purchasing_activateLease","classification":"WRITE","schema":"9fb51372ff53","response":"9fb51372ff53","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_addReturnOrderLine","classification":"WRITE","schema":"64ba603aba2d","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_applyPlanningActions","classification":"WRITE","schema":"97c5a5a85a8d","response":"1fcb7549b33d","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_assignPurchasingPlanningActions","classification":"WRITE","schema":"a18b4088f112","response":"fb4223d67640","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_cancelLease","classification":"DESTRUCTIVE","schema":"9fb51372ff53","response":"9fb51372ff53","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_cancelPurchasingRfq","classification":"DESTRUCTIVE","schema":"9531e4360acd","response":"9531e4360acd","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_cancelReturnOrder","classification":"DESTRUCTIVE","schema":"11b028f16d94","response":"11b028f16d94","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_closePurchaseOrderAndApprovals","classification":"DESTRUCTIVE","schema":"28cffcd9d6e8","response":"28cffcd9d6e8","permission":"purchasing:delete+update","paginates":false},+ {"name":"purchasing_confirmReturnOrder","classification":"WRITE","schema":"e4d2372c370b","response":"bd154a7a199c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_convertSupplierQuoteToOrder","classification":"WRITE","schema":"ed4c93e2b28c","response":"873673b16fc8","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_createPurchaseOrderLine","classification":"WRITE","schema":"3cd5255bcf67","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createPurchaseReturnOrderCredit","classification":"WRITE","schema":"71e626ec2145","response":"00404e686415","permission":"invoicing:create","paginates":false},+ {"name":"purchasing_createPurchasingRfq","classification":"WRITE","schema":"6c41ec826827","response":"0c1a1b93cca3","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createPurchasingRFQLine","classification":"WRITE","schema":"5fa277599ba0","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createReplacementPurchaseOrder","classification":"WRITE","schema":"ceebeb4f9cac","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplier","classification":"WRITE","schema":"3741922f8489","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierBankAccount","classification":"WRITE","schema":"efd1d70f5843","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"purchasing_createSupplierInteractionDocumentUploadUrl","classification":"WRITE","schema":"a1e758f60479","response":"4ad76afe0777","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierInteractionLineDocumentUploadUrl","classification":"WRITE","schema":"89370e60a3e7","response":"4ad76afe0777","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierProcess","classification":"WRITE","schema":"6cc767af67ff","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierQuoteLine","classification":"WRITE","schema":"3c3ef5a7c489","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_createSupplierType","classification":"WRITE","schema":"d73822329fe1","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_deactivateSupplier","classification":"DESTRUCTIVE","schema":"67043a31b1b5","response":"67043a31b1b5","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_decidePurchaseOrderApproval","classification":"WRITE","schema":"03b37ea9315e","response":"5d541df0c1a6","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_decideSupplierApproval","classification":"WRITE","schema":"7fc37bfd72cb","response":"3420a9ad965d","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_deleteLease","classification":"DESTRUCTIVE","schema":"dc3a69d0ccf7","response":"8394fbabd845","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteLeaseLine","classification":"DESTRUCTIVE","schema":"2cf0099ceecf","response":"8394fbabd845","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteLeasePayment","classification":"DESTRUCTIVE","schema":"08b90ec76499","response":"8394fbabd845","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchaseOrderLine","classification":"DESTRUCTIVE","schema":"555dd21fcbd0","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchaseOrders","classification":"DESTRUCTIVE","schema":"56451bca9438","response":"56451bca9438","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchaseReturnOrder","classification":"DESTRUCTIVE","schema":"ceebeb4f9cac","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchaseReturnOrderLine","classification":"DESTRUCTIVE","schema":"e2b1df794940","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchasingRFQ","classification":"DESTRUCTIVE","schema":"a03ea9b74e8a","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deletePurchasingRFQLine","classification":"DESTRUCTIVE","schema":"79a5f4500bbf","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplier","classification":"DESTRUCTIVE","schema":"47ea6a43aa68","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierBankAccount","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"purchasing_deleteSupplierContact","classification":"DESTRUCTIVE","schema":"aa6e2dd10410","response":"700b93baa3ef","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierLocation","classification":"DESTRUCTIVE","schema":"4c735b01a149","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierProcess","classification":"DESTRUCTIVE","schema":"aac871c2c83c","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierQuote","classification":"DESTRUCTIVE","schema":"bb086c35d51f","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierQuoteLine","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_deleteSupplierType","classification":"DESTRUCTIVE","schema":"c798505e510b","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},+ {"name":"purchasing_dismissPurchasingPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"fb4223d67640","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_duplicatePurchaseOrder","classification":"WRITE","schema":"95bc69935968","response":"f5212679d580","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_finalizePurchaseOrderAndNotify","classification":"WRITE","schema":"9f1cc7c6b5b5","response":"309570ef92a9","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_finalizePurchasingRfqAndNotify","classification":"WRITE","schema":"8bb952a2b85c","response":"094107e7128f","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_finalizeSupplierQuoteWithLink","classification":"WRITE","schema":"5db39f9abf41","response":"5db39f9abf41","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_getCreditableQuantitiesForPurchaseReturn","classification":"READ","schema":"ceebeb4f9cac","response":"1e97e6c72b1d","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getDefaultAttachmentsForPO","classification":"READ","schema":"9474713c78d5","response":"6568f0b88496","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLease","classification":"READ","schema":"dc3a69d0ccf7","response":"fc0e61ea3215","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeaseEvents","classification":"READ","schema":"dc3a69d0ccf7","response":"d6ca448f2de1","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeaseLines","classification":"READ","schema":"dc3a69d0ccf7","response":"ac478377b901","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeasePayments","classification":"READ","schema":"dc3a69d0ccf7","response":"e8667e0adeb6","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeaseRelatedDocuments","classification":"READ","schema":"dc3a69d0ccf7","response":"281a385d45a6","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLeases","classification":"READ","schema":"e2389bb135b5","response":"5ea4c94909de","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getLeaseSchedule","classification":"READ","schema":"dc3a69d0ccf7","response":"8c06f01ac6f1","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getLinkedSupplierQuotes","classification":"READ","schema":"a03ea9b74e8a","response":"cb143b1fe761","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrder","classification":"READ","schema":"47850e9f092b","response":"259ccf5593fd","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrderDelivery","classification":"READ","schema":"47850e9f092b","response":"1b814db8a608","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrderLine","classification":"READ","schema":"555dd21fcbd0","response":"d1fd90a42c26","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrderLines","classification":"READ","schema":"47850e9f092b","response":"085f671f872c","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrderPayment","classification":"READ","schema":"47850e9f092b","response":"c7a62e53e09b","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseOrders","classification":"READ","schema":"e30b02013b19","response":"2dc249e54e3c","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getPurchaseReturnOrder","classification":"READ","schema":"ceebeb4f9cac","response":"96bcc73f6a1e","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderCredits","classification":"READ","schema":"ceebeb4f9cac","response":"49639d091139","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderIssues","classification":"READ","schema":"ceebeb4f9cac","response":"a81c998e95a3","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderLine","classification":"READ","schema":"e2b1df794940","response":"6e3bf67c7a97","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderLines","classification":"READ","schema":"ceebeb4f9cac","response":"96a37b74bd9d","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrderLineTrackedEntities","classification":"READ","schema":"72a93572f55f","response":"7c681886c392","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchaseReturnOrders","classification":"READ","schema":"e30b02013b19","response":"248fa6073d74","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getPurchaseReturnOrderShipments","classification":"READ","schema":"ceebeb4f9cac","response":"fcf875f84b9b","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingDocumentsAssignedToMe","classification":"READ","schema":"31b84d65b2ac","response":"da511db6b83a","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingPlanning","classification":"READ","schema":"cffbfff1a7d6","response":"2853f93ce584","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getPurchasingRFQ","classification":"READ","schema":"7f8214d1083f","response":"08cb90c207da","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingRFQLine","classification":"READ","schema":"e2b1df794940","response":"453aec159c67","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingRFQLines","classification":"READ","schema":"a03ea9b74e8a","response":"9507bd698de0","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingRFQs","classification":"READ","schema":"e2389bb135b5","response":"a17f64c1d9c6","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getPurchasingRFQSuppliersWithLinks","classification":"READ","schema":"a03ea9b74e8a","response":"5483e69d7515","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getReturnableEntitiesForSupplier","classification":"READ","schema":"f4032bf993a4","response":"80bf661fb053","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getReturnableLinesForSupplier","classification":"READ","schema":"9ce2623b4864","response":"24dd6c0d1c55","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSiblingQuotesForQuote","classification":"READ","schema":"bb086c35d51f","response":"cb143b1fe761","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplier","classification":"READ","schema":"47ea6a43aa68","response":"e1446596b250","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierBankAccounts","classification":"READ","schema":"47ea6a43aa68","response":"f2b09b60b722","permission":"accounting:view","paginates":false},+ {"name":"purchasing_getSupplierContact","classification":"READ","schema":"23bff787ec5d","response":"6d2aa722b1ce","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierContacts","classification":"READ","schema":"47ea6a43aa68","response":"e28ccbd2c417","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierInteraction","classification":"READ","schema":"1ee597897662","response":"f674b3eb0acb","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierInteractionDocuments","classification":"READ","schema":"a99e7a244595","response":"1c34622130cc","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierInteractionLineDocuments","classification":"READ","schema":"e2b1df794940","response":"1c34622130cc","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierLocation","classification":"READ","schema":"23bff787ec5d","response":"4603d06d1055","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierLocations","classification":"READ","schema":"47ea6a43aa68","response":"6dad1063175d","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierPayment","classification":"READ","schema":"47ea6a43aa68","response":"24b286adf1ff","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierProcessesByProcess","classification":"READ","schema":"5631e53ea64f","response":"c2eb609c8ad1","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierProcessesBySupplier","classification":"READ","schema":"47ea6a43aa68","response":"c2eb609c8ad1","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuote","classification":"READ","schema":"bb086c35d51f","response":"903106f4ab48","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteByExternalLinkId","classification":"READ","schema":"61d80c989426","response":"0276bbe00656","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteLine","classification":"READ","schema":"fe9f25e9881e","response":"8274b1f62041","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteLinePrices","classification":"READ","schema":"fe9f25e9881e","response":"22abc40c4789","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteLinePricesByQuoteId","classification":"READ","schema":"bb086c35d51f","response":"22abc40c4789","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuoteLines","classification":"READ","schema":"bb086c35d51f","response":"fb8d2333a3dc","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierQuotes","classification":"READ","schema":"e2389bb135b5","response":"a8ea39a27fdf","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getSupplierQuotesForComparison","classification":"READ","schema":"a03ea9b74e8a","response":"aa927eec99a0","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierReportContacts","classification":"READ","schema":"4e3d74ecb68e","response":"753cb51d6d41","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSuppliers","classification":"READ","schema":"514c5c4af618","response":"1dd9d01eeb5f","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getSupplierShipping","classification":"READ","schema":"47ea6a43aa68","response":"673f4f400833","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSuppliersList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierTax","classification":"READ","schema":"47ea6a43aa68","response":"89b4ff5c4012","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierType","classification":"READ","schema":"c798505e510b","response":"8b3eca34dbfd","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierTypes","classification":"READ","schema":"e2389bb135b5","response":"e0001a83b60b","permission":"purchasing:view","paginates":true},+ {"name":"purchasing_getSupplierTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_insertLease","classification":"WRITE","schema":"55753efdb84c","response":"f6631a819d19","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertPurchaseOrder","classification":"WRITE","schema":"b7f7ea3824d5","response":"73785d310369","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertPurchaseReturnOrder","classification":"WRITE","schema":"8faa8981ada0","response":"d53d13c89312","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertSupplierContact","classification":"WRITE","schema":"442dcf7c63d4","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertSupplierLocation","classification":"WRITE","schema":"e401ef4fb9c3","response":"3797626bd17e","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertSupplierQuote","classification":"WRITE","schema":"6b9d616bd5ca","response":"77e21c1e2e32","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_modifyLease","classification":"WRITE","schema":"36fa257d377a","response":"9fb51372ff53","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_orderPlannedPurchases","classification":"WRITE","schema":"075bf940d96b","response":"783cfed7484c","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_overrideLeaseLineClassification","classification":"WRITE","schema":"1fe629e754c9","response":"b75a6f5aff44","permission":"accounting:update","paginates":false},+ {"name":"purchasing_purchaseLeaseLine","classification":"WRITE","schema":"38acf7de6118","response":"bb4487ea3e25","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_removeLeaseLineClassificationOverride","classification":"WRITE","schema":"bb4487ea3e25","response":"58ef28d4f5cf","permission":"accounting:update","paginates":false},+ {"name":"purchasing_reopenPurchaseOrder","classification":"WRITE","schema":"ede13800cd39","response":"e703c553a33e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_reopenPurchasingPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"fb4223d67640","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_reopenReturnOrder","classification":"WRITE","schema":"11b028f16d94","response":"11b028f16d94","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_requestSupplierApproval","classification":"WRITE","schema":"67043a31b1b5","response":"67043a31b1b5","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_sendSupplierQuoteToSupplier","classification":"WRITE","schema":"216a3e92c06c","response":"5db39f9abf41","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_shortClosePurchaseOrderLine","classification":"WRITE","schema":"de3ac14cd9f4","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_shortClosePurchaseReturnOrderLine","classification":"WRITE","schema":"2a627b0c4264","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_terminateLeaseLine","classification":"DESTRUCTIVE","schema":"cb77a6b7f416","response":"bb4487ea3e25","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateLeaseDetails","classification":"WRITE","schema":"58766088a3e6","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePlanningPurchaseOrderLine","classification":"WRITE","schema":"f9f036f80ca3","response":"2d9389fd413d","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrder","classification":"WRITE","schema":"be711f3a1c77","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderFavorite","classification":"DESTRUCTIVE","schema":"ff73dc321969","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderLine","classification":"WRITE","schema":"dcf7f1d780b9","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrderLineOrder","classification":"WRITE","schema":"33aad0d0c2bb","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchaseOrders","classification":"WRITE","schema":"c182f3099a0b","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchasingRFQLine","classification":"WRITE","schema":"886a79ee22a8","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchasingRFQLineOrder","classification":"WRITE","schema":"913042cdd55f","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchasingRfqs","classification":"WRITE","schema":"e7babf8c0f84","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updatePurchasingRFQStatus","classification":"WRITE","schema":"947842502cae","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateReturnOrderLine","classification":"WRITE","schema":"390645da3aea","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateReturnOrders","classification":"WRITE","schema":"98f12a4ce2ea","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplier","classification":"WRITE","schema":"a82f06ad0009","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierBankAccount","classification":"WRITE","schema":"70825efb56db","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"purchasing_updateSupplierContact","classification":"WRITE","schema":"327a6ef8e7b5","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierLocation","classification":"WRITE","schema":"6afc03cf515f","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierPayment","classification":"WRITE","schema":"35582b0e7de4","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierProcess","classification":"WRITE","schema":"4721221813f2","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuote","classification":"WRITE","schema":"b775ec1375c3","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuoteExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuoteLine","classification":"WRITE","schema":"4a8f2e55ede3","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuoteLineOrder","classification":"WRITE","schema":"248d2ba4c421","response":"none","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuotes","classification":"WRITE","schema":"aee40ae8e095","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierQuoteStatus","classification":"WRITE","schema":"b6ed6e3f17e0","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierShipping","classification":"WRITE","schema":"4da28c918b78","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierTax","classification":"WRITE","schema":"fc0cfcd24aeb","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_updateSupplierType","classification":"WRITE","schema":"5f39e7b61b61","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_upsertLeasePayment","classification":"WRITE","schema":"c0ed999b5813","response":"3797626bd17e","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_upsertPurchaseOrderDelivery","classification":"WRITE","schema":"8bdd908f85bd","response":"3797626bd17e","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchaseOrderPayment","classification":"WRITE","schema":"a4b89c399504","response":"3797626bd17e","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchasingRFQ","classification":"WRITE","schema":"56cc1ae7fa75","response":"3797626bd17e","permission":"purchasing:create+update","paginates":false},+ {"name":"purchasing_upsertPurchasingRFQSuppliers","classification":"DESTRUCTIVE","schema":"769394a6f909","response":"5c9ba5bee3f1","permission":"purchasing:create+update","paginates":false},+ {"name":"quality_activateGauge","classification":"DESTRUCTIVE","schema":"059138c6b8da","response":"bcde375ebd4c","permission":"quality:delete+update","paginates":false},+ {"name":"quality_completeIssue","classification":"WRITE","schema":"3797626bd17e","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_createGaugeCalibrationRecord","classification":"WRITE","schema":"e6f00ff8a0ad","response":"3797626bd17e","permission":"quality:create","paginates":false},+ {"name":"quality_createGaugeType","classification":"WRITE","schema":"d73822329fe1","response":"8394fbabd845","permission":"quality:create","paginates":false},+ {"name":"quality_createIssue","classification":"WRITE","schema":"98e94090cc53","response":"67030fdab724","permission":"quality:create","paginates":false},+ {"name":"quality_createIssueAssociation","classification":"WRITE","schema":"6abd32611fef","response":"f16bdda80515","permission":"quality:update","paginates":false},+ {"name":"quality_createIssueType","classification":"WRITE","schema":"d73822329fe1","response":"8394fbabd845","permission":"quality:create","paginates":false},+ {"name":"quality_createIssueWorkflow","classification":"WRITE","schema":"6e3cd015f8ad","response":"3797626bd17e","permission":"quality:create","paginates":false},+ {"name":"quality_createQualityDocument","classification":"WRITE","schema":"9ae16f0cc380","response":"3797626bd17e","permission":"quality:create","paginates":false},+ {"name":"quality_createRequiredAction","classification":"WRITE","schema":"b5ff6cf052a3","response":"8394fbabd845","permission":"quality:create","paginates":false},+ {"name":"quality_deactivateGauge","classification":"DESTRUCTIVE","schema":"059138c6b8da","response":"bcde375ebd4c","permission":"quality:delete+update","paginates":false},+ {"name":"quality_decideQualityDocumentApproval","classification":"WRITE","schema":"03770b06d8f1","response":"febf01bee291","permission":"quality:update","paginates":false},+ {"name":"quality_deleteGauge","classification":"DESTRUCTIVE","schema":"059138c6b8da","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteGaugeCalibrationRecord","classification":"DESTRUCTIVE","schema":"4e3f6158526a","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteGaugeType","classification":"DESTRUCTIVE","schema":"f53d2343f254","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteInspectionDocument","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"e92dda062549","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteIssue","classification":"DESTRUCTIVE","schema":"9a315debddd5","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteIssueAssociation","classification":"DESTRUCTIVE","schema":"df77e85ac07f","response":"none","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteIssueType","classification":"DESTRUCTIVE","schema":"8e7960fd6070","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteIssueWorkflow","classification":"DESTRUCTIVE","schema":"85f1fd269377","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteQualityDocument","classification":"DESTRUCTIVE","schema":"3dc73fe900b8","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteRequiredAction","classification":"DESTRUCTIVE","schema":"d65e071deff9","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_deleteRisk","classification":"DESTRUCTIVE","schema":"f1db6acfa864","response":"bcde375ebd4c","permission":"quality:delete","paginates":false},+ {"name":"quality_draftIssueSupplierReturn","classification":"WRITE","schema":"927d79b82bc1","response":"b54823969d01","permission":"purchasing:create","paginates":false},+ {"name":"quality_getBalloons","classification":"READ","schema":"b6a25994639a","response":"3fec0abbc97d","permission":"quality:view","paginates":false},+ {"name":"quality_getGauge","classification":"READ","schema":"059138c6b8da","response":"e991e480f76c","permission":"quality:view","paginates":false},+ {"name":"quality_getGaugeCalibrationRecord","classification":"READ","schema":"7f8214d1083f","response":"2b11fefda0c1","permission":"quality:view","paginates":false},+ {"name":"quality_getGaugeCalibrationRecords","classification":"READ","schema":"e2389bb135b5","response":"3b6339a8e722","permission":"quality:view","paginates":true},+ {"name":"quality_getGaugeCalibrationRecordsByGaugeId","classification":"READ","schema":"059138c6b8da","response":"47dc08537d57","permission":"quality:view","paginates":false},+ {"name":"quality_getGauges","classification":"READ","schema":"e2389bb135b5","response":"ef3b7f672ff5","permission":"quality:view","paginates":true},+ {"name":"quality_getGaugesList","classification":"READ","schema":"31b84d65b2ac","response":"34b9a5801676","permission":"quality:view","paginates":false},+ {"name":"quality_getGaugeType","classification":"READ","schema":"f53d2343f254","response":"63b5b3f8f143","permission":"quality:view","paginates":false},+ {"name":"quality_getGaugeTypes","classification":"READ","schema":"e2389bb135b5","response":"31ad065cdc4a","permission":"quality:view","paginates":true},+ {"name":"quality_getGaugeTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"quality:view","paginates":false},+ {"name":"quality_getInspection","classification":"READ","schema":"7f8214d1083f","response":"none","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionDocument","classification":"READ","schema":"7f8214d1083f","response":"a82889f583de","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionDocuments","classification":"READ","schema":"e2389bb135b5","response":"0daf2106401c","permission":"quality:view","paginates":true},+ {"name":"quality_getInspectionDocumentsForItem","classification":"READ","schema":"30ab89ff5be9","response":"cfa5f1f7b8aa","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionFeatures","classification":"READ","schema":"b6a25994639a","response":"1e8d8f002f21","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionGauges","classification":"READ","schema":"162c842697ab","response":"68597e017f0d","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionMeasurements","classification":"READ","schema":"162c842697ab","response":"c743640a210d","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionPlan","classification":"READ","schema":"b6a25994639a","response":"83a9b3640e41","permission":"quality:view","paginates":false},+ {"name":"quality_getInspections","classification":"READ","schema":"fb4a6c0ab2fb","response":"8c1809e97180","permission":"quality:view","paginates":true},+ {"name":"quality_getInspectionSamplingPlans","classification":"READ","schema":"162c842697ab","response":"fccb92d930f6","permission":"quality:view","paginates":false},+ {"name":"quality_getInspectionTrackedEntities","classification":"READ","schema":"76ee331dd860","response":"ec54684c77fb","permission":"quality:view","paginates":false},+ {"name":"quality_getIssue","classification":"READ","schema":"9a315debddd5","response":"a1e666efa89c","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueActionTasks","classification":"READ","schema":"3c597e8cd46b","response":"7a21aafdb718","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueApprovalTasks","classification":"READ","schema":"7f8214d1083f","response":"c8b12eeadf05","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueAssociations","classification":"READ","schema":"9a315debddd5","response":"ebdefbd901a7","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueFromExternalLink","classification":"READ","schema":"7f8214d1083f","response":"7d8ae32223a1","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueItems","classification":"READ","schema":"7f8214d1083f","response":"8e532cfdc47f","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueReviewers","classification":"READ","schema":"7f8214d1083f","response":"7cfc99a45933","permission":"quality:view","paginates":false},+ {"name":"quality_getIssues","classification":"READ","schema":"e2389bb135b5","response":"37768f573675","permission":"quality:view","paginates":true},+ {"name":"quality_getIssueSuppliers","classification":"READ","schema":"7f8214d1083f","response":"2a7e42e2f8c2","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueType","classification":"READ","schema":"8e7960fd6070","response":"63b5b3f8f143","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueTypeByName","classification":"READ","schema":"3728a862815e","response":"3797626bd17e","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueTypes","classification":"READ","schema":"e2389bb135b5","response":"31ad065cdc4a","permission":"quality:view","paginates":true},+ {"name":"quality_getIssueTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueWorkflow","classification":"READ","schema":"85f1fd269377","response":"f88698228931","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueWorkflows","classification":"READ","schema":"e2389bb135b5","response":"2669c312ddb8","permission":"quality:view","paginates":true},+ {"name":"quality_getIssueWorkflowsList","classification":"READ","schema":"31b84d65b2ac","response":"078f43165541","permission":"quality:view","paginates":false},+ {"name":"quality_getItemInspectionDocumentAssignments","classification":"READ","schema":"30ab89ff5be9","response":"9bedeef9a12b","permission":"quality:view","paginates":false},+ {"name":"quality_getQualityActions","classification":"READ","schema":"e2389bb135b5","response":"5a45675f1097","permission":"quality:view","paginates":true},+ {"name":"quality_getQualityDocument","classification":"READ","schema":"7f8214d1083f","response":"695de208baac","permission":"quality:view","paginates":false},+ {"name":"quality_getQualityDocuments","classification":"READ","schema":"e2389bb135b5","response":"4afca05d1d27","permission":"quality:view","paginates":true},+ {"name":"quality_getQualityDocumentVersions","classification":"READ","schema":"b6064496c216","response":"81dd83c56231","permission":"quality:view","paginates":false},+ {"name":"quality_getQualityFiles","classification":"READ","schema":"7f8214d1083f","response":"6351756c9816","permission":"quality:view","paginates":false},+ {"name":"quality_getReceiptInspections","classification":"READ","schema":"85cf4fd2917f","response":"83d5d10abb6a","permission":"quality:view","paginates":false},+ {"name":"quality_getRequiredAction","classification":"READ","schema":"d65e071deff9","response":"58c7a89fdc1f","permission":"quality:view","paginates":false},+ {"name":"quality_getRequiredActions","classification":"READ","schema":"e2389bb135b5","response":"bb4170f94792","permission":"quality:view","paginates":true},+ {"name":"quality_getRequiredActionsList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"quality:view","paginates":false},+ {"name":"quality_getRisk","classification":"READ","schema":"f1db6acfa864","response":"25996e7756ac","permission":"quality:view","paginates":false},+ {"name":"quality_getRisks","classification":"READ","schema":"31e8d135e01d","response":"97a932a15ee2","permission":"quality:view","paginates":true},+ {"name":"quality_insertGauge","classification":"WRITE","schema":"8d2ada8f5f52","response":"3269d4609ad2","permission":"quality:create","paginates":false},+ {"name":"quality_insertIssue","classification":"WRITE","schema":"ea632d40582e","response":"bf12cbd0f560","permission":"quality:create","paginates":false},+ {"name":"quality_insertIssueReviewer","classification":"WRITE","schema":"83d8aaae61eb","response":"bcde375ebd4c","permission":"quality:create","paginates":false},+ {"name":"quality_rejectInspection","classification":"WRITE","schema":"d7fc4d660b91","response":"c1beaadbde90","permission":"quality:update","paginates":false},+ {"name":"quality_reorderIssueActionTasks","classification":"WRITE","schema":"e27ca9c14dfd","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},+ {"name":"quality_saveInspectionDocument","classification":"WRITE","schema":"ce666421c179","response":"f67a43378af0","permission":"quality:update","paginates":false},+ {"name":"quality_saveInspectionDocumentAtomic","classification":"WRITE","schema":"7a3138ccf220","response":"none","permission":"quality:update","paginates":false},+ {"name":"quality_seedQualityDocuments","classification":"WRITE","schema":"31b84d65b2ac","response":"85c82e9f9d11","permission":"quality:create","paginates":false},+ {"name":"quality_setInspectionDocumentDrawingNumber","classification":"WRITE","schema":"b70d7fc9aa08","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_setIssueActionDueDate","classification":"WRITE","schema":"226732b41ef5","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_setIssueStatus","classification":"WRITE","schema":"1a25bfc1a327","response":"1a25bfc1a327","permission":"quality:update","paginates":false},+ {"name":"quality_setIssueTaskStatus","classification":"WRITE","schema":"4b9a245ad2cf","response":"6857d1b1a4e8","permission":"quality:update","paginates":false},+ {"name":"quality_setIssueTaskSupplier","classification":"WRITE","schema":"b6b0275e1616","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateGauge","classification":"WRITE","schema":"d26a7f29a929","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateGaugeCalibrationRecord","classification":"WRITE","schema":"c9cf47d7d6ec","response":"3797626bd17e","permission":"quality:create+update","paginates":false},+ {"name":"quality_updateGaugeType","classification":"WRITE","schema":"5f39e7b61b61","response":"8394fbabd845","permission":"quality:update","paginates":false},+ {"name":"quality_updateInspectionDocumentSampling","classification":"WRITE","schema":"42714a7976eb","response":"bcde375ebd4c","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssue","classification":"WRITE","schema":"336ea2add45b","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueActionProcesses","classification":"DESTRUCTIVE","schema":"4ddcbb8d1ac6","response":"bcde375ebd4c","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueField","classification":"WRITE","schema":"8712a26ffddc","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueItemField","classification":"WRITE","schema":"32444013b5c4","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueType","classification":"WRITE","schema":"5f39e7b61b61","response":"8394fbabd845","permission":"quality:update","paginates":false},+ {"name":"quality_updateIssueWorkflow","classification":"WRITE","schema":"b2a98a055ad5","response":"3797626bd17e","permission":"quality:create+update","paginates":false},+ {"name":"quality_updateQualityDocument","classification":"WRITE","schema":"3ad25b3f6a84","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_updateQualityDocumentField","classification":"WRITE","schema":"241fb5b89617","response":"0eb0c2be01ed","permission":"quality:update","paginates":false},+ {"name":"quality_updateRequiredAction","classification":"WRITE","schema":"11bbd98a2e05","response":"8394fbabd845","permission":"quality:update","paginates":false},+ {"name":"quality_updateRisk","classification":"WRITE","schema":"059e5e53b44b","response":"3797626bd17e","permission":"quality:update","paginates":false},+ {"name":"quality_upsertInspectionDocument","classification":"WRITE","schema":"11b9bba59419","response":"3797626bd17e","permission":"quality:create+update","paginates":false},+ {"name":"quality_upsertItemInspectionDocumentAssignment","classification":"DESTRUCTIVE","schema":"4948a99b7a53","response":"bcde375ebd4c","permission":"quality:create+update","paginates":false},+ {"name":"resources_activateProcess","classification":"WRITE","schema":"5631e53ea64f","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_addEmployeeAbility","classification":"WRITE","schema":"86a9132fd668","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_createAbility","classification":"WRITE","schema":"df2e6ccff2a4","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createContractor","classification":"DESTRUCTIVE","schema":"a672e282e0cd","response":"bcde375ebd4c","permission":"resources:create","paginates":false},+ {"name":"resources_createFailureMode","classification":"WRITE","schema":"f44233439b1b","response":"8394fbabd845","permission":"resources:create","paginates":false},+ {"name":"resources_createLocation","classification":"WRITE","schema":"140095be5d68","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createMaintenanceDispatch","classification":"WRITE","schema":"629d474dc047","response":"ede36af7307d","permission":"resources:create","paginates":false},+ {"name":"resources_createMaintenanceDispatchComment","classification":"WRITE","schema":"a60a4f3b168c","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createMaintenanceDispatchItem","classification":"WRITE","schema":"bb6dfef16ca0","response":"31c4f3f69c9a","permission":"resources:update","paginates":false},+ {"name":"resources_createMaintenanceEvent","classification":"WRITE","schema":"6e76bd1f09c1","response":"8e58a21e4c94","permission":"resources:update","paginates":false},+ {"name":"resources_createMaintenanceSchedule","classification":"WRITE","schema":"b84710917cca","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createPartner","classification":"WRITE","schema":"63fa7a0fe27d","response":"bcde375ebd4c","permission":"resources:create","paginates":false},+ {"name":"resources_createProcess","classification":"WRITE","schema":"aee880893829","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createTraining","classification":"WRITE","schema":"28ee97c9f48d","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createTrainingAssignment","classification":"WRITE","schema":"70b3c1aa623e","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createTrainingQuestion","classification":"WRITE","schema":"5defbdc86578","response":"3797626bd17e","permission":"resources:create","paginates":false},+ {"name":"resources_createWorkCenter","classification":"WRITE","schema":"fd853b10d45a","response":"3797626bd17e","permission":"resources:create+update","paginates":false},+ {"name":"resources_deactivateAbility","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"resources:delete","paginates":false},+ {"name":"resources_deactivateWorkCenter","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteContractor","classification":"DESTRUCTIVE","schema":"050d2aeb4e9a","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteFailureMode","classification":"DESTRUCTIVE","schema":"2557649b1a5e","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteLocation","classification":"DESTRUCTIVE","schema":"75b90f67d533","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","schema":"74a8a528c9d8","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteMaintenanceEvent","classification":"DESTRUCTIVE","schema":"a5eeac694397","response":"8e58a21e4c94","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","schema":"093d449cdac0","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deletePartner","classification":"DESTRUCTIVE","schema":"48d3fd6edb53","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteProcess","classification":"DESTRUCTIVE","schema":"5631e53ea64f","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteShift","classification":"DESTRUCTIVE","schema":"7830c71fa7a3","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteSuggestion","classification":"DESTRUCTIVE","schema":"7e2e609c39b4","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteTraining","classification":"DESTRUCTIVE","schema":"ad4ee6c278a0","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteTrainingAssignment","classification":"DESTRUCTIVE","schema":"9ee4c244585a","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_deleteTrainingQuestion","classification":"DESTRUCTIVE","schema":"3a46a4c5c924","response":"bcde375ebd4c","permission":"resources:delete","paginates":false},+ {"name":"resources_getAbilities","classification":"READ","schema":"e2389bb135b5","response":"b306c2cb1888","permission":"resources:view","paginates":true},+ {"name":"resources_getAbilitiesList","classification":"READ","schema":"31b84d65b2ac","response":"fc7a0345fc53","permission":"resources:view","paginates":false},+ {"name":"resources_getAbility","classification":"READ","schema":"18c5e48c0ea4","response":"d98eac986c97","permission":"resources:view","paginates":false},+ {"name":"resources_getContractor","classification":"READ","schema":"050d2aeb4e9a","response":"995cb2d28a3e","permission":"resources:view","paginates":false},+ {"name":"resources_getContractors","classification":"READ","schema":"e2389bb135b5","response":"ccd6066a170d","permission":"resources:view","paginates":true},+ {"name":"resources_getEmployeeAbilities","classification":"READ","schema":"f77d5ceb3fe7","response":"328aa0024967","permission":"resources:view","paginates":false},+ {"name":"resources_getEmployeeAbility","classification":"READ","schema":"71c585bd9df0","response":"f0d72cd0ea38","permission":"resources:view","paginates":false},+ {"name":"resources_getFailureMode","classification":"READ","schema":"2557649b1a5e","response":"412854326fc3","permission":"resources:view","paginates":false},+ {"name":"resources_getFailureModes","classification":"READ","schema":"e2389bb135b5","response":"b5d9b684eccd","permission":"resources:view","paginates":true},+ {"name":"resources_getFailureModesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"resources:view","paginates":false},+ {"name":"resources_getLocation","classification":"READ","schema":"75b90f67d533","response":"99dfd44b4c2e","permission":"resources:view","paginates":false},+ {"name":"resources_getLocations","classification":"READ","schema":"e2389bb135b5","response":"73aefed94223","permission":"resources:view","paginates":true},+ {"name":"resources_getLocationsList","classification":"READ","schema":"31b84d65b2ac","response":"e19c89c1e8a0","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceDispatch","classification":"READ","schema":"74a8a528c9d8","response":"083fee6ab76b","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceDispatchComments","classification":"READ","schema":"74a8a528c9d8","response":"7df6d6b7ba88","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceDispatchesByLocation","classification":"READ","schema":"4e2de91177d5","response":"6bb3f549dc61","permission":"resources:view","paginates":true},+ {"name":"resources_getMaintenanceDispatchEvents","classification":"READ","schema":"74a8a528c9d8","response":"fc0af15629d8","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceDispatchItems","classification":"READ","schema":"74a8a528c9d8","response":"4e3a00f00ee6","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceSchedule","classification":"READ","schema":"093d449cdac0","response":"2ea53f4f72d0","permission":"resources:view","paginates":false},+ {"name":"resources_getMaintenanceSchedulesByLocation","classification":"READ","schema":"a5332a4600fb","response":"4c005030a48e","permission":"resources:view","paginates":true},+ {"name":"resources_getOutstandingTrainingsForUser","classification":"READ","schema":"f77d5ceb3fe7","response":"a313bd7ca6e0","permission":"resources:view","paginates":false},+ {"name":"resources_getPartner","classification":"READ","schema":"fedfa0da6447","response":"690aa589fb9c","permission":"resources:view","paginates":false},+ {"name":"resources_getPartnerBySupplierId","classification":"READ","schema":"48d3fd6edb53","response":"690aa589fb9c","permission":"resources:view","paginates":false},+ {"name":"resources_getPartners","classification":"READ","schema":"e2389bb135b5","response":"6c9a4233e834","permission":"resources:view","paginates":true},+ {"name":"resources_getProcess","classification":"READ","schema":"5631e53ea64f","response":"1dcef23b2416","permission":"resources:view","paginates":false},+ {"name":"resources_getProcesses","classification":"READ","schema":"e2389bb135b5","response":"cd79fe552b97","permission":"resources:view","paginates":true},+ {"name":"resources_getProcessesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"resources:view","paginates":false},+ {"name":"resources_getProcessesWithoutAbility","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"resources:view","paginates":false},+ {"name":"resources_getSuggestion","classification":"READ","schema":"7e2e609c39b4","response":"77bb66a1249a","permission":"resources:view","paginates":false},+ {"name":"resources_getSuggestions","classification":"READ","schema":"e2389bb135b5","response":"de6c6fa956e3","permission":"resources:view","paginates":true},+ {"name":"resources_getTraining","classification":"READ","schema":"7f8214d1083f","response":"49bd32630132","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignment","classification":"READ","schema":"9ee4c244585a","response":"d992354bd0fd","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentForCompletion","classification":"READ","schema":"9ee4c244585a","response":"cc0e3d2cf77a","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignments","classification":"READ","schema":"27aced930989","response":"03daf9b26033","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentStatus","classification":"READ","schema":"f8ae9324ff87","response":"a313bd7ca6e0","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentStatusForEmployee","classification":"READ","schema":"f77d5ceb3fe7","response":"a313bd7ca6e0","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainingAssignmentSummary","classification":"READ","schema":"31b84d65b2ac","response":"64abd6a67dfa","permission":"resources:view","paginates":false},+ {"name":"resources_getTrainings","classification":"READ","schema":"e2389bb135b5","response":"304498b26d10","permission":"resources:view","paginates":true},+ {"name":"resources_getTrainingsList","classification":"READ","schema":"31b84d65b2ac","response":"22f58f9494b3","permission":"resources:view","paginates":false},+ {"name":"resources_getWorkCenter","classification":"READ","schema":"7f8214d1083f","response":"af7e30751616","permission":"resources:view","paginates":false},+ {"name":"resources_getWorkCenters","classification":"READ","schema":"e2389bb135b5","response":"7e12337d863b","permission":"resources:view","paginates":true},+ {"name":"resources_getWorkCentersByLocation","classification":"READ","schema":"75b90f67d533","response":"3aa9b7ccf523","permission":"resources:view","paginates":false},+ {"name":"resources_getWorkCentersList","classification":"READ","schema":"31b84d65b2ac","response":"d1a122ea7f19","permission":"resources:view","paginates":false},+ {"name":"resources_getWorkCentersListWithBlockingStatus","classification":"READ","schema":"31b84d65b2ac","response":"628a610a980e","permission":"resources:view","paginates":false},+ {"name":"resources_issueMaintenancePart","classification":"WRITE","schema":"af0751f3105f","response":"cf78aa7da634","permission":"resources:update","paginates":false},+ {"name":"resources_processDeactivate","classification":"WRITE","schema":"5631e53ea64f","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_reactivateWorkCenter","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"resources:delete","paginates":false},+ {"name":"resources_removeEmployeeAbility","classification":"DESTRUCTIVE","schema":"10092409622c","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_setMaintenanceDispatchStatus","classification":"WRITE","schema":"1bd67c7106fd","response":"8e58a21e4c94","permission":"resources:update","paginates":false},+ {"name":"resources_startMaintenanceEvent","classification":"WRITE","schema":"34cb412f1fae","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_stopMaintenanceEvent","classification":"WRITE","schema":"a5eeac694397","response":"8e58a21e4c94","permission":"resources:update","paginates":false},+ {"name":"resources_uncompleteTrainingAssignment","classification":"DESTRUCTIVE","schema":"d520f70388c9","response":"d520f70388c9","permission":"resources:delete","paginates":false},+ {"name":"resources_unissueMaintenancePart","classification":"DESTRUCTIVE","schema":"be5a1d978dcc","response":"3797626bd17e","permission":"resources:delete","paginates":false},+ {"name":"resources_updateAbility","classification":"WRITE","schema":"9fa76da0d27e","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateContractor","classification":"DESTRUCTIVE","schema":"a672e282e0cd","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateEmployeeAbility","classification":"WRITE","schema":"86a9132fd668","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateFailureMode","classification":"WRITE","schema":"165bfa2b7fdf","response":"8394fbabd845","permission":"resources:update","paginates":false},+ {"name":"resources_updateLocation","classification":"WRITE","schema":"ce189a85ea7e","response":"3797626bd17e","permission":"resources:create+update","paginates":false},+ {"name":"resources_updateMaintenanceDispatchComment","classification":"WRITE","schema":"9381cafe0efa","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateMaintenanceDispatchField","classification":"WRITE","schema":"29f2399f61fc","response":"6a884dc1da07","permission":"resources:update","paginates":false},+ {"name":"resources_updateMaintenanceDispatchItem","classification":"WRITE","schema":"871ab6aba5a8","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateMaintenanceEvent","classification":"WRITE","schema":"bf8266758b63","response":"8e58a21e4c94","permission":"resources:update","paginates":false},+ {"name":"resources_updateMaintenanceSchedule","classification":"WRITE","schema":"af63079aefd4","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updatePartner","classification":"WRITE","schema":"63fa7a0fe27d","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateProcess","classification":"DESTRUCTIVE","schema":"d33f66716674","response":"3797626bd17e","permission":"resources:create+delete+update","paginates":false},+ {"name":"resources_updateSuggestionEmoji","classification":"WRITE","schema":"5f9afdcc2556","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateTraining","classification":"WRITE","schema":"be935610f883","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingAssignment","classification":"WRITE","schema":"c787b54127d0","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingField","classification":"WRITE","schema":"89d3447a10b3","response":"0eb0c2be01ed","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingQuestion","classification":"WRITE","schema":"c97888abdd14","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingQuestionOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"60cd1f553572","permission":"resources:update","paginates":false},+ {"name":"resources_updateWorkCenter","classification":"WRITE","schema":"ae0789f2b0ea","response":"3797626bd17e","permission":"resources:update","paginates":false},+ {"name":"sales_activateRentalAgreement","classification":"WRITE","schema":"3797626bd17e","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_amendContract","classification":"WRITE","schema":"04dc5f3d37f7","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_cancelContract","classification":"WRITE","schema":"ced608188030","response":"f4c9785b5239","permission":"sales:update","paginates":false},+ {"name":"sales_cancelSalesReturnOrder","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_classifyRentalUnit","classification":"WRITE","schema":"0130929837e0","response":"c2c8ef2bbef1","permission":"accounting:update","paginates":false},+ {"name":"sales_confirmContract","classification":"WRITE","schema":"a806875e8efc","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_confirmReturnOrder","classification":"WRITE","schema":"22c6386df9f2","response":"b01f3bbdd0f8","permission":"sales:update","paginates":false},+ {"name":"sales_confirmSalesOrder","classification":"WRITE","schema":"ac08a54cf72b","response":"61c982753707","permission":"sales:create","paginates":false},+ {"name":"sales_convertQuote","classification":"WRITE","schema":"2f9ce4892f8e","response":"b3c62fcb92ac","permission":"sales:create","paginates":false},+ {"name":"sales_convertSalesRfq","classification":"WRITE","schema":"e74b45db7021","response":"8f3a111d6dd7","permission":"sales:create","paginates":false},+ {"name":"sales_copyItemMethodToQuoteLine","classification":"WRITE","schema":"c415fa75351b","response":"e0050938a2c8","permission":"sales:update","paginates":false},+ {"name":"sales_copyItemMethodToQuoteMaterial","classification":"WRITE","schema":"c9fd44bf9a70","response":"bfcaa45eb18e","permission":"sales:update","paginates":false},+ {"name":"sales_copyQuote","classification":"WRITE","schema":"06f2835dfed0","response":"4e1a8f1febce","permission":"sales:create","paginates":false},+ {"name":"sales_copyQuoteLineMethod","classification":"WRITE","schema":"e2d617e47e0a","response":"e0050938a2c8","permission":"sales:update","paginates":false},+ {"name":"sales_createContract","classification":"WRITE","schema":"249368eaeb19","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createContractLine","classification":"WRITE","schema":"70b5f6f42771","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createCustomer","classification":"WRITE","schema":"b37423e21101","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createCustomerBankAccount","classification":"WRITE","schema":"141fff5c420e","response":"3797626bd17e","permission":"accounting:create","paginates":false},+ {"name":"sales_createCustomerStatus","classification":"WRITE","schema":"d73822329fe1","response":"8394fbabd845","permission":"sales:create","paginates":false},+ {"name":"sales_createCustomerType","classification":"WRITE","schema":"d73822329fe1","response":"8394fbabd845","permission":"sales:create","paginates":false},+ {"name":"sales_createNoQuoteReason","classification":"WRITE","schema":"d73822329fe1","response":"8394fbabd845","permission":"sales:create","paginates":false},+ {"name":"sales_createOpportunityDocumentUploadUrl","classification":"WRITE","schema":"9d023be224ef","response":"4ad76afe0777","permission":"sales:create","paginates":false},+ {"name":"sales_createOpportunityLineDocumentUploadUrl","classification":"WRITE","schema":"89370e60a3e7","response":"4ad76afe0777","permission":"sales:create","paginates":false},+ {"name":"sales_createPricingRule","classification":"WRITE","schema":"6b9956ef81b3","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteLine","classification":"WRITE","schema":"f490cabfaa4e","response":"bb48df81da15","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteMaterial","classification":"WRITE","schema":"8c29d66dac67","response":"8e58a21e4c94","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteOperation","classification":"WRITE","schema":"bdc2bb4c515e","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteOperationParameter","classification":"WRITE","schema":"fd33201b6404","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteOperationStep","classification":"WRITE","schema":"47d8a0a8b0c2","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createQuoteOperationTool","classification":"WRITE","schema":"b4ca2f2a0605","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createRentalAgreement","classification":"WRITE","schema":"3d2ec5205417","response":"a443ac9aa1f1","permission":"sales:create","paginates":false},+ {"name":"sales_createRentalAgreementCharge","classification":"WRITE","schema":"fa60bc3af730","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createRentalAgreementLine","classification":"WRITE","schema":"08cde3c0c4a5","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createReplacementSalesOrder","classification":"WRITE","schema":"3fdcd215dc22","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createReturnOrderLine","classification":"WRITE","schema":"f0f787b6d728","response":"f9d1513a44f3","permission":"sales:create","paginates":false},+ {"name":"sales_createReturnReason","classification":"WRITE","schema":"a8a4f74d55d8","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesOrderLine","classification":"WRITE","schema":"91896427de3a","response":"8f061af39e95","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","schema":"a752775acc57","response":"00404e686415","permission":"invoicing:create","paginates":false},+ {"name":"sales_createSalesRfq","classification":"WRITE","schema":"ef914612528f","response":"0c1a1b93cca3","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesRFQ","classification":"WRITE","schema":"3cd79b44f627","response":"2e56e1180d37","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesRFQLine","classification":"WRITE","schema":"b6b52d8707ee","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","schema":"9671bf9bdd53","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerBankAccount","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},+ {"name":"sales_deleteCustomerContact","classification":"DESTRUCTIVE","schema":"0a2c14c75652","response":"700b93baa3ef","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerItemPriceOverride","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerItemRentalRate","classification":"DESTRUCTIVE","schema":"fa2fb5ff991b","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerLocation","classification":"DESTRUCTIVE","schema":"fac9952916a4","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerStatus","classification":"DESTRUCTIVE","schema":"52bec6d3e5bd","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteCustomerType","classification":"DESTRUCTIVE","schema":"2a8659f88eca","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteNoQuoteReason","classification":"DESTRUCTIVE","schema":"3b4691733f86","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deletePricingRule","classification":"DESTRUCTIVE","schema":"954531f020b9","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuote","classification":"DESTRUCTIVE","schema":"8087dc4f5248","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteLine","classification":"DESTRUCTIVE","schema":"40e11ca73a53","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteMaterialAndReprice","classification":"DESTRUCTIVE","schema":"92adb5e77c44","response":"3797626bd17e","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteOperationAndReprice","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteOperationParameter","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteOperationStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteQuoteOperationTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteRentalAgreement","classification":"DESTRUCTIVE","schema":"7e41fc1a1e08","response":"3797626bd17e","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteRentalAgreementCharge","classification":"DESTRUCTIVE","schema":"2d825d87bc47","response":"3797626bd17e","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteRentalAgreementLine","classification":"DESTRUCTIVE","schema":"4249190735aa","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteReturnReason","classification":"DESTRUCTIVE","schema":"9db6b9d7003b","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesOrder","classification":"DESTRUCTIVE","schema":"6e4655763b3f","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesOrderLine","classification":"DESTRUCTIVE","schema":"fbe78064dbd7","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesReturnOrder","classification":"DESTRUCTIVE","schema":"3fdcd215dc22","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesReturnOrderLine","classification":"DESTRUCTIVE","schema":"e2b1df794940","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesRFQ","classification":"DESTRUCTIVE","schema":"c32128ec72f8","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deleteSalesRFQLine","classification":"DESTRUCTIVE","schema":"7201248a5292","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},+ {"name":"sales_deliverRentalUnit","classification":"WRITE","schema":"253e51a04f4e","response":"2e39a760a5ca","permission":"none","paginates":false},+ {"name":"sales_duplicatePricingRule","classification":"WRITE","schema":"7f8214d1083f","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_escalateReturnOrderLine","classification":"WRITE","schema":"b207270e6864","response":"a3013ba5cdbb","permission":"none","paginates":false},+ {"name":"sales_finalizeAndSendQuote","classification":"WRITE","schema":"ca18e9270f18","response":"c1e125e7d8af","permission":"sales:create","paginates":false},+ {"name":"sales_getBaseCatalog","classification":"READ","schema":"e4a07535daf2","response":"965c08b897d0","permission":"sales:view","paginates":false},+ {"name":"sales_getConfigurationParametersByQuoteLineId","classification":"READ","schema":"40e11ca73a53","response":"4dc7e9b6cbc3","permission":"sales:view","paginates":false},+ {"name":"sales_getContract","classification":"READ","schema":"d1a753b63ac7","response":"1375deebd9f6","permission":"sales:view","paginates":false},+ {"name":"sales_getContractAmendments","classification":"READ","schema":"d1a753b63ac7","response":"70b301a95120","permission":"sales:view","paginates":false},+ {"name":"sales_getContractInvoiceSchedule","classification":"READ","schema":"d1a753b63ac7","response":"4a793f5433cd","permission":"sales:view","paginates":false},+ {"name":"sales_getContractLine","classification":"READ","schema":"f4d3dbaa8bfd","response":"49583c612441","permission":"sales:view","paginates":false},+ {"name":"sales_getContractLines","classification":"READ","schema":"d1a753b63ac7","response":"8c2832f17e6d","permission":"sales:view","paginates":false},+ {"name":"sales_getContracts","classification":"READ","schema":"e2389bb135b5","response":"9bb0c1fac394","permission":"sales:view","paginates":true},+ {"name":"sales_getCreditableQuantities","classification":"READ","schema":"3fdcd215dc22","response":"da2f02c5bdac","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomer","classification":"READ","schema":"9671bf9bdd53","response":"8642159293c2","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerBankAccounts","classification":"READ","schema":"9671bf9bdd53","response":"d8173b9c2e54","permission":"accounting:view","paginates":false},+ {"name":"sales_getCustomerContact","classification":"READ","schema":"bfd196306256","response":"d16ba475ee9a","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerContacts","classification":"READ","schema":"9671bf9bdd53","response":"acc29dbe9746","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerContractStatuses","classification":"READ","schema":"9671bf9bdd53","response":"b4542ed3da5e","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemPriceOverride","classification":"READ","schema":"75fd8400560d","response":"2dfcd06e591d","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemPriceOverrideById","classification":"READ","schema":"7f8214d1083f","response":"none","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemRentalRate","classification":"READ","schema":"fa2fb5ff991b","response":"b3b8ce0eaba0","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerItemRentalRates","classification":"READ","schema":"30ab89ff5be9","response":"8b9441c41a32","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerLocation","classification":"READ","schema":"e0df27278d11","response":"be52ec9b4436","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerLocations","classification":"READ","schema":"9671bf9bdd53","response":"bcf222d6d73a","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerPayment","classification":"READ","schema":"9671bf9bdd53","response":"4357e4e42177","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomers","classification":"READ","schema":"e2389bb135b5","response":"e16ee6870826","permission":"sales:view","paginates":true},+ {"name":"sales_getCustomerShipping","classification":"READ","schema":"9671bf9bdd53","response":"d9e04e1cc364","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomersList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerStatus","classification":"READ","schema":"52bec6d3e5bd","response":"9203566a8ab4","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerStatuses","classification":"READ","schema":"e2389bb135b5","response":"254774c57849","permission":"sales:view","paginates":true},+ {"name":"sales_getCustomerStatusesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerTax","classification":"READ","schema":"9671bf9bdd53","response":"1d92e9e0b01d","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerType","classification":"READ","schema":"2a8659f88eca","response":"8b3eca34dbfd","permission":"sales:view","paginates":false},+ {"name":"sales_getCustomerTypes","classification":"READ","schema":"e2389bb135b5","response":"e0001a83b60b","permission":"sales:view","paginates":true},+ {"name":"sales_getCustomerTypesList","classification":"READ","schema":"31b84d65b2ac","response":"ce08332e0ce6","permission":"sales:view","paginates":false},+ {"name":"sales_getDefaultRentalRates","classification":"READ","schema":"e1fbd2f519d4","response":"aebd7c76789d","permission":"sales:view","paginates":false},+ {"name":"sales_getExternalSalesOrderLines","classification":"READ","schema":"48dfb046bfac","response":"7b8bd29508cd","permission":"sales:view","paginates":true},+ {"name":"sales_getItemRentalRate","classification":"READ","schema":"ddd591f1b7ad","response":"d1badca592c6","permission":"sales:view","paginates":false},+ {"name":"sales_getModelByQuoteLineId","classification":"READ","schema":"40e11ca73a53","response":"none","permission":"sales:view","paginates":false},+ {"name":"sales_getNoQuoteReason","classification":"READ","schema":"3b4691733f86","response":"4bbb50609deb","permission":"sales:view","paginates":false},+ {"name":"sales_getNoQuoteReasons","classification":"READ","schema":"e2389bb135b5","response":"f6f55833db42","permission":"sales:view","paginates":true},+ {"name":"sales_getOpenSalesOrderLinesForItem","classification":"READ","schema":"30ab89ff5be9","response":"2942b53dfd95","permission":"sales:view","paginates":false},+ {"name":"sales_getOpportunity","classification":"READ","schema":"1ee597897662","response":"03abafe9fa9f","permission":"sales:view","paginates":false},+ {"name":"sales_getOpportunityDocuments","classification":"READ","schema":"6dc274c5c3da","response":"1c34622130cc","permission":"sales:view","paginates":false},+ {"name":"sales_getOpportunityLineDocuments","classification":"READ","schema":"e11598873908","response":"1c34622130cc","permission":"sales:view","paginates":false},+ {"name":"sales_getPricingRule","classification":"READ","schema":"7f8214d1083f","response":"50720f6e5f2a","permission":"sales:view","paginates":false},+ {"name":"sales_getPricingRules","classification":"READ","schema":"e4a07535daf2","response":"f83b909b7fb0","permission":"sales:view","paginates":true},+ {"name":"sales_getQuote","classification":"READ","schema":"8087dc4f5248","response":"5b7ae632c481","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteByExternalId","classification":"READ","schema":"b8b14c07d2f0","response":"e1c8d7e62b7d","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteCustomerDetails","classification":"READ","schema":"8087dc4f5248","response":"7656953707c3","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLine","classification":"READ","schema":"40e11ca73a53","response":"a37f940eb1fa","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLinePrices","classification":"READ","schema":"40e11ca73a53","response":"b380070f2ac3","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLinePricesByQuoteId","classification":"READ","schema":"8087dc4f5248","response":"b380070f2ac3","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLinePriceTraces","classification":"READ","schema":"ffca7e5c29c1","response":"36a0683de042","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLines","classification":"READ","schema":"8087dc4f5248","response":"947e5b11c1ee","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteLinesList","classification":"READ","schema":"8087dc4f5248","response":"5ebff9af923d","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteMakeMethod","classification":"READ","schema":"d12e0ae9a70b","response":"f6ec0930d3af","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteMaterialsByMethodId","classification":"READ","schema":"d12e0ae9a70b","response":"34d1789c595a","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteMethodTrees","classification":"READ","schema":"8087dc4f5248","response":"abdc8a7e0541","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteOperationsByLine","classification":"READ","schema":"40e11ca73a53","response":"17a8edc27947","permission":"sales:view","paginates":false},+ {"name":"sales_getQuoteOperationsByMethodId","classification":"READ","schema":"d12e0ae9a70b","response":"68487e902368","permission":"sales:view","paginates":false},+ {"name":"sales_getQuotePayment","classification":"READ","schema":"8087dc4f5248","response":"c94b5d1f2b47","permission":"sales:view","paginates":false},+ {"name":"sales_getQuotes","classification":"READ","schema":"e2389bb135b5","response":"7c5302da1e9d","permission":"sales:view","paginates":true},+ {"name":"sales_getQuoteShipment","classification":"READ","schema":"8087dc4f5248","response":"9022fbc076f4","permission":"sales:view","paginates":false},+ {"name":"sales_getQuotesList","classification":"READ","schema":"31b84d65b2ac","response":"0ff25946068c","permission":"sales:view","paginates":false},+ {"name":"sales_getRelatedPricesForQuoteLine","classification":"READ","schema":"5fd8e97dfc3d","response":"72aab90423c2","permission":"sales:view","paginates":false},+ {"name":"sales_getRentableFleetAssets","classification":"READ","schema":"31b84d65b2ac","response":"18707409983d","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreement","classification":"READ","schema":"7e41fc1a1e08","response":"db7705c96e45","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementCharges","classification":"READ","schema":"7e41fc1a1e08","response":"20b5cadac79e","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementDeposits","classification":"READ","schema":"7e41fc1a1e08","response":"b905a3be4ed2","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementLine","classification":"READ","schema":"4249190735aa","response":"117c34a19a98","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementLines","classification":"READ","schema":"7e41fc1a1e08","response":"f65cfafe2da1","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreementRelatedDocuments","classification":"READ","schema":"7e41fc1a1e08","response":"bec1149b52c7","permission":"sales:view","paginates":false},+ {"name":"sales_getRentalAgreements","classification":"READ","schema":"e2389bb135b5","response":"b03dff63849f","permission":"sales:view","paginates":true},+ {"name":"sales_getRentalBillingPeriods","classification":"READ","schema":"7e41fc1a1e08","response":"be6d8cd76aac","permission":"sales:view","paginates":false},+ {"name":"sales_getReturnableLinesForCustomer","classification":"READ","schema":"b8b343f19f4f","response":"8b3d2e7917fd","permission":"sales:view","paginates":false},+ {"name":"sales_getReturnReason","classification":"READ","schema":"9db6b9d7003b","response":"784c9ecc581f","permission":"sales:view","paginates":false},+ {"name":"sales_getReturnReasons","classification":"READ","schema":"e2389bb135b5","response":"8a4afca236fd","permission":"sales:view","paginates":true},+ {"name":"sales_getReturnReasonsList","classification":"READ","schema":"31b84d65b2ac","response":"152e0efd7e28","permission":"sales:view","paginates":false},+ {"name":"sales_getRootQuoteMakeMethod","classification":"READ","schema":"40e11ca73a53","response":"f6ec0930d3af","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesDocumentsAssignedToMe","classification":"READ","schema":"31b84d65b2ac","response":"79cc01ae0450","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrder","classification":"READ","schema":"6e4655763b3f","response":"8f0db58fa8de","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderInvoiceLines","classification":"READ","schema":"6e4655763b3f","response":"1ff852ae9154","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderInvoicePaymentsByIds","classification":"READ","schema":"c9445aed4a17","response":"397cd2bf218b","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","schema":"c9445aed4a17","response":"cd5bcdc964de","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderLine","classification":"READ","schema":"fbe78064dbd7","response":"29aeab62ea0c","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderLines","classification":"READ","schema":"6e4655763b3f","response":"f904c1837ab8","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderLineShipments","classification":"READ","schema":"fbe78064dbd7","response":"57f078948fed","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderPayment","classification":"READ","schema":"6e4655763b3f","response":"e52a6a8beddf","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrderRelatedItems","classification":"READ","schema":"73e5a8561a17","response":"7368e76f2238","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrders","classification":"READ","schema":"378f68c53f60","response":"0e723cce3b7f","permission":"sales:view","paginates":true},+ {"name":"sales_getSalesOrderShipment","classification":"READ","schema":"6e4655763b3f","response":"c3b2536756de","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesOrdersList","classification":"READ","schema":"31b84d65b2ac","response":"5cc20a44d4fe","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrder","classification":"READ","schema":"3fdcd215dc22","response":"e1d9d94aa958","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderCredits","classification":"READ","schema":"3fdcd215dc22","response":"49639d091139","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderIssues","classification":"READ","schema":"3fdcd215dc22","response":"7cc200ea4b26","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderLine","classification":"READ","schema":"e2b1df794940","response":"6a8842161fed","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderLines","classification":"READ","schema":"3fdcd215dc22","response":"76501c9a66f1","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrderReceipts","classification":"READ","schema":"3fdcd215dc22","response":"184a88ad855b","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesReturnOrders","classification":"READ","schema":"378f68c53f60","response":"90d6fe03373c","permission":"sales:view","paginates":true},+ {"name":"sales_getSalesRFQ","classification":"READ","schema":"7f8214d1083f","response":"976840e1df1f","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesRFQLine","classification":"READ","schema":"e2b1df794940","response":"6a8f94e9ad4f","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesRFQLines","classification":"READ","schema":"c32128ec72f8","response":"9d27e3810b86","permission":"sales:view","paginates":false},+ {"name":"sales_getSalesRFQs","classification":"READ","schema":"e2389bb135b5","response":"19578401a4c3","permission":"sales:view","paginates":true},+ {"name":"sales_getSalesTerms","classification":"READ","schema":"31b84d65b2ac","response":"9819ae68df9b","permission":"sales:view","paginates":false},+ {"name":"sales_getShippedTrackedEntitiesForCustomer","classification":"READ","schema":"a25c9a6913ae","response":"a1e8810dc49a","permission":"sales:view","paginates":false},+ {"name":"sales_insertCustomerContact","classification":"WRITE","schema":"bc32d3cd1b75","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_insertCustomerLocation","classification":"WRITE","schema":"59180d724919","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_insertQuote","classification":"WRITE","schema":"bf0bba77b42f","response":"9e29b49e1dc8","permission":"sales:create","paginates":false},+ {"name":"sales_insertSalesOrder","classification":"WRITE","schema":"1e78cc5e252c","response":"dbfc22813350","permission":"sales:create","paginates":false},+ {"name":"sales_insertSalesReturnOrder","classification":"WRITE","schema":"d94a35f05cf8","response":"c32485518acd","permission":"sales:create","paginates":false},+ {"name":"sales_mapSalesRfqLines","classification":"WRITE","schema":"02bac31af170","response":"2132422b3a2d","permission":"sales:update","paginates":false},+ {"name":"sales_previewContractAmendment","classification":"WRITE","schema":"d957db5d561f","response":"351679e8ebb2","permission":"sales:update","paginates":false},+ {"name":"sales_previewContractCancellation","classification":"WRITE","schema":"0ef6e4e693de","response":"3ce9eb1c5d28","permission":"sales:update","paginates":false},+ {"name":"sales_releaseRentalUnit","classification":"WRITE","schema":"45909d441c37","response":"9729319c460e","permission":"sales:update","paginates":false},+ {"name":"sales_reopenSalesReturnOrder","classification":"WRITE","schema":"7f8214d1083f","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_repriceQuoteLineFromRules","classification":"WRITE","schema":"ffca7e5c29c1","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_resolvePrice","classification":"WRITE","schema":"f5fcab444c97","response":"eb12029769da","permission":"sales:update","paginates":false},+ {"name":"sales_resolvePriceList","classification":"WRITE","schema":"d153936d59d7","response":"965c08b897d0","permission":"sales:update","paginates":false},+ {"name":"sales_returnRentalUnit","classification":"WRITE","schema":"253e51a04f4e","response":"e00a9764517d","permission":"none","paginates":false},+ {"name":"sales_revertContractCancellation","classification":"WRITE","schema":"a18bd6ac2fe5","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_sellRentalUnit","classification":"WRITE","schema":"253e51a04f4e","response":"d51ae9969843","permission":"none","paginates":false},+ {"name":"sales_setContractInvoiceAutomation","classification":"WRITE","schema":"321dd5c5e689","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setContractTerm","classification":"WRITE","schema":"3db861398453","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setContractType","classification":"WRITE","schema":"4899de777529","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setQuoteStatus","classification":"WRITE","schema":"1ea4822e0e18","response":"1ea4822e0e18","permission":"sales:update","paginates":false},+ {"name":"sales_setRentalAgreementStatus","classification":"WRITE","schema":"18addd891e4a","response":"18addd891e4a","permission":"sales:update","paginates":false},+ {"name":"sales_setRentalAgreementTerm","classification":"WRITE","schema":"2aff228d5443","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setRentalInvoiceAutomation","classification":"WRITE","schema":"321dd5c5e689","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setSalesOrderStatus","classification":"WRITE","schema":"2c6a4f982ec9","response":"54a0554d39e6","permission":"sales:update","paginates":false},+ {"name":"sales_setSalesReturnOrderLineDisposition","classification":"WRITE","schema":"eea359b826f8","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setSalesRfqStatus","classification":"WRITE","schema":"068bf0995415","response":"7b9686b50055","permission":"sales:update","paginates":false},+ {"name":"sales_shipSalesOrderLine","classification":"WRITE","schema":"58e3c9762923","response":"2e39a760a5ca","permission":"inventory:create","paginates":false},+ {"name":"sales_shortCloseSalesReturnOrderLine","classification":"WRITE","schema":"b212fe8e50fb","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_updateContractLine","classification":"WRITE","schema":"c6dcafdb3ee3","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateContractTerms","classification":"WRITE","schema":"7cdb0bcfea29","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomer","classification":"WRITE","schema":"32148ef07cc7","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerBankAccount","classification":"WRITE","schema":"90273d505d9d","response":"3797626bd17e","permission":"accounting:update","paginates":false},+ {"name":"sales_updateCustomerContact","classification":"WRITE","schema":"713c7de4f8a2","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerLocation","classification":"WRITE","schema":"6afc03cf515f","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerPayment","classification":"WRITE","schema":"d3366ce33e7a","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerShipping","classification":"WRITE","schema":"32775010b257","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerStatus","classification":"WRITE","schema":"5f39e7b61b61","response":"8394fbabd845","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerTax","classification":"WRITE","schema":"17d9248d9345","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateCustomerType","classification":"WRITE","schema":"5f39e7b61b61","response":"8394fbabd845","permission":"sales:update","paginates":false},+ {"name":"sales_updateNoQuoteReason","classification":"WRITE","schema":"5f39e7b61b61","response":"8394fbabd845","permission":"sales:update","paginates":false},+ {"name":"sales_updatePricingRule","classification":"WRITE","schema":"a558835d70d7","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteDetails","classification":"WRITE","schema":"97e47673eb0b","response":"c726ae407913","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteLine","classification":"WRITE","schema":"29659b4ffe67","response":"8529f8fc63c9","permission":"sales:create","paginates":false},+ {"name":"sales_updateQuoteLineOrder","classification":"WRITE","schema":"323824b4392c","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteLinePrecision","classification":"WRITE","schema":"cf30feb01e5c","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteMaterial","classification":"WRITE","schema":"8c29d66dac67","response":"4ea32bd70246","permission":"sales:create","paginates":false},+ {"name":"sales_updateQuoteMaterialOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"60cd1f553572","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperation","classification":"WRITE","schema":"bdc2bb4c515e","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_updateQuoteOperationOrder","classification":"WRITE","schema":"60a7bcc6c0a3","response":"60cd1f553572","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperationParameter","classification":"WRITE","schema":"3d26db99a28d","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperationStep","classification":"WRITE","schema":"4ba3e76e5486","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperationTool","classification":"WRITE","schema":"e41cd4d18607","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateRentalAgreementCharge","classification":"WRITE","schema":"60104d550539","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateRentalAgreementLine","classification":"WRITE","schema":"a41a29319f75","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateReturnOrderLine","classification":"WRITE","schema":"9707b1beaf57","response":"f9d1513a44f3","permission":"sales:update","paginates":false},+ {"name":"sales_updateReturnReason","classification":"WRITE","schema":"49892225258b","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesOrderDetails","classification":"WRITE","schema":"cdfda47dd459","response":"d160a49d6787","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesOrderLine","classification":"WRITE","schema":"1f7aae174849","response":"8f061af39e95","permission":"sales:create","paginates":false},+ {"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","schema":"bc4baf1732ad","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesRFQ","classification":"WRITE","schema":"bb5d5a3918f8","response":"2e56e1180d37","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesRFQLine","classification":"WRITE","schema":"0b62b525fede","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesRFQLineOrder","classification":"WRITE","schema":"fa6fee3c7515","response":"none","permission":"sales:update","paginates":false},+ {"name":"sales_upsertCustomerItemPriceOverride","classification":"DESTRUCTIVE","schema":"c74a2a58d6cf","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertCustomerItemRentalRate","classification":"WRITE","schema":"36aacd353983","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertItemRentalRate","classification":"WRITE","schema":"69671ac2dab6","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertMakeMethodFromQuoteLine","classification":"WRITE","schema":"605368c2b9bd","response":"4e1a8f1febce","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertMakeMethodFromQuoteMethod","classification":"WRITE","schema":"dc9ff7a4d939","response":"bcde375ebd4c","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteLineAdditionalCharges","classification":"WRITE","schema":"18f385f95d04","response":"bcde375ebd4c","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteLinePrices","classification":"DESTRUCTIVE","schema":"01ec343190bf","response":"none","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuotePayment","classification":"WRITE","schema":"41842b4f8a7e","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertQuoteShipment","classification":"WRITE","schema":"9f413dd10f89","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertSalesOrderPayment","classification":"WRITE","schema":"d637b4fad42f","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"sales_upsertSalesOrderShipment","classification":"WRITE","schema":"c91b5d79606d","response":"3797626bd17e","permission":"sales:create+update","paginates":false},+ {"name":"settings_assignPrinter","classification":"WRITE","schema":"e396a6d7690b","response":"de371a276a58","permission":"settings:update","paginates":false},+ {"name":"settings_createItemSerialSequence","classification":"WRITE","schema":"bf7d97ed2065","response":"3797626bd17e","permission":"settings:create","paginates":false},+ {"name":"settings_deactivateCompanyIntegration","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"f06d2d858884","permission":"settings:update","paginates":false},+ {"name":"settings_deleteItemSerialSequence","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"settings:delete","paginates":false},+ {"name":"settings_deletePrintJob","classification":"DESTRUCTIVE","schema":"d46f637367f8","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_disableCompanyAuditLog","classification":"DESTRUCTIVE","schema":"31b84d65b2ac","response":"a369dbcd055c","permission":"settings:update","paginates":false},+ {"name":"settings_enableCompanyAuditLog","classification":"WRITE","schema":"31b84d65b2ac","response":"a369dbcd055c","permission":"settings:update","paginates":false},+ {"name":"settings_getAccountsPayableBillingAddress","classification":"READ","schema":"31b84d65b2ac","response":"7c0b9dc6d441","permission":"settings:view","paginates":false},+ {"name":"settings_getAccountsReceivableBillingAddress","classification":"READ","schema":"31b84d65b2ac","response":"7c0b9dc6d441","permission":"settings:view","paginates":false},+ {"name":"settings_getApiKeys","classification":"WRITE","schema":"e2389bb135b5","response":"14fbafc2ddf8","permission":"users:update","paginates":true},+ {"name":"settings_getCompanies","classification":"READ","schema":"31b84d65b2ac","response":"5783a32e0f4a","permission":"settings:view","paginates":false},+ {"name":"settings_getCompany","classification":"READ","schema":"31b84d65b2ac","response":"81a93f0029ec","permission":"settings:view","paginates":false},- {"name":"settings_getCompanySettings","classification":"READ","schema":"31b84d65b2ac","response":"689a7e333d99","permission":"settings:view","paginates":false},++ {"name":"settings_getCompanySettings","classification":"READ","schema":"31b84d65b2ac","response":"592dc0578df9","permission":"settings:view","paginates":false},+ {"name":"settings_getConfig","classification":"READ","schema":"31b84d65b2ac","response":"aa1021ff34cf","permission":"settings:view","paginates":false},+ {"name":"settings_getCurrentSequence","classification":"READ","schema":"31018ffa701d","response":"00404e686415","permission":"settings:view","paginates":false},+ {"name":"settings_getCustomField","classification":"READ","schema":"7f8214d1083f","response":"a533a796c094","permission":"settings:view","paginates":false},+ {"name":"settings_getCustomFields","classification":"READ","schema":"31018ffa701d","response":"2dad5e1497d3","permission":"settings:view","paginates":false},+ {"name":"settings_getCustomFieldsTables","classification":"READ","schema":"e2389bb135b5","response":"b1e2b7dc7754","permission":"settings:view","paginates":true},+ {"name":"settings_getDocumentSections","classification":"READ","schema":"31b84d65b2ac","response":"d8b65982e0d9","permission":"settings:view","paginates":false},+ {"name":"settings_getDocumentTemplate","classification":"READ","schema":"2a2940399e72","response":"99cae633d7cb","permission":"settings:view","paginates":false},+ {"name":"settings_getDocumentTemplateConfig","classification":"READ","schema":"2a2940399e72","response":"b41fea20c407","permission":"settings:view","paginates":false},+ {"name":"settings_getEmployeeCompanies","classification":"READ","schema":"31b84d65b2ac","response":"5783a32e0f4a","permission":"settings:view","paginates":false},+ {"name":"settings_getIndustries","classification":"READ","schema":"31b84d65b2ac","response":"5dcce0f224dd","permission":"settings:view","paginates":false},+ {"name":"settings_getIntegration","classification":"READ","schema":"7f8214d1083f","response":"099545249106","permission":"settings:view","paginates":false},+ {"name":"settings_getItemSerialSequence","classification":"READ","schema":"7f8214d1083f","response":"be8519536044","permission":"settings:view","paginates":false},+ {"name":"settings_getItemSerialSequences","classification":"READ","schema":"e2389bb135b5","response":"1caa1f035e17","permission":"settings:view","paginates":true},+ {"name":"settings_getKanbanOutputSetting","classification":"READ","schema":"31b84d65b2ac","response":"ca53dc098fc8","permission":"settings:view","paginates":false},+ {"name":"settings_getNextSequence","classification":"WRITE","schema":"31018ffa701d","response":"00404e686415","permission":"settings:update","paginates":false},+ {"name":"settings_getPlans","classification":"READ","schema":"31b84d65b2ac","response":"5483e69d7515","permission":"settings:view","paginates":false},+ {"name":"settings_getSequence","classification":"READ","schema":"31018ffa701d","response":"ef17e2453ded","permission":"settings:view","paginates":false},+ {"name":"settings_getSequences","classification":"READ","schema":"e2389bb135b5","response":"9f334247353f","permission":"settings:view","paginates":true},+ {"name":"settings_getSequencesList","classification":"READ","schema":"31018ffa701d","response":"8394fbabd845","permission":"settings:view","paginates":false},+ {"name":"settings_getSubsidiaries","classification":"READ","schema":"31b84d65b2ac","response":"577bb278c46e","permission":"settings:view","paginates":false},+ {"name":"settings_getSubsidiary","classification":"READ","schema":"31b84d65b2ac","response":"ac5d56a91ae0","permission":"settings:view","paginates":false},+ {"name":"settings_getTerms","classification":"READ","schema":"31b84d65b2ac","response":"deb82bb77180","permission":"settings:view","paginates":false},+ {"name":"settings_getWebhook","classification":"READ","schema":"7f8214d1083f","response":"cb2b17a3252e","permission":"settings:view","paginates":false},+ {"name":"settings_getWebhooks","classification":"READ","schema":"e2389bb135b5","response":"6a21799f60dd","permission":"settings:view","paginates":true},+ {"name":"settings_getWebhookTables","classification":"READ","schema":"31b84d65b2ac","response":"4417f117cc34","permission":"settings:view","paginates":false},+ {"name":"settings_removeDocumentSection","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_removePrinterRoute","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_resolveSections","classification":"WRITE","schema":"1ddda22ecba8","response":"32e51b029d79","permission":"settings:update","paginates":false},+ {"name":"settings_saveDocumentSection","classification":"WRITE","schema":"8a0f21626132","response":"d77a04e8c53e","permission":"settings:update","paginates":false},+ {"name":"settings_saveDocumentTemplate","classification":"WRITE","schema":"af049b32ee8d","response":"f1822dd9c8ab","permission":"settings:update","paginates":false},+ {"name":"settings_setIntegrationSyncEnabled","classification":"WRITE","schema":"fa07001f8501","response":"4111dc6445bb","permission":"settings:update","paginates":false},+ {"name":"settings_transitionSyncOperations","classification":"WRITE","schema":"c5a1f2594d65","response":"401e1aae225f","permission":"settings:update","paginates":false},+ {"name":"settings_updateAccountingSettings","classification":"WRITE","schema":"ecf0d5091645","response":"70bcf2b87ee3","permission":"settings:update","paginates":false},+ {"name":"settings_updateCompanyDetails","classification":"WRITE","schema":"f48dad39eb59","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_updateDimensionSync","classification":"WRITE","schema":"42c99362fccd","response":"f95fa90d0071","permission":"settings:update","paginates":false},- {"name":"settings_updateInventorySettings","classification":"WRITE","schema":"0e19706cf388","response":"8197b1c61474","permission":"settings:update","paginates":false},++ {"name":"settings_updateInventorySettings","classification":"WRITE","schema":"a76084d47705","response":"d62a56ef4842","permission":"settings:update","paginates":false},+ {"name":"settings_updateInvoicingSettings","classification":"WRITE","schema":"48fd9aba9ea8","response":"a32ee5ad2099","permission":"settings:update","paginates":false},+ {"name":"settings_updateItemSerialSequence","classification":"WRITE","schema":"5544b362f82e","response":"3797626bd17e","permission":"settings:update","paginates":false},+ {"name":"settings_updateItemsSettings","classification":"WRITE","schema":"e8ef8b2a7abb","response":"da26374a450b","permission":"settings:update","paginates":false},+ {"name":"settings_updatePlanningSettings","classification":"WRITE","schema":"0c543ed217a3","response":"0b9572e63423","permission":"settings:update","paginates":false},+ {"name":"settings_updatePostingSync","classification":"WRITE","schema":"a545e3ef8da3","response":"f95fa90d0071","permission":"settings:update","paginates":false},+ {"name":"settings_updateProductionSettings","classification":"WRITE","schema":"aab377266e08","response":"be6b8045779d","permission":"settings:update","paginates":false},+ {"name":"settings_updatePurchasingSettings","classification":"WRITE","schema":"bac40d77d38a","response":"b3fda8ac0d5f","permission":"settings:update","paginates":false},+ {"name":"settings_updateQualitySettings","classification":"WRITE","schema":"1bcfa3043aa1","response":"e87697c359ae","permission":"settings:update","paginates":false},+ {"name":"settings_updateResourcesSettings","classification":"WRITE","schema":"ba1b98fe944a","response":"ec0f37163627","permission":"settings:update","paginates":false},+ {"name":"settings_updateSalesSettings","classification":"WRITE","schema":"b200fc3300ac","response":"8becbd99be1d","permission":"settings:update","paginates":false},+ {"name":"settings_updateSecuritySettings","classification":"WRITE","schema":"1a5429a80ff2","response":"1a5429a80ff2","permission":"settings:update","paginates":false},+ {"name":"settings_updateSequence","classification":"WRITE","schema":"4f2efa805950","response":"bcde375ebd4c","permission":"settings:update","paginates":false},+ {"name":"shared_deleteSavedView","classification":"DESTRUCTIVE","schema":"785f497635a2","response":"bcde375ebd4c","permission":"none","paginates":false},+ {"name":"shared_enrollImplementationHub","classification":"WRITE","schema":"31b84d65b2ac","response":"a8f082a96841","permission":"settings:update","paginates":false},+ {"name":"shared_getBase64ImageFromSupabase","classification":"READ","schema":"e7450d4b5827","response":"00404e686415","permission":"none","paginates":false},+ {"name":"shared_getCountries","classification":"READ","schema":"31b84d65b2ac","response":"0e8a11b4e81c","permission":"none","paginates":false},+ {"name":"shared_getCustomerPortal","classification":"READ","schema":"7f8214d1083f","response":"none","permission":"none","paginates":false},+ {"name":"shared_getCustomerPortals","classification":"READ","schema":"e2389bb135b5","response":"2793c4da07f4","permission":"none","paginates":true},+ {"name":"shared_getEnforcementRule","classification":"READ","schema":"1345cc9e3507","response":"5d98bf9ad216","permission":"none","paginates":false},+ {"name":"shared_getEnforcementRuleAssignmentCounts","classification":"READ","schema":"3d06fc9d6384","response":"979bf79974f2","permission":"none","paginates":false},+ {"name":"shared_getEnforcementRules","classification":"READ","schema":"b185fab4a9f3","response":"4c883b774887","permission":"none","paginates":true},+ {"name":"shared_getExternalLink","classification":"READ","schema":"7f8214d1083f","response":"11128e5c07f9","permission":"none","paginates":false},+ {"name":"shared_getModelByItemId","classification":"READ","schema":"30ab89ff5be9","response":"none","permission":"none","paginates":false},+ {"name":"shared_getNotes","classification":"READ","schema":"1a362ab8a372","response":"1a052a4417b5","permission":"none","paginates":false},+ {"name":"shared_getTagsList","classification":"READ","schema":"af4eca956117","response":"b837740e18f4","permission":"none","paginates":false},+ {"name":"shared_insertNote","classification":"WRITE","schema":"6b735d93fae1","response":"c2fb0e5225f8","permission":"none","paginates":false},+ {"name":"shared_insertTag","classification":"WRITE","schema":"9fd690c21fa5","response":"27f67ae1958c","permission":"none","paginates":false},+ {"name":"shared_updateSavedViewOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"393a0d83325c","permission":"none","paginates":false},+ {"name":"shared_upsertSavedView","classification":"WRITE","schema":"0bfaff189d21","response":"3797626bd17e","permission":"none","paginates":false},+ {"name":"users_deleteGroup","classification":"DESTRUCTIVE","schema":"6624f3863074","response":"bcde375ebd4c","permission":"users:delete","paginates":false},+ {"name":"users_getAccount","classification":"READ","schema":"7f8214d1083f","response":"8adb0e14ee10","permission":"none","paginates":false},+ {"name":"users_getAllAttributeCategories","classification":"READ","schema":"31b84d65b2ac","response":"e93d76f694fe","permission":"none","paginates":false},+ {"name":"users_getAttributeCategoryWithValues","classification":"READ","schema":"ac8b9e1ae260","response":"32112b6759f8","permission":"none","paginates":false},+ {"name":"users_getConsoleOperators","classification":"READ","schema":"e2389bb135b5","response":"9823b01639fc","permission":"users:view","paginates":true},+ {"name":"users_getCurrentUser","classification":"READ","schema":"31b84d65b2ac","response":"ddc730821e71","permission":"none","paginates":false},+ {"name":"users_getCustomers","classification":"READ","schema":"e2389bb135b5","response":"01865d2b41ff","permission":"users:view","paginates":true},+ {"name":"users_getEmployee","classification":"READ","schema":"7f8214d1083f","response":"fddbdf17260d","permission":"users:view","paginates":false},+ {"name":"users_getEmployees","classification":"READ","schema":"e2389bb135b5","response":"9823b01639fc","permission":"users:view","paginates":true},+ {"name":"users_getEmployeeType","classification":"READ","schema":"6e5e68777065","response":"02c4f766f388","permission":"users:view","paginates":false},+ {"name":"users_getEmployeeTypes","classification":"READ","schema":"e2389bb135b5","response":"1546a93f061d","permission":"users:view","paginates":true},+ {"name":"users_getGroup","classification":"READ","schema":"6624f3863074","response":"f06d2d858884","permission":"users:view","paginates":false},+ {"name":"users_getGroupEmails","classification":"READ","schema":"99198903a0f2","response":"681004346c78","permission":"users:view","paginates":false},+ {"name":"users_getGroupMembers","classification":"READ","schema":"6624f3863074","response":"f218e882144b","permission":"users:view","paginates":false},+ {"name":"users_getGroups","classification":"READ","schema":"946e9e64ce34","response":"14a0c805bf0d","permission":"users:view","paginates":true},+ {"name":"users_getInvitable","classification":"READ","schema":"31b84d65b2ac","response":"3173c3a99146","permission":"users:view","paginates":false},+ {"name":"users_getItarCertificationReport","classification":"READ","schema":"31b84d65b2ac","response":"203ea6eb1a16","permission":"users:view","paginates":false},+ {"name":"users_getItarCertificationStatus","classification":"READ","schema":"31b84d65b2ac","response":"6afd62a22e82","permission":"users:view","paginates":false},+ {"name":"users_getItarEntityCertification","classification":"READ","schema":"31b84d65b2ac","response":"c5ae95ca48db","permission":"users:view","paginates":false},+ {"name":"users_getModules","classification":"READ","schema":"31b84d65b2ac","response":"df0e311a0baf","permission":"users:view","paginates":false},+ {"name":"users_getNotificationPreferences","classification":"READ","schema":"31b84d65b2ac","response":"0486649779fc","permission":"none","paginates":false},+ {"name":"users_getPermissionsByEmployeeType","classification":"READ","schema":"6e5e68777065","response":"9273cec17683","permission":"users:view","paginates":false},+ {"name":"users_getSuppliers","classification":"READ","schema":"e2389bb135b5","response":"92e8a9c9df02","permission":"users:view","paginates":true},+ {"name":"users_getUnrevokedInviteEmails","classification":"READ","schema":"31b84d65b2ac","response":"a6b0124b4410","permission":"users:view","paginates":false},+ {"name":"users_getUserSelectGroupMembers","classification":"READ","schema":"6624f3863074","response":"b754519017cb","permission":"users:view","paginates":false},+ {"name":"users_getUserSelectGroups","classification":"READ","schema":"f802932716af","response":"51b54791b40a","permission":"users:view","paginates":false},+ {"name":"users_getUsersWithVerifiedMfa","classification":"READ","schema":"31b84d65b2ac","response":"4c1fdc714231","permission":"users:view","paginates":false},+ {"name":"users_resolveUserSelectIds","classification":"WRITE","schema":"1ddda22ecba8","response":"7fdfa4c9e77e","permission":"users:update","paginates":false},+ {"name":"users_searchUsersForSelect","classification":"READ","schema":"b9c0b50026a7","response":"c9c1df9c3e28","permission":"users:view","paginates":false},+ {"name":"users_updatePublicAccount","classification":"WRITE","schema":"1ce670a17890","response":"bcde375ebd4c","permission":"none","paginates":false},+ {"name":"users_upsertNotificationPreference","classification":"WRITE","schema":"537337e9e9aa","response":"bcde375ebd4c","permission":"none","paginates":false}]}diff --cc apps/erp/app/routes/x+/settings+/inventory.tsxindex cd42ab357b,443b2f5b28..149e82ec00--- a/apps/erp/app/routes/x+/settings+/inventory.tsx+++ b/apps/erp/app/routes/x+/settings+/inventory.tsx@@@ -31,7 -30,6 +33,7 @@@ importimport { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";- import { useCallback, useEffect } from "react";++import { useCallback } from "react";import {LuLayers,LuPackageCheck,@@@ -42,23 -40,18 +44,20 @@@LuUndo2} from "react-icons/lu";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";- import { useFetcher, useLoaderData } from "react-router";+ import { useLoaderData } from "react-router";+ import { z } from "zod";import { SettingsPage, SettingsPageHeading } from "~/components/SettingsPage";import SettingsSectionHeader from "~/components/SettingsSectionHeader";+import { useSavedToggle } from "~/hooks/useSavedToggle";import {- getCompanySettings,incompletePickingListPolicyValidator,kanbanOutputTypes,kanbanOutputValidator,returnPickedMaterialTimingValidator,- shelfLifeSettingsValidator,- updateIncompletePickingListPolicySetting,- updateKanbanOutputSetting,- updateReceiptQuantitiesStartAtZeroSetting,- updateReturnPickedMaterialTimingSetting,- updateShelfLifeSettings- } from "~/modules/settings";++ settingsToggle,+ shelfLifeSettingsValidator+ } from "~/modules/settings/settings.models";+ import { getCompanySettings } from "~/modules/settings/settings.service";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@@ -89,134 -82,31 +88,32 @@@ export async function loader({ requestreturn { companySettings: companySettings.data };}- export async function action({ request }: ActionFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- update: "settings"- });-- const formData = await request.formData();- const intent = formData.get("intent");-- switch (intent) {- case "kanbanOutput":- const kanbanOutputValidation = await validator(- kanbanOutputValidator- ).validate(formData);-- if (kanbanOutputValidation.error) {- return { success: false, message: "Invalid form data" };+ // One form per card, told apart by its intent: each becomes the fields of+ // `settings.inventory.update` it saves (the operation drops `intent`).+ const inventorySettingsForm = z.discriminatedUnion("intent", [+ kanbanOutputValidator.extend({ intent: z.literal("kanbanOutput") }),+ shelfLifeSettingsValidator+ .extend({ intent: z.literal("shelfLife") })+ .transform(({ intent: _, ...shelfLife }) => ({+ inventoryShelfLife: {+ ...shelfLife,+ nearExpiryWarningDays: shelfLife.nearExpiryWarningDays ?? null}-- const kanbanOutputResult = await updateKanbanOutputSetting(- client,- companyId,- kanbanOutputValidation.data.kanbanOutput- );- if (kanbanOutputResult.error)- return {- success: false,- message: kanbanOutputResult.error.message- };-- return { success: true, message: "Kanban output setting updated" };-- case "shelfLife":- const shelfLifeValidation = await validator(- shelfLifeSettingsValidator- ).validate(formData);-- if (shelfLifeValidation.error) {- return { success: false, message: "Invalid form data" };- }-- const shelfLifeResult = await updateShelfLifeSettings(client, companyId, {- nearExpiryWarningDays: shelfLifeValidation.data.nearExpiryWarningDays,- defaultShelfLifeDays: shelfLifeValidation.data.defaultShelfLifeDays,- calculatedInputScope: shelfLifeValidation.data.calculatedInputScope,- expiredEntityPolicy: shelfLifeValidation.data.expiredEntityPolicy- });- if (shelfLifeResult.error)- return {- success: false,- message: shelfLifeResult.error.message- };-- return {- success: true,- message: "Shelf life & expiry settings updated"- };-- case "incompletePickingListPolicy":- const pickingPolicyValidation = await validator(- incompletePickingListPolicyValidator- ).validate(formData);-- if (pickingPolicyValidation.error) {- return { success: false, message: "Invalid form data" };- }-- const pickingPolicyResult =- await updateIncompletePickingListPolicySetting(- client,- companyId,- pickingPolicyValidation.data.incompletePickingListPolicy- );- if (pickingPolicyResult.error)- return {- success: false,- message: pickingPolicyResult.error.message- };-- return {- success: true,- message: "Picking list completion policy updated"- };-- case "receiptQuantitiesStartAtZero": {- const enabled = formData.get("enabled") === "true";- const result = await updateReceiptQuantitiesStartAtZeroSetting(- client,- companyId,- enabled- );- if (result.error)- return { success: false, message: result.error.message };-- return {- success: true,- message: enabled- ? "Receipt quantities now start at zero"- : "Receipt quantities now start at the quantity to receive"- };- }-- case "returnPickedMaterialTiming":- const returnTimingValidation = await validator(- returnPickedMaterialTimingValidator- ).validate(formData);-- if (returnTimingValidation.error) {- return { success: false, message: "Invalid form data" };- }-- const returnTimingResult = await updateReturnPickedMaterialTimingSetting(- client,- companyId,- returnTimingValidation.data.returnPickedMaterialTiming- );- if (returnTimingResult.error)- return {- success: false,- message: returnTimingResult.error.message- };-- return {- success: true,- message: "Material return timing updated"- };- }-- return { success: false, message: "Invalid form data" };+ })),+ incompletePickingListPolicyValidator.extend({+ intent: z.literal("incompletePickingListPolicy")+ }),+ returnPickedMaterialTimingValidator.extend({+ intent: z.literal("returnPickedMaterialTiming")- })++ }),++ settingsToggle("receiptQuantitiesStartAtZero", "receiptQuantitiesStartAtZero")+ ]);++ export async function action(args: ActionFunctionArgs) {+ const input = await validator(inventorySettingsForm).request(args);+ if ("invalid" in input) return input.invalid;+ const api = await carbon(args.request);+ return api.settings.updateInventorySettings(input.data);}const outputLabels: Record<(typeof kanbanOutputTypes)[number], string> = {@@@ -228,45 -118,18 +125,47 @@@export default function InventorySettingsRoute() {const { t } = useLingui();const { companySettings } = useLoaderData<typeof loader>();- const fetcher = useFetcher<typeof action>();-- useEffect(() => {- if (fetcher.data?.success === true && fetcher?.data?.message) {- toast.success(fetcher.data.message);+ const fetcher = useAction<typeof action>({+ onSuccess: ({ data }) => {+ if (!data) return;+ if (data.kanbanOutput) toast.success(t`Kanban output setting updated`);+ else if (data.inventoryShelfLife)+ toast.success(t`Shelf life & expiry settings updated`);+ else if (data.incompletePickingListPolicy)+ toast.success(t`Picking list completion policy updated`);+ else toast.success(t`Material return timing updated`);}+ });- if (fetcher.data?.success === false && fetcher?.data?.message) {- toast.error(fetcher.data.message);++ // The switch saves on change through its own fetcher, so saving another++ // card cannot cancel it or disable it.++ const toggleFetcher = useAction<typeof action>({++ onSuccess: ({ data }) => {++ if (data?.receiptQuantitiesStartAtZero === undefined) return;++ toast.success(++ data.receiptQuantitiesStartAtZero++ ? t`Receipt quantities now start at zero`++ : t`Receipt quantities now start at the quantity to receive`++ );+ }- }, [fetcher.data?.message, fetcher.data?.success]);-- const toggleFetcher = useFetcher<typeof action>();++ });++ const receiptQuantitiesStartAtZero = useSavedToggle(+ toggleFetcher,+ "receiptQuantitiesStartAtZero",+ companySettings.receiptQuantitiesStartAtZero+ );++ const handleReceiptQuantitiesStartAtZeroToggle = useCallback(+ (checked: boolean) => {+ toggleFetcher.submit(+ { intent: "receiptQuantitiesStartAtZero", enabled: checked.toString() },+ { method: "POST" }+ );+ },+ [toggleFetcher]+ );+- useEffect(() => {- if (toggleFetcher.data?.success === true && toggleFetcher?.data?.message) {- toast.success(toggleFetcher.data.message);- }- if (toggleFetcher.data?.success === false && toggleFetcher?.data?.message) {- toast.error(toggleFetcher.data.message);- }- }, [toggleFetcher.data?.message, toggleFetcher.data?.success]);-return (<ScrollArea className="w-full h-[calc(100dvh-var(--topbar-height)-var(--content-inset))]"><SettingsPage className="gap-4">diff --cc apps/erp/test/database/receipt-quantities-start-at-zero.test.tsindex fcf8e6a863,0000000000..2b241ba058mode 100644,000000..100644--- a/apps/erp/test/database/receipt-quantities-start-at-zero.test.ts+++ b/apps/erp/test/database/receipt-quantities-start-at-zero.test.ts@@@ -1,370 -1,0 +1,381 @@@+// 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.++// Blind receiving against the live database: with+// `companySettings.receiptQuantitiesStartAtZero` on, a purchase-order receipt's+// lines start at 0, and posting it books only the lines that were received.++import { expect } from "vitest";++import { postReceipt } from "../../app/modules/inventory/inventory.service";++import {++ invokeCreate,++ invokePosting++} from "../../app/modules/shared/shared.service";+import {+ alwaysPostFixture,+ type Fixture,+ seed,+ USER,+ unwrap- } from "./always-post-test-fixture";- import create from "./create";- import { databaseTest } from "./local-database-test-fixture";- import postReceipt from "./post-receipt";++} from "./fixtures/always-post";++import { handlesOf } from "./fixtures/handles";++import { databaseTest } from "./fixtures/local-database";++/** A purchase order with two lines of 10 of the fixture's part. */+async function purchaseOrderWithTwoLines(f: Fixture): Promise<string> {+ const purchaseOrderId = `${f.prefix}-po-blind`;+ await seed(f, async (trx) => {+ const interaction = await trx+ .insertInto("supplierInteraction")+ .values({ supplierId: f.supplierId, companyId: f.companyId })+ .returning("id")+ .executeTakeFirstOrThrow();+ await trx+ .insertInto("purchaseOrder")+ .values({+ id: purchaseOrderId,+ purchaseOrderId: "PO-BLIND",+ supplierId: f.supplierId,+ supplierInteractionId: interaction.id,+ currencyCode: "USD",+ exchangeRate: 1,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("purchaseOrderDelivery")+ .values({+ id: purchaseOrderId,+ locationId: f.locationId,+ companyId: f.companyId+ })+ .execute();+ await trx+ .insertInto("purchaseOrderLine")+ .values(+ ["line-1", "line-2"].map((key) => ({+ id: `${f.prefix}-pol-${key}`,+ purchaseOrderId,+ purchaseOrderLineType: "Part" as const,+ itemId: f.partId,+ purchaseQuantity: 10,+ supplierUnitPrice: 10,+ exchangeRate: 1,+ conversionFactor: 1,+ inventoryUnitOfMeasureCode: "EA",+ locationId: f.locationId,+ companyId: f.companyId,+ createdBy: USER+ }))+ )+ .execute();+ });+ return purchaseOrderId;+}++async function setStartAtZero(f: Fixture, value: boolean) {+ await f.db+ .updateTable("companySettings")+ .set({ receiptQuantitiesStartAtZero: value })+ .where("id", "=", f.companyId)+ .execute();+}++async function receiptLines(f: Fixture, receiptId: string) {+ return f.db+ .selectFrom("receiptLine")+ .select(["id", "lineId", "receivedQuantity", "outstandingQuantity"])+ .where("receiptId", "=", receiptId)+ .where("companyId", "=", f.companyId)+ .orderBy("lineId")+ .execute();+}++databaseTest(+ "a receipt starts each line at the quantity to receive when the setting is off",+ async () => {+ const f = await alwaysPostFixture();+ try {+ const purchaseOrderId = await purchaseOrderWithTwoLines(f);+ const receipt = unwrap(- await create(f.ctx, {++ await invokeCreate(handlesOf(f.ctx), {+ type: "receiptFromPurchaseOrder",+ purchaseOrderId,+ locationId: f.locationId+ })+ );++ const lines = await receiptLines(f, receipt.id);+ expect(lines.map((l) => Number(l.receivedQuantity))).toEqual([10, 10]);+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "with the setting on, a receipt starts at 0 and posts only the lines that were received",+ async () => {+ const f = await alwaysPostFixture();+ try {+ await setStartAtZero(f, true);+ const purchaseOrderId = await purchaseOrderWithTwoLines(f);+ const receipt = unwrap(- await create(f.ctx, {++ await invokeCreate(handlesOf(f.ctx), {+ type: "receiptFromPurchaseOrder",+ purchaseOrderId,+ locationId: f.locationId+ })+ );++ const lines = await receiptLines(f, receipt.id);+ expect(+ lines.map((l) => [+ Number(l.receivedQuantity),+ Number(l.outstandingQuantity)+ ])+ ).toEqual([+ [0, 10],+ [0, 10]+ ]);++ // The receiver counts 4 on the first line; nothing arrived for the second.+ await f.db+ .updateTable("receiptLine")+ .set({ receivedQuantity: 4 })+ .where("id", "=", lines[0]!.id)+ .where("companyId", "=", f.companyId)+ .execute();+- unwrap(await postReceipt(f.ctx, { type: "post", receiptId: receipt.id }));++ unwrap(++ await invokePosting(++ handlesOf(f.ctx),++ "post-receipt",++ { type: "post", receiptId: receipt.id },++ postReceipt++ )++ );++ const ledger = await f.db+ .selectFrom("itemLedger")+ .select("quantity")+ .where("documentId", "=", receipt.id)+ .where("companyId", "=", f.companyId)+ .execute();+ expect(ledger.map((row) => Number(row.quantity))).toEqual([4]);++ const purchaseOrderLines = await f.db+ .selectFrom("purchaseOrderLine")+ .select(["id", "quantityReceived", "receivedComplete"])+ .where("purchaseOrderId", "=", purchaseOrderId)+ .where("companyId", "=", f.companyId)+ .orderBy("id")+ .execute();+ expect(+ purchaseOrderLines.map((l) => [+ Number(l.quantityReceived),+ l.receivedComplete+ ])+ ).toEqual([+ [4, false],+ [0, false]+ ]);+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "with the setting on, transfer and sales return receipts start at 0",+ async () => {+ const f = await alwaysPostFixture();+ try {+ await setStartAtZero(f, true);+ const warehouseTransferId = `${f.prefix}-transfer-blind`;+ const salesReturnOrderId = `${f.prefix}-rma-blind`;+ await seed(f, async (trx) => {+ await trx+ .insertInto("warehouseTransfer")+ .values({+ id: warehouseTransferId,+ transferId: "WT-BLIND",+ fromLocationId: f.otherLocationId,+ toLocationId: f.locationId,+ status: "To Receive",+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("warehouseTransferLine")+ .values({+ transferId: warehouseTransferId,+ itemId: f.partId,+ quantity: 5,+ shippedQuantity: 5,+ fromLocationId: f.otherLocationId,+ toLocationId: f.locationId,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("salesReturnOrder")+ .values({+ id: salesReturnOrderId,+ salesReturnOrderId: "RMA-BLIND",+ customerId: f.customerId,+ currencyCode: "USD",+ orderDate: f.today,+ locationId: f.locationId,+ status: "To Receive",+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("salesReturnOrderLine")+ .values({+ salesReturnOrderId,+ itemId: f.partId,+ quantity: 2,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ });++ const transferReceipt = unwrap(- await create(f.ctx, {++ await invokeCreate(handlesOf(f.ctx), {+ type: "receiptFromInboundTransfer",+ warehouseTransferId+ })+ );+ const returnReceipt = unwrap(- await create(f.ctx, {++ await invokeCreate(handlesOf(f.ctx), {+ type: "receiptFromSalesReturnOrder",+ salesReturnOrderId,+ locationId: f.locationId+ })+ );++ for (const [receiptId, outstanding] of [+ [transferReceipt.id, 5],+ [returnReceipt.id, 2]+ ] as const) {+ const lines = await receiptLines(f, receiptId);+ expect(+ lines.map((l) => [+ Number(l.receivedQuantity),+ Number(l.outstandingQuantity)+ ])+ ).toEqual([[0, outstanding]]);+ }+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "with the setting on, a purchase order's fixed-asset line starts unticked",+ async () => {+ const f = await alwaysPostFixture();+ try {+ await setStartAtZero(f, true);+ const purchaseOrderId = `${f.prefix}-po-asset`;+ await seed(f, async (trx) => {+ const filler = f.account("filler");+ const assetClass = await trx+ .insertInto("fixedAssetClass")+ .values({+ name: `${f.prefix} machinery`,+ assetAccountId: filler,+ accumulatedDepreciationAccountId: filler,+ depreciationExpenseAccountId: filler,+ writeOffAccountId: filler,+ writeDownAccountId: filler,+ lossOnDisposalAccountId: filler,+ gainOnDisposalAccountId: filler,+ companyId: f.companyId,+ createdBy: USER+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ const asset = await trx+ .insertInto("fixedAsset")+ .values({+ fixedAssetId: `${f.prefix}-FA`,+ name: "CNC machining center",+ fixedAssetClassId: assetClass.id,+ companyId: f.companyId,+ createdBy: USER+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ const interaction = await trx+ .insertInto("supplierInteraction")+ .values({ supplierId: f.supplierId, companyId: f.companyId })+ .returning("id")+ .executeTakeFirstOrThrow();+ await trx+ .insertInto("purchaseOrder")+ .values({+ id: purchaseOrderId,+ purchaseOrderId: "PO-ASSET",+ supplierId: f.supplierId,+ supplierInteractionId: interaction.id,+ currencyCode: "USD",+ exchangeRate: 1,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("purchaseOrderDelivery")+ .values({+ id: purchaseOrderId,+ locationId: f.locationId,+ companyId: f.companyId+ })+ .execute();+ await trx+ .insertInto("purchaseOrderLine")+ .values({+ purchaseOrderId,+ purchaseOrderLineType: "Fixed Asset",+ assetId: asset.id,+ purchaseQuantity: 1,+ supplierUnitPrice: 1000,+ exchangeRate: 1,+ conversionFactor: 1,+ locationId: f.locationId,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ });++ const receipt = unwrap(- await create(f.ctx, {++ await invokeCreate(handlesOf(f.ctx), {+ type: "receiptFromPurchaseOrder",+ purchaseOrderId,+ locationId: f.locationId+ })+ );++ const assetLines = await f.db+ .selectFrom("receiptFixedAssetLine")+ .select("received")+ .where("receiptId", "=", receipt.id)+ .where("companyId", "=", f.companyId)+ .execute();+ expect(assetLines.map((l) => l.received)).toEqual([false]);+ } finally {+ await f.cleanup();+ }+ }+);diff --cc packages/jobs/manifests/schema.jsonindex ff8f67942b,06f09732a4..844e159737--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@@ -5,7 -5,7 +5,7 @@@"sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-17T03:39:44.574Z",- "exportedAt": "2026-10-17T07:08:05.778Z",++ "exportedAt": "2026-10-17T16:04:06.119Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",diff --cc packages/locale/locales/de/erp.poindex 4198c50d49,3a4bfe6e40..3a4c08d851--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Empfangszeilenmsgid "Receipt Promised Date"msgstr "Zugesagter Termin Wareneingang"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "Wareneingangsmengen starten jetzt bei der zu empfangenden Menge"++++msgid "Receipt quantities now start at zero"++msgstr "Wareneingangsmengen starten jetzt bei null"++msgid "Receipt Requested Date"msgstr "Wunschtermin Wareneingang"diff --cc packages/locale/locales/en/erp.poindex 8a44356779,2b48abdaa0..672ac402ba--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Receipt Linesmsgid "Receipt Promised Date"msgstr "Receipt Promised Date"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "Receipt quantities now start at the quantity to receive"++++msgid "Receipt quantities now start at zero"++msgstr "Receipt quantities now start at zero"++msgid "Receipt Requested Date"msgstr "Receipt Requested Date"diff --cc packages/locale/locales/es/erp.poindex 621d5a75a6,fbed5a960d..699c48a044--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Líneas de Recepciónmsgid "Receipt Promised Date"msgstr "Fecha de Entrega Prometida"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "Las cantidades de recepción ahora comienzan con la cantidad por recibir"++++msgid "Receipt quantities now start at zero"++msgstr "Las cantidades de recepción ahora comienzan en cero"++msgid "Receipt Requested Date"msgstr "Fecha de Recepción Solicitada"diff --cc packages/locale/locales/fr/erp.poindex fce2bb0625,158417145a..a752243372--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Lignes de réceptionmsgid "Receipt Promised Date"msgstr "Date de livraison promise"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "Les quantités de réception commencent maintenant à la quantité à réceptionner"++++msgid "Receipt quantities now start at zero"++msgstr "Les quantités de réception commencent maintenant à zéro"++msgid "Receipt Requested Date"msgstr "Date de réception demandée"diff --cc packages/locale/locales/hi/erp.poindex 01d2f7dbe5,040d7774fd..20031fd0cd--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "रसीद लाइनेंmsgid "Receipt Promised Date"msgstr "प्राप्ति वादा की गई तिथि"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "प्राप्ति की मात्रा अब प्राप्त करने के लिए की मात्रा से शुरू होती है"++++msgid "Receipt quantities now start at zero"++msgstr "प्राप्ति की मात्रा अब शून्य से शुरू होती है"++msgid "Receipt Requested Date"msgstr "प्राप्ति अनुरोधित तिथि"diff --cc packages/locale/locales/it/erp.poindex c455187ec3,6ecb0a1524..7634ca0c6f--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Righe di ricezionemsgid "Receipt Promised Date"msgstr "Data di Consegna Promessa"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "Le quantità di entrata merci ora iniziano da quella da ricevere"++++msgid "Receipt quantities now start at zero"++msgstr "Le quantità di entrata merci ora iniziano da zero"++msgid "Receipt Requested Date"msgstr "Data di ricezione richiesta"diff --cc packages/locale/locales/ja/erp.poindex 4af0858b3b,c56e7b9e0e..0e901ec94d--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "領収書行msgid "Receipt Promised Date"msgstr "入荷回答納期"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "入荷数量が入荷待ち数量から開始されるようになりました"++++msgid "Receipt quantities now start at zero"++msgstr "入荷数量がゼロから開始されるようになりました"++msgid "Receipt Requested Date"msgstr "入荷希望納期"diff --cc packages/locale/locales/ko/erp.poindex e5ad12ae8e,3afb325dcf..d73fadd488--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "입고 라인msgid "Receipt Promised Date"msgstr "입고 약속일"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "입고 수량이 이제 입고 대기 수량부터 시작합니다"++++msgid "Receipt quantities now start at zero"++msgstr "입고 수량이 이제 0부터 시작합니다"++msgid "Receipt Requested Date"msgstr "입고 요청일"diff --cc packages/locale/locales/pl/erp.poindex b85b3b8340,5aa1c106bb..4e70a571f5--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Linie przyjęciamsgid "Receipt Promised Date"msgstr "Data potwierdzona przyjęcia"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "Ilości przyjęcia teraz zaczynają się od ilości do przyjęcia"++++msgid "Receipt quantities now start at zero"++msgstr "Ilości przyjęcia teraz zaczynają się od zera"++msgid "Receipt Requested Date"msgstr "Data żądanego odbioru"diff --cc packages/locale/locales/pt/erp.poindex 7560ca2bff,c719a08618..67a2b2ee4e--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Linhas de Recebimentomsgid "Receipt Promised Date"msgstr "Data de Entrega Prometida"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "As quantidades do recebimento agora começam na quantidade a receber"++++msgid "Receipt quantities now start at zero"++msgstr "As quantidades do recebimento agora começam em zero"++msgid "Receipt Requested Date"msgstr "Data de Recebimento Solicitada"diff --cc packages/locale/locales/ru/erp.poindex 35f225d849,aeaff95bf8..e3d63c4f41--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Строки квитанцииmsgid "Receipt Promised Date"msgstr "Подтвержденная дата поступления"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "Количества в поступлениях теперь начинаются с остатка к приемке"++++msgid "Receipt quantities now start at zero"++msgstr "Количества в поступлениях теперь начинаются с нуля"++msgid "Receipt Requested Date"msgstr "Запрошенная дата получения"diff --cc packages/locale/locales/tr/erp.poindex c48f5ac27c,5ce323c9f8..d71df97bc7--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "Mal Kabul Edilen Satırlarmsgid "Receipt Promised Date"msgstr "Mal kabul taahhüt tarihi"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "Mal kabul miktarları artık alınacak miktarla başlıyor"++++msgid "Receipt quantities now start at zero"++msgstr "Mal kabul miktarları artık sıfırdan başlıyor"++msgid "Receipt Requested Date"msgstr "Talep Edilen Teslim Tarihi"diff --cc packages/locale/locales/zh/erp.poindex 860c311787,89e9ddc874..f14864633b--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@@ -17891,6 -18202,6 +18214,12 @@@ msgstr "收据行msgid "Receipt Promised Date"msgstr "收货承诺日期"++msgid "Receipt quantities now start at the quantity to receive"++msgstr "收货数量现在从待收货数量开始"++++msgid "Receipt quantities now start at zero"++msgstr "收货数量现在从零开始"++msgid "Receipt Requested Date"msgstr "收货要求日期"