@litusarchieve18/agricore-utils 1.0.29 → 1.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/constants.js CHANGED
@@ -66,6 +66,7 @@ __export(constants_exports, {
66
66
  ROLE_SECTIONS_BY_KEY: () => ROLE_SECTIONS_BY_KEY,
67
67
  RelationshipType: () => RelationshipType,
68
68
  RowOrientation: () => RowOrientation,
69
+ SCOPE_LEVELS: () => SCOPE_LEVELS,
69
70
  SENTINEL_UUID: () => SENTINEL_UUID,
70
71
  SESSION_SCHEMA: () => SESSION_SCHEMA,
71
72
  SIGNATURE_MODES: () => SIGNATURE_MODES,
@@ -73,7 +74,6 @@ __export(constants_exports, {
73
74
  StockPolicyTier: () => StockPolicyTier,
74
75
  StoragePhases: () => StoragePhases,
75
76
  TASK_TYPE_REGISTRY: () => TASK_TYPE_REGISTRY,
76
- TEMPLATE_SCOPE_LEVELS: () => TEMPLATE_SCOPE_LEVELS,
77
77
  TargetEntityType: () => TargetEntityType,
78
78
  TaskStatus: () => TaskStatus,
79
79
  TaskType: () => TaskType,
@@ -467,6 +467,12 @@ var RESOURCE_PATHS = {
467
467
  farmManagement: "operations.farmManagement",
468
468
  packhouse: "operations.packhouse",
469
469
  accommodation: "operations.accommodation",
470
+ logistics: "operations.logistics",
471
+ logisticsReceival: "operations.logistics.receival",
472
+ logisticsReceivalReview: "operations.logistics.receival.review",
473
+ // being reviewed by manager/owner
474
+ logisticsDispatch: "operations.logistics.dispatch",
475
+ logisticsDispatchReview: "operations.logistics.dispatch.review",
470
476
  // ── Inventory ────────────────────────────────────────────────────────────
471
477
  // === Consumables ===
472
478
  inventory: "inventory",
@@ -502,6 +508,7 @@ var RESOURCE_PATHS = {
502
508
  equipFuelRegister: "equipment.fuelRegister",
503
509
  equipCalibration: "equipment.calibration",
504
510
  equipFleet: "equipment.fleetManagement",
511
+ // ── Finance ──────────────────────────────────────────────────────
505
512
  finance: "finance",
506
513
  financeProductRequisition: "finance.product.requistion",
507
514
  financeDashboard: "finance.dashboard",
@@ -565,12 +572,23 @@ var RESOURCE_MODULE_MAP = {
565
572
  [RESOURCE_PATHS.farmManagement]: [EnabledModule.FARM_MANAGEMENT],
566
573
  [RESOURCE_PATHS.packhouse]: [EnabledModule.PACKHOUSE],
567
574
  [RESOURCE_PATHS.accommodation]: [EnabledModule.ACCOMMODATION],
575
+ // ── Logistics ──────────────────────────────────────────────────────────────
576
+ [RESOURCE_PATHS.logistics]: ALL_OPERATIONS,
577
+ [RESOURCE_PATHS.logisticsReceival]: ALL_OPERATIONS,
578
+ [RESOURCE_PATHS.logisticsReceivalReview]: ALL_OPERATIONS,
579
+ [RESOURCE_PATHS.logisticsDispatch]: ALL_OPERATIONS,
580
+ [RESOURCE_PATHS.logisticsDispatchReview]: ALL_OPERATIONS,
568
581
  // ── Equipment & Fleet ──────────────────────────────────────────────────────
569
582
  [RESOURCE_PATHS.equipPreStart]: ALL_OPERATIONS,
570
583
  [RESOURCE_PATHS.equipMaintenance]: ALL_OPERATIONS,
571
584
  [RESOURCE_PATHS.equipFuelRegister]: ALL_OPERATIONS,
572
585
  [RESOURCE_PATHS.equipCalibration]: AGRI_ONLY,
573
586
  [RESOURCE_PATHS.equipFleet]: ALL_OPERATIONS,
587
+ // ── Finance ──────────────────────────────────────────────────────────────
588
+ [RESOURCE_PATHS.financeProductRequisition]: ALL_OPERATIONS,
589
+ [RESOURCE_PATHS.financeDashboard]: ALL_OPERATIONS,
590
+ [RESOURCE_PATHS.financeTransaction]: ALL_OPERATIONS,
591
+ [RESOURCE_PATHS.financeBudgetAllocation]: ALL_OPERATIONS,
574
592
  // ── Safety, Quality & Compliance ──────────────────────────────────────────
575
593
  [RESOURCE_PATHS.safetyAuditing]: ALL_OPERATIONS,
576
594
  [RESOURCE_PATHS.safetyFood]: AGRI_ONLY,
@@ -619,6 +637,15 @@ var RESOURCE_REQUIREMENTS = {
619
637
  allowedRoles: [UserRole.OWNER, UserRole.MANAGER, UserRole.SUPERVISOR],
620
638
  requiredPrivileges: [UserPrivilege.ADMIN, UserPrivilege.AUDIT_COMPLIANCE, UserPrivilege.FINANCE, UserPrivilege.DOCUMENT]
621
639
  },
640
+ // ── Logistics ──────────────────────────────────────────────────────────────
641
+ [RESOURCE_PATHS.logisticsReceival]: {
642
+ allowedRoles: EVERYONE
643
+ },
644
+ [RESOURCE_PATHS.logisticsReceivalReview]: {
645
+ allowedRoles: [UserRole.OWNER, UserRole.MANAGER, UserRole.SUPERVISOR]
646
+ },
647
+ [RESOURCE_PATHS.logisticsDispatch]: { allowedRoles: EVERYONE },
648
+ [RESOURCE_PATHS.logisticsDispatchReview]: { allowedRoles: [UserRole.OWNER, UserRole.MANAGER, UserRole.SUPERVISOR] },
622
649
  // CONSUMABLES PERMISSIONS
623
650
  [RESOURCE_PATHS.inventoryConsumableProduct]: {
624
651
  allowedRoles: [UserRole.OWNER, UserRole.MANAGER, UserRole.SUPERVISOR]
@@ -733,6 +760,7 @@ var DocumentType = /* @__PURE__ */ ((DocumentType2) => {
733
760
  DocumentType2["PACKHOUSE_INSPECTION"] = "PACKHOUSE_INSPECTION";
734
761
  DocumentType2["TRAINING_CERTIFICATE"] = "TRAINING_CERTIFICATE";
735
762
  DocumentType2["INVOICE"] = "INVOICE";
763
+ DocumentType2["PURCHASE"] = "PURCHASE";
736
764
  DocumentType2["LEGAL_CONTRACT"] = "LEGAL_CONTRACT";
737
765
  DocumentType2["AUDIT_REPORT"] = "AUDIT_REPORT";
738
766
  DocumentType2["SENSITIVE_IDENTITY"] = "SENSITIVE_IDENTITY";
@@ -746,6 +774,7 @@ var DocumentCategory = /* @__PURE__ */ ((DocumentCategory2) => {
746
774
  DocumentCategory2["ASSETS_MAINT"] = "Assets & Maintenance";
747
775
  DocumentCategory2["HR_LEGAL_SAFETY"] = "HR, Legal & Safety";
748
776
  DocumentCategory2["FINANCE_ADMIN"] = "Finance & Admin";
777
+ DocumentCategory2["LOGISTICS"] = "Logistics";
749
778
  return DocumentCategory2;
750
779
  })(DocumentCategory || {});
751
780
  var DOCUMENT_DISPLAY_INFO = {
@@ -920,6 +949,12 @@ var DOCUMENT_DISPLAY_INFO = {
920
949
  label: "Supplier Invoices",
921
950
  description: "Billing records for inputs, utilities, and services.",
922
951
  category: "Finance & Admin" /* FINANCE_ADMIN */
952
+ },
953
+ // --- LOGISTICS ---
954
+ ["PURCHASE" /* PURCHASE */]: {
955
+ label: "Purchase Orders",
956
+ description: "Purchase orders for goods and services.",
957
+ category: "Logistics" /* LOGISTICS */
923
958
  }
924
959
  };
925
960
  var CATEGORY_TABS = [
@@ -957,6 +992,7 @@ var DOCUMENT_MENU_MAP = {
957
992
  ["HARVEST_LOG" /* HARVEST_LOG */]: [RESOURCE_PATHS.farmManagement],
958
993
  ["PACKHOUSE_INSPECTION" /* PACKHOUSE_INSPECTION */]: [RESOURCE_PATHS.packhouse],
959
994
  ["INVOICE" /* INVOICE */]: [RESOURCE_PATHS.documentHub],
995
+ ["PURCHASE" /* PURCHASE */]: [RESOURCE_PATHS.logistics],
960
996
  ["LEGAL_CONTRACT" /* LEGAL_CONTRACT */]: [RESOURCE_PATHS.documentHub],
961
997
  ["AUDIT_REPORT" /* AUDIT_REPORT */]: [RESOURCE_PATHS.safetyAuditing, RESOURCE_PATHS.dashboard],
962
998
  ["SENSITIVE_IDENTITY" /* SENSITIVE_IDENTITY */]: [RESOURCE_PATHS.adminUserRoster]
@@ -973,10 +1009,10 @@ var CORRECTIVE_ACTION_STATUSES = {
973
1009
  CLOSED: "closed",
974
1010
  FAILED: "failed"
975
1011
  };
976
- var TEMPLATE_SCOPE_LEVELS = {
977
- FACILITY: "facility",
978
- LEGAL_ENTITY: "legalEntity",
979
- COMPANY: "company"
1012
+ var SCOPE_LEVELS = {
1013
+ COMPANY: "company",
1014
+ LEGAL_ENTITY: "legal_entity",
1015
+ FACILITY: "facility"
980
1016
  };
981
1017
  var CORRECTIVE_ACTION_GENERATION_SOURCES = {
982
1018
  CREATE: "CREATE",
@@ -1042,6 +1078,42 @@ var StockPolicyTier = {
1042
1078
  BY_STORAGE_PHASE: 2,
1043
1079
  BY_LOCATION: 3
1044
1080
  };
1081
+ var PRODUCT_TYPE_TO_BUDGET_CATEGORY = Object.freeze({
1082
+ carton: "packaging",
1083
+ tray: "packaging",
1084
+ liner: "packaging",
1085
+ label: "packaging",
1086
+ tape: "packaging",
1087
+ strapping: "packaging",
1088
+ pallet: "packaging",
1089
+ stretch_wrap: "packaging",
1090
+ other: "general"
1091
+ // fallback — reviewer must confirm at Step 3
1092
+ });
1093
+ var TERM_RESOLUTION_MODES = Object.freeze({
1094
+ SUPPLIER_LEVEL: "SUPPLIER_LEVEL",
1095
+ PRODUCT_LEVEL: "PRODUCT_LEVEL"
1096
+ });
1097
+ var REQUISITION_STATUSES = Object.freeze({
1098
+ DRAFT: "draft",
1099
+ PENDING_FINANCE: "pending_finance",
1100
+ APPROVED: "approved",
1101
+ REJECTED: "rejected",
1102
+ ORDERED: "ordered"
1103
+ });
1104
+ var PO_STATUSES = Object.freeze({
1105
+ NEW: "new",
1106
+ ACKNOWLEDGED: "acknowledged",
1107
+ IN_PROGRESS: "in_progress",
1108
+ SHIPPED: "shipped",
1109
+ RECEIVED: "received",
1110
+ CANCELLED: "cancelled"
1111
+ });
1112
+ var PREFLIGHT_CHECK_STATUSES = Object.freeze({
1113
+ OK: "ok",
1114
+ WARNING: "warning",
1115
+ BLOCKED: "blocked"
1116
+ });
1045
1117
  // Annotate the CommonJS export names for ESM import in node:
1046
1118
  0 && (module.exports = {
1047
1119
  ACCESS_RANK,
@@ -1090,6 +1162,7 @@ var StockPolicyTier = {
1090
1162
  ROLE_SECTIONS_BY_KEY,
1091
1163
  RelationshipType,
1092
1164
  RowOrientation,
1165
+ SCOPE_LEVELS,
1093
1166
  SENTINEL_UUID,
1094
1167
  SESSION_SCHEMA,
1095
1168
  SIGNATURE_MODES,
@@ -1097,7 +1170,6 @@ var StockPolicyTier = {
1097
1170
  StockPolicyTier,
1098
1171
  StoragePhases,
1099
1172
  TASK_TYPE_REGISTRY,
1100
- TEMPLATE_SCOPE_LEVELS,
1101
1173
  TargetEntityType,
1102
1174
  TaskStatus,
1103
1175
  TaskType,
@@ -45,6 +45,7 @@ import {
45
45
  ROLE_SECTIONS_BY_KEY,
46
46
  RelationshipType,
47
47
  RowOrientation,
48
+ SCOPE_LEVELS,
48
49
  SENTINEL_UUID,
49
50
  SESSION_SCHEMA,
50
51
  SIGNATURE_MODES,
@@ -52,7 +53,6 @@ import {
52
53
  StockPolicyTier,
53
54
  StoragePhases,
54
55
  TASK_TYPE_REGISTRY,
55
- TEMPLATE_SCOPE_LEVELS,
56
56
  TargetEntityType,
57
57
  TaskStatus,
58
58
  TaskType,
@@ -62,7 +62,7 @@ import {
62
62
  UserRole,
63
63
  VigorRating,
64
64
  WaterSource
65
- } from "./chunk-Y5KVDVNY.mjs";
65
+ } from "./chunk-OSHR422C.mjs";
66
66
  export {
67
67
  ACCESS_RANK,
68
68
  ACT,
@@ -110,6 +110,7 @@ export {
110
110
  ROLE_SECTIONS_BY_KEY,
111
111
  RelationshipType,
112
112
  RowOrientation,
113
+ SCOPE_LEVELS,
113
114
  SENTINEL_UUID,
114
115
  SESSION_SCHEMA,
115
116
  SIGNATURE_MODES,
@@ -117,7 +118,6 @@ export {
117
118
  StockPolicyTier,
118
119
  StoragePhases,
119
120
  TASK_TYPE_REGISTRY,
120
- TEMPLATE_SCOPE_LEVELS,
121
121
  TargetEntityType,
122
122
  TaskStatus,
123
123
  TaskType,
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { d as AgriCoreSession, aR as UserRoleAssignment, aL as Tier, a8 as PriceConflictCandidate, av as ShadowedCleanMatch, ab as PricingDataSource, aa as PricingContext, a9 as PriceResolutionResult, au as ScopeType, aV as WireSession, an as ResourceRequirement, c as AccessLevelType, j as AvailableScope, V as InfrastructureFields, T as FormMeta, aF as TabConfig, al as ResolvedError } from './constants-CrAPx_xU.mjs';
2
- export { A as ACCESS_RANK, a as ACT, b as AccessLevel, e as ApprovalStatus, f as ApprovalType, g as AuditStatus, h as AuditType, i as AuthScopeFields, B as BarcodeNamespace, k as BarcodeNamespaceType, l as BarcodeType, m as BarcodeTypeType, n as Base44Id, o as BaseProductRow, C as CAR_SUPPORTED_EVIDENCE_MIME_TYPES, p as CAR_SUPPORTED_SIGNATURE_MIME_TYPES, q as CAT, r as CATEGORY_TABS, s as CORRECTIVE_ACTION_GENERATION_SOURCES, t as CORRECTIVE_ACTION_STATUSES, u as CanonicalId, v as CarSupportedEvidenceMimeType, w as CarSupportedSignatureMimeType, x as CarTemplateFileMetadata, y as CatalogSyncStatus, z as CatalogSyncStatusType, D as CompanyConfig, E as CorrectiveActionCompileTaskMetadata, F as CorrectiveActionGenerationSource, G as CorrectiveActionStatus, H as CropCycleStatus, I as DOCUMENT_DISPLAY_INFO, J as DOCUMENT_MENU_MAP, K as DocumentCategory, L as DocumentType, M as ERROR_DICTIONARY, N as EVERYONE, O as EmitterType, P as EnabledModule, Q as FORM_REGISTRY, R as FacilityType, S as FileUploadTaskType, U as HarvestMethod, W as LinkedStatus, X as MOD, Y as MODULE_LABELS, Z as MatrixRow, _ as MicroclimateZone, $ as MimeType, a0 as ModCode, a1 as NettingType, a2 as NormalizedSignatureValue, a3 as NotificationMode, a4 as OrderStatus, a5 as PermissionLevel, a6 as PhysicalState, a7 as PlantingMethod, ac as ProductType, ad as ProductTypeType, ae as ProductUnit, af as ProductUnitType, ag as RESOURCE_MODULE_MAP, ah as RESOURCE_PATHS, ai as RESOURCE_REQUIREMENTS, aj as ROLE_SECTIONS_BY_KEY, ak as RelationshipType, am as ResourceOverrides, ao as RoleAssignment, ap as RowOrientation, aq as SENTINEL_UUID, ar as SESSION_SCHEMA, as as SIGNATURE_MODES, at as SchemaField, aw as SignatureInput, ax as SignatureMode, ay as SoilTexture, az as StockPolicyTier, aA as StockPolicyTierType, aB as StoragePhases, aC as StorageType, aD as TASK_TYPE_REGISTRY, aE as TEMPLATE_SCOPE_LEVELS, aG as TargetEntityType, aH as TaskStatus, aI as TaskType, aJ as TaskTypeConfig, aK as TemplateScopeLevel, aM as TransactionType, aN as TrellisType, aO as UserPrivilege, aP as UserPrivilegeType, aQ as UserRole, aS as UserRoleType, aT as VigorRating, aU as WaterSource } from './constants-CrAPx_xU.mjs';
1
+ import { d as AgriCoreSession, aW as UserRoleAssignment, aQ as Tier, ad as PriceConflictCandidate, aB as ShadowedCleanMatch, ag as PricingDataSource, af as PricingContext, ae as PriceResolutionResult, u as CalculatePaymentDueDateInput, aA as ScopeType, a_ as WireSession, as as ResourceRequirement, c as AccessLevelType, j as AvailableScope, Y as InfrastructureFields, V as FormMeta, aK as TabConfig, aq as ResolvedError } from './constants-KqcPqiCa.mjs';
2
+ export { A as ACCESS_RANK, a as ACT, b as AccessLevel, e as ApprovalStatus, f as ApprovalType, g as AuditStatus, h as AuditType, i as AuthScopeFields, B as BarcodeNamespace, k as BarcodeNamespaceType, l as BarcodeType, m as BarcodeTypeType, n as Base44Id, o as BaseProductRow, C as CAR_SUPPORTED_EVIDENCE_MIME_TYPES, p as CAR_SUPPORTED_SIGNATURE_MIME_TYPES, q as CAT, r as CATEGORY_TABS, s as CORRECTIVE_ACTION_GENERATION_SOURCES, t as CORRECTIVE_ACTION_STATUSES, v as CanonicalId, w as CarSupportedEvidenceMimeType, x as CarSupportedSignatureMimeType, y as CarTemplateFileMetadata, z as CatalogSyncStatus, D as CatalogSyncStatusType, E as CompanyConfig, F as CorrectiveActionCompileTaskMetadata, G as CorrectiveActionGenerationSource, H as CorrectiveActionStatus, I as CreditDaysWindow, J as CropCycleStatus, K as DOCUMENT_DISPLAY_INFO, L as DOCUMENT_MENU_MAP, M as DocumentCategory, N as DocumentType, O as ERROR_DICTIONARY, P as EVERYONE, Q as EmitterType, R as EnabledModule, S as FORM_REGISTRY, T as FacilityType, U as FileUploadTaskType, W as ForwardOrderingContractWindow, X as HarvestMethod, Z as InstallmentWindow, _ as LinkedStatus, $ as MOD, a0 as MODULE_LABELS, a1 as MatrixRow, a2 as MicroclimateZone, a3 as MimeType, a4 as ModCode, a5 as NettingType, a6 as NormalizedSignatureValue, a7 as NotificationMode, a8 as OrderStatus, a9 as PaymentTerm, aa as PermissionLevel, ab as PhysicalState, ac as PlantingMethod, ah as ProductType, ai as ProductTypeType, aj as ProductUnit, ak as ProductUnitType, al as RESOURCE_MODULE_MAP, am as RESOURCE_PATHS, an as RESOURCE_REQUIREMENTS, ao as ROLE_SECTIONS_BY_KEY, ap as RelationshipType, ar as ResourceOverrides, at as RoleAssignment, au as RowOrientation, av as SCOPE_LEVELS, aw as SENTINEL_UUID, ax as SESSION_SCHEMA, ay as SIGNATURE_MODES, az as SchemaField, aC as SignatureInput, aD as SignatureMode, aE as SoilTexture, aF as StockPolicyTier, aG as StockPolicyTierType, aH as StoragePhases, aI as StorageType, aJ as TASK_TYPE_REGISTRY, aL as TargetEntityType, aM as TaskStatus, aN as TaskType, aO as TaskTypeConfig, aP as TemplateScopeLevel, aR as TransactionType, aS as TrellisType, aT as UserPrivilege, aU as UserPrivilegeType, aV as UserRole, aX as UserRoleType, aY as VigorRating, aZ as WaterSource } from './constants-KqcPqiCa.mjs';
3
3
 
4
4
  declare const AgriLogger: {
5
5
  log(level: "INFO" | "WARN" | "ERROR", message: string, meta: any): void;
@@ -54,6 +54,50 @@ declare function findOverlappingPriceWindows(db: any, scope: OverlapCheckScope,
54
54
  validTo: string | null;
55
55
  }, excludeId?: string): Promise<PriceConflictCandidate[]>;
56
56
 
57
+ /**
58
+ * Payment Due Date Calculation Utility
59
+ * ------------------------------------
60
+ * Computes `paymentDueDate` (or, for installments, the full due-date
61
+ * schedule) from a `transactionDate`, a `paymentTerm`, and term-specific
62
+ * config.
63
+ *
64
+ * Dates are handled as UTC-normalized "calendar dates" (year/month/day only)
65
+ * to avoid timezone/DST bugs when adding days or jumping months. If you pass
66
+ * in a Date with a time component, it's normalized to midnight UTC first,
67
+ * and results are also midnight UTC.
68
+ */
69
+
70
+ /**
71
+ * Returns a single `Date` for most payment terms, a `Date[]` for
72
+ * "thirdPartyInputFinance" (the full installment schedule), or `null` when
73
+ * the due date can't be determined yet from the info available so far
74
+ * (currently only "cashOnDelivery" before a deliveryDate is known).
75
+ *
76
+ * Designed to be called from one central place regardless of paymentTerm —
77
+ * e.g. at order creation, then again once delivery is confirmed. Callers
78
+ * should handle the `null` case as "not yet known, try again later" rather
79
+ * than treating it as an error.
80
+ *
81
+ * Narrow with Array.isArray() / === null at the call site as needed.
82
+ */
83
+ declare function calculatePaymentDueDate(input: CalculatePaymentDueDateInput): Date | Date[] | null;
84
+ /**
85
+ * True when the due date isn't determinable yet (currently only
86
+ * "cashOnDelivery" before deliveryDate is known). Call
87
+ * calculatePaymentDueDate() again later once the missing info is available.
88
+ */
89
+ declare function isDueDatePending(result: Date | Date[] | null): result is null;
90
+ /**
91
+ * True when the result is a single due date (all terms except
92
+ * "thirdPartyInputFinance", and excluding the pending/null case).
93
+ */
94
+ declare function isSingleDueDate(result: Date | Date[] | null): result is Date;
95
+ /**
96
+ * True when the result is a full installment schedule
97
+ * (paymentTerm === "thirdPartyInputFinance").
98
+ */
99
+ declare function isInstallmentSchedule(result: Date | Date[] | null): result is Date[];
100
+
57
101
  declare const Validator: {
58
102
  /** * 1. Email: The classic. Uses a standard RFC 5322 regex.
59
103
  */
@@ -177,10 +221,10 @@ declare function evaluateBaseAccess(resourcePath: string, session: AgriCoreSessi
177
221
  */
178
222
  declare function resolveEffectiveAccess(base: AccessLevelType, override?: AccessLevelType | null): AccessLevelType;
179
223
  declare function findSpecificOverride(session: AgriCoreSession, activeScopeId: string, resourcePath: string): AccessLevelType | null;
180
- declare function assertTenantBoundary(db: any, session: AgriCoreSession, // Pass the JWT session instead of just requesterCompanyId
181
- targets: {
224
+ declare function assertTenantBoundary(db: any, session: AgriCoreSession, targets: {
182
225
  targetUserId?: string;
183
226
  authScopeId?: string;
227
+ authScopeIds?: string[];
184
228
  expectedScopeType?: ScopeType;
185
229
  }): Promise<boolean>;
186
230
  declare function verifyAndExtractSession(token: string, secret: string): Promise<AgriCoreSession>;
@@ -215,4 +259,4 @@ declare function calculateFileMetadataMatch(criteria: {
215
259
  contextMatch?: string[];
216
260
  }, fileMetadata: Record<string, any>, auditContext: Record<string, any>): number;
217
261
 
218
- export { AccessLevelType, AggregatePriceAmbiguityError, AgriCoreSession, AgriLogger, AppError, AvailableScope, Converter, ErrorFactory, FormMeta, InfrastructureFields, type OverlapCheckScope, PriceAmbiguityError, PriceConflictCandidate, PriceResolutionResult, type PricingAdapterScope, PricingContext, PricingDataSource, ResolvedError, ResourceRequirement, ScopeType, ShadowedCleanMatch, TabConfig, Tier, UserRoleAssignment, Validator, WireSession, assertTenantBoundary, calculateFileMetadataMatch, createBase44PricingAdapter, decodeSession, encodeSession, evaluateBaseAccess, extractAppCode, findOverlappingPriceWindows, findSpecificOverride, generateCanonicalId, generateDocumentPath, generateInfrastructureFields, getAcceptedMimeTypes, getApproveAction, getFormMeta, getFormsGroupedByModule, getPrivilegesAt, getRoleAt, getScopeAncestry, getTaskTypeOptions, handleAppErrorResponse, hasPrivilegeAt, hasRoleAt, isTabVisible, isTabWritable, resolveAccess, resolveAppError, resolveEffectiveAccess, resolveError, resolvePrice, transformRoleAssignments, verifyAndExtractSession, withAgriLogging };
262
+ export { AccessLevelType, AggregatePriceAmbiguityError, AgriCoreSession, AgriLogger, AppError, AvailableScope, CalculatePaymentDueDateInput, Converter, ErrorFactory, FormMeta, InfrastructureFields, type OverlapCheckScope, PriceAmbiguityError, PriceConflictCandidate, PriceResolutionResult, type PricingAdapterScope, PricingContext, PricingDataSource, ResolvedError, ResourceRequirement, ScopeType, ShadowedCleanMatch, TabConfig, Tier, UserRoleAssignment, Validator, WireSession, assertTenantBoundary, calculateFileMetadataMatch, calculatePaymentDueDate, createBase44PricingAdapter, decodeSession, encodeSession, evaluateBaseAccess, extractAppCode, findOverlappingPriceWindows, findSpecificOverride, generateCanonicalId, generateDocumentPath, generateInfrastructureFields, getAcceptedMimeTypes, getApproveAction, getFormMeta, getFormsGroupedByModule, getPrivilegesAt, getRoleAt, getScopeAncestry, getTaskTypeOptions, handleAppErrorResponse, hasPrivilegeAt, hasRoleAt, isDueDatePending, isInstallmentSchedule, isSingleDueDate, isTabVisible, isTabWritable, resolveAccess, resolveAppError, resolveEffectiveAccess, resolveError, resolvePrice, transformRoleAssignments, verifyAndExtractSession, withAgriLogging };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { d as AgriCoreSession, aR as UserRoleAssignment, aL as Tier, a8 as PriceConflictCandidate, av as ShadowedCleanMatch, ab as PricingDataSource, aa as PricingContext, a9 as PriceResolutionResult, au as ScopeType, aV as WireSession, an as ResourceRequirement, c as AccessLevelType, j as AvailableScope, V as InfrastructureFields, T as FormMeta, aF as TabConfig, al as ResolvedError } from './constants-CrAPx_xU.js';
2
- export { A as ACCESS_RANK, a as ACT, b as AccessLevel, e as ApprovalStatus, f as ApprovalType, g as AuditStatus, h as AuditType, i as AuthScopeFields, B as BarcodeNamespace, k as BarcodeNamespaceType, l as BarcodeType, m as BarcodeTypeType, n as Base44Id, o as BaseProductRow, C as CAR_SUPPORTED_EVIDENCE_MIME_TYPES, p as CAR_SUPPORTED_SIGNATURE_MIME_TYPES, q as CAT, r as CATEGORY_TABS, s as CORRECTIVE_ACTION_GENERATION_SOURCES, t as CORRECTIVE_ACTION_STATUSES, u as CanonicalId, v as CarSupportedEvidenceMimeType, w as CarSupportedSignatureMimeType, x as CarTemplateFileMetadata, y as CatalogSyncStatus, z as CatalogSyncStatusType, D as CompanyConfig, E as CorrectiveActionCompileTaskMetadata, F as CorrectiveActionGenerationSource, G as CorrectiveActionStatus, H as CropCycleStatus, I as DOCUMENT_DISPLAY_INFO, J as DOCUMENT_MENU_MAP, K as DocumentCategory, L as DocumentType, M as ERROR_DICTIONARY, N as EVERYONE, O as EmitterType, P as EnabledModule, Q as FORM_REGISTRY, R as FacilityType, S as FileUploadTaskType, U as HarvestMethod, W as LinkedStatus, X as MOD, Y as MODULE_LABELS, Z as MatrixRow, _ as MicroclimateZone, $ as MimeType, a0 as ModCode, a1 as NettingType, a2 as NormalizedSignatureValue, a3 as NotificationMode, a4 as OrderStatus, a5 as PermissionLevel, a6 as PhysicalState, a7 as PlantingMethod, ac as ProductType, ad as ProductTypeType, ae as ProductUnit, af as ProductUnitType, ag as RESOURCE_MODULE_MAP, ah as RESOURCE_PATHS, ai as RESOURCE_REQUIREMENTS, aj as ROLE_SECTIONS_BY_KEY, ak as RelationshipType, am as ResourceOverrides, ao as RoleAssignment, ap as RowOrientation, aq as SENTINEL_UUID, ar as SESSION_SCHEMA, as as SIGNATURE_MODES, at as SchemaField, aw as SignatureInput, ax as SignatureMode, ay as SoilTexture, az as StockPolicyTier, aA as StockPolicyTierType, aB as StoragePhases, aC as StorageType, aD as TASK_TYPE_REGISTRY, aE as TEMPLATE_SCOPE_LEVELS, aG as TargetEntityType, aH as TaskStatus, aI as TaskType, aJ as TaskTypeConfig, aK as TemplateScopeLevel, aM as TransactionType, aN as TrellisType, aO as UserPrivilege, aP as UserPrivilegeType, aQ as UserRole, aS as UserRoleType, aT as VigorRating, aU as WaterSource } from './constants-CrAPx_xU.js';
1
+ import { d as AgriCoreSession, aW as UserRoleAssignment, aQ as Tier, ad as PriceConflictCandidate, aB as ShadowedCleanMatch, ag as PricingDataSource, af as PricingContext, ae as PriceResolutionResult, u as CalculatePaymentDueDateInput, aA as ScopeType, a_ as WireSession, as as ResourceRequirement, c as AccessLevelType, j as AvailableScope, Y as InfrastructureFields, V as FormMeta, aK as TabConfig, aq as ResolvedError } from './constants-KqcPqiCa.js';
2
+ export { A as ACCESS_RANK, a as ACT, b as AccessLevel, e as ApprovalStatus, f as ApprovalType, g as AuditStatus, h as AuditType, i as AuthScopeFields, B as BarcodeNamespace, k as BarcodeNamespaceType, l as BarcodeType, m as BarcodeTypeType, n as Base44Id, o as BaseProductRow, C as CAR_SUPPORTED_EVIDENCE_MIME_TYPES, p as CAR_SUPPORTED_SIGNATURE_MIME_TYPES, q as CAT, r as CATEGORY_TABS, s as CORRECTIVE_ACTION_GENERATION_SOURCES, t as CORRECTIVE_ACTION_STATUSES, v as CanonicalId, w as CarSupportedEvidenceMimeType, x as CarSupportedSignatureMimeType, y as CarTemplateFileMetadata, z as CatalogSyncStatus, D as CatalogSyncStatusType, E as CompanyConfig, F as CorrectiveActionCompileTaskMetadata, G as CorrectiveActionGenerationSource, H as CorrectiveActionStatus, I as CreditDaysWindow, J as CropCycleStatus, K as DOCUMENT_DISPLAY_INFO, L as DOCUMENT_MENU_MAP, M as DocumentCategory, N as DocumentType, O as ERROR_DICTIONARY, P as EVERYONE, Q as EmitterType, R as EnabledModule, S as FORM_REGISTRY, T as FacilityType, U as FileUploadTaskType, W as ForwardOrderingContractWindow, X as HarvestMethod, Z as InstallmentWindow, _ as LinkedStatus, $ as MOD, a0 as MODULE_LABELS, a1 as MatrixRow, a2 as MicroclimateZone, a3 as MimeType, a4 as ModCode, a5 as NettingType, a6 as NormalizedSignatureValue, a7 as NotificationMode, a8 as OrderStatus, a9 as PaymentTerm, aa as PermissionLevel, ab as PhysicalState, ac as PlantingMethod, ah as ProductType, ai as ProductTypeType, aj as ProductUnit, ak as ProductUnitType, al as RESOURCE_MODULE_MAP, am as RESOURCE_PATHS, an as RESOURCE_REQUIREMENTS, ao as ROLE_SECTIONS_BY_KEY, ap as RelationshipType, ar as ResourceOverrides, at as RoleAssignment, au as RowOrientation, av as SCOPE_LEVELS, aw as SENTINEL_UUID, ax as SESSION_SCHEMA, ay as SIGNATURE_MODES, az as SchemaField, aC as SignatureInput, aD as SignatureMode, aE as SoilTexture, aF as StockPolicyTier, aG as StockPolicyTierType, aH as StoragePhases, aI as StorageType, aJ as TASK_TYPE_REGISTRY, aL as TargetEntityType, aM as TaskStatus, aN as TaskType, aO as TaskTypeConfig, aP as TemplateScopeLevel, aR as TransactionType, aS as TrellisType, aT as UserPrivilege, aU as UserPrivilegeType, aV as UserRole, aX as UserRoleType, aY as VigorRating, aZ as WaterSource } from './constants-KqcPqiCa.js';
3
3
 
4
4
  declare const AgriLogger: {
5
5
  log(level: "INFO" | "WARN" | "ERROR", message: string, meta: any): void;
@@ -54,6 +54,50 @@ declare function findOverlappingPriceWindows(db: any, scope: OverlapCheckScope,
54
54
  validTo: string | null;
55
55
  }, excludeId?: string): Promise<PriceConflictCandidate[]>;
56
56
 
57
+ /**
58
+ * Payment Due Date Calculation Utility
59
+ * ------------------------------------
60
+ * Computes `paymentDueDate` (or, for installments, the full due-date
61
+ * schedule) from a `transactionDate`, a `paymentTerm`, and term-specific
62
+ * config.
63
+ *
64
+ * Dates are handled as UTC-normalized "calendar dates" (year/month/day only)
65
+ * to avoid timezone/DST bugs when adding days or jumping months. If you pass
66
+ * in a Date with a time component, it's normalized to midnight UTC first,
67
+ * and results are also midnight UTC.
68
+ */
69
+
70
+ /**
71
+ * Returns a single `Date` for most payment terms, a `Date[]` for
72
+ * "thirdPartyInputFinance" (the full installment schedule), or `null` when
73
+ * the due date can't be determined yet from the info available so far
74
+ * (currently only "cashOnDelivery" before a deliveryDate is known).
75
+ *
76
+ * Designed to be called from one central place regardless of paymentTerm —
77
+ * e.g. at order creation, then again once delivery is confirmed. Callers
78
+ * should handle the `null` case as "not yet known, try again later" rather
79
+ * than treating it as an error.
80
+ *
81
+ * Narrow with Array.isArray() / === null at the call site as needed.
82
+ */
83
+ declare function calculatePaymentDueDate(input: CalculatePaymentDueDateInput): Date | Date[] | null;
84
+ /**
85
+ * True when the due date isn't determinable yet (currently only
86
+ * "cashOnDelivery" before deliveryDate is known). Call
87
+ * calculatePaymentDueDate() again later once the missing info is available.
88
+ */
89
+ declare function isDueDatePending(result: Date | Date[] | null): result is null;
90
+ /**
91
+ * True when the result is a single due date (all terms except
92
+ * "thirdPartyInputFinance", and excluding the pending/null case).
93
+ */
94
+ declare function isSingleDueDate(result: Date | Date[] | null): result is Date;
95
+ /**
96
+ * True when the result is a full installment schedule
97
+ * (paymentTerm === "thirdPartyInputFinance").
98
+ */
99
+ declare function isInstallmentSchedule(result: Date | Date[] | null): result is Date[];
100
+
57
101
  declare const Validator: {
58
102
  /** * 1. Email: The classic. Uses a standard RFC 5322 regex.
59
103
  */
@@ -177,10 +221,10 @@ declare function evaluateBaseAccess(resourcePath: string, session: AgriCoreSessi
177
221
  */
178
222
  declare function resolveEffectiveAccess(base: AccessLevelType, override?: AccessLevelType | null): AccessLevelType;
179
223
  declare function findSpecificOverride(session: AgriCoreSession, activeScopeId: string, resourcePath: string): AccessLevelType | null;
180
- declare function assertTenantBoundary(db: any, session: AgriCoreSession, // Pass the JWT session instead of just requesterCompanyId
181
- targets: {
224
+ declare function assertTenantBoundary(db: any, session: AgriCoreSession, targets: {
182
225
  targetUserId?: string;
183
226
  authScopeId?: string;
227
+ authScopeIds?: string[];
184
228
  expectedScopeType?: ScopeType;
185
229
  }): Promise<boolean>;
186
230
  declare function verifyAndExtractSession(token: string, secret: string): Promise<AgriCoreSession>;
@@ -215,4 +259,4 @@ declare function calculateFileMetadataMatch(criteria: {
215
259
  contextMatch?: string[];
216
260
  }, fileMetadata: Record<string, any>, auditContext: Record<string, any>): number;
217
261
 
218
- export { AccessLevelType, AggregatePriceAmbiguityError, AgriCoreSession, AgriLogger, AppError, AvailableScope, Converter, ErrorFactory, FormMeta, InfrastructureFields, type OverlapCheckScope, PriceAmbiguityError, PriceConflictCandidate, PriceResolutionResult, type PricingAdapterScope, PricingContext, PricingDataSource, ResolvedError, ResourceRequirement, ScopeType, ShadowedCleanMatch, TabConfig, Tier, UserRoleAssignment, Validator, WireSession, assertTenantBoundary, calculateFileMetadataMatch, createBase44PricingAdapter, decodeSession, encodeSession, evaluateBaseAccess, extractAppCode, findOverlappingPriceWindows, findSpecificOverride, generateCanonicalId, generateDocumentPath, generateInfrastructureFields, getAcceptedMimeTypes, getApproveAction, getFormMeta, getFormsGroupedByModule, getPrivilegesAt, getRoleAt, getScopeAncestry, getTaskTypeOptions, handleAppErrorResponse, hasPrivilegeAt, hasRoleAt, isTabVisible, isTabWritable, resolveAccess, resolveAppError, resolveEffectiveAccess, resolveError, resolvePrice, transformRoleAssignments, verifyAndExtractSession, withAgriLogging };
262
+ export { AccessLevelType, AggregatePriceAmbiguityError, AgriCoreSession, AgriLogger, AppError, AvailableScope, CalculatePaymentDueDateInput, Converter, ErrorFactory, FormMeta, InfrastructureFields, type OverlapCheckScope, PriceAmbiguityError, PriceConflictCandidate, PriceResolutionResult, type PricingAdapterScope, PricingContext, PricingDataSource, ResolvedError, ResourceRequirement, ScopeType, ShadowedCleanMatch, TabConfig, Tier, UserRoleAssignment, Validator, WireSession, assertTenantBoundary, calculateFileMetadataMatch, calculatePaymentDueDate, createBase44PricingAdapter, decodeSession, encodeSession, evaluateBaseAccess, extractAppCode, findOverlappingPriceWindows, findSpecificOverride, generateCanonicalId, generateDocumentPath, generateInfrastructureFields, getAcceptedMimeTypes, getApproveAction, getFormMeta, getFormsGroupedByModule, getPrivilegesAt, getRoleAt, getScopeAncestry, getTaskTypeOptions, handleAppErrorResponse, hasPrivilegeAt, hasRoleAt, isDueDatePending, isInstallmentSchedule, isSingleDueDate, isTabVisible, isTabWritable, resolveAccess, resolveAppError, resolveEffectiveAccess, resolveError, resolvePrice, transformRoleAssignments, verifyAndExtractSession, withAgriLogging };