@robosystems/client 2.31.0 → 2.33.0

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.
@@ -368,34 +368,194 @@ export interface LedgerReconciliationPolicy {
368
368
  /** Statement reconciliations only; null for any other. */
369
369
  statementCycle: StatementCycle | null;
370
370
  }
371
+ export type ScheduleMethod = 'straight_line' | 'custom' | 'effective_interest';
372
+ /** The columns of a loan schedule's amortization table a leg can post. */
373
+ export type ScheduleCurveColumn = 'interest' | 'interest_paid' | 'principal' | 'payment';
374
+ export type ScheduleDayCount = '30/360' | 'actual/365' | 'actual/360';
375
+ export type SchedulePaymentFrequency = 'monthly' | 'quarterly' | 'annual' | 'at_maturity';
376
+ /** One line of the entry a loan schedule drafts each period. */
377
+ export interface ScheduleLeg {
378
+ elementId: string;
379
+ side: 'debit' | 'credit';
380
+ /**
381
+ * The amortization-table column the line takes each period: `interest`
382
+ * (accrued in the period), `interest_paid` (accrued interest settled by
383
+ * the period's payment), `principal` (principal repaid), `payment`
384
+ * (interest_paid + principal).
385
+ */
386
+ amountSource: ScheduleCurveColumn;
387
+ }
388
+ /** The terms a loan schedule's amortization table is computed from. */
389
+ export interface LoanTerms {
390
+ /** Principal drawn, in cents. */
391
+ principal: number;
392
+ /** Annual interest rate as a fraction: 0.099 for 9.9%. */
393
+ annualRate: number;
394
+ /** The day the principal was drawn (YYYY-MM-DD); falls in the schedule's first month. */
395
+ startDate: string;
396
+ /** `30/360` (default), `actual/365`, or `actual/360` (the usual bank line of credit). */
397
+ dayCount?: ScheduleDayCount;
398
+ /** How often a payment falls due, applied at the end of the month it falls in. Default monthly. */
399
+ paymentFrequency?: SchedulePaymentFrequency;
400
+ /** The first payment's date. Omit for one frequency after the schedule's first month. */
401
+ firstPaymentDate?: string | null;
402
+ /**
403
+ * Each scheduled payment in cents, interest included. Omit for the level
404
+ * payment that retires the principal by `maturityDate`, or for the accrued
405
+ * interest when `interestOnly`.
406
+ */
407
+ paymentAmount?: number | null;
408
+ /** Payments settle interest only; the principal is due at maturity. */
409
+ interestOnly?: boolean;
410
+ /**
411
+ * When the remaining principal is due: repaid in that month, the
412
+ * schedule's last. Omit for a line of credit with no maturity, whose
413
+ * balance carries past the schedule.
414
+ */
415
+ maturityDate?: string | null;
416
+ /** Interest is added to the note (a PIK note) rather than accrued apart. */
417
+ capitalizeInterest?: boolean;
418
+ /**
419
+ * The liability account the principal is carried in. The schedule states
420
+ * its balance each period, which the schedule reconciliation compares
421
+ * with the ledger.
422
+ */
423
+ noteElementId: string;
424
+ /**
425
+ * A current-liability account for the principal due within twelve
426
+ * months. When set, each period's entry also reclasses between it and
427
+ * the note so it holds the next twelve months' principal.
428
+ */
429
+ currentPortionElementId?: string | null;
430
+ }
431
+ export interface ScheduleEntryTemplate {
432
+ /** The account debited: a straight-line or custom schedule's debit; a loan's interest debit leg. */
433
+ debitElementId: string;
434
+ /** The account credited: the pair's credit; one of a loan's credit legs. */
435
+ creditElementId: string;
436
+ entryType?: LedgerEntryType;
437
+ memoTemplate?: string;
438
+ /** Auto-generate a reversing entry on the first day of the next period. */
439
+ autoReverse?: boolean;
440
+ /** The management dimension members every drafted entry carries, one per axis. */
441
+ dimensionIds?: string[];
442
+ /**
443
+ * The lines of a loan schedule's entry (`method: 'effective_interest'`
444
+ * only), each taking one column of the amortization table; each period's
445
+ * lines must balance. Accrue and pay through the bank: debit Interest
446
+ * Expense and credit Accrued Interest, both `interest`. The schedule
447
+ * settles the payment itself: debit the note `principal`, debit Interest
448
+ * Expense `interest`, credit cash or a due-to `payment`.
449
+ */
450
+ legs?: ScheduleLeg[];
451
+ }
452
+ export interface ScheduleMetadata {
453
+ /**
454
+ * `straight_line` (default) spreads `monthlyAmount` over the months, the
455
+ * last absorbing rounding; `custom` takes `periodicAmounts`;
456
+ * `effective_interest` is a loan computed from `loanTerms`.
457
+ */
458
+ method?: ScheduleMethod | (string & {});
459
+ /** Cost basis in cents. */
460
+ originalAmount?: number;
461
+ /** Salvage value in cents; the schedule expenses `originalAmount` less this. */
462
+ residualValue?: number;
463
+ usefulLifeMonths?: number;
464
+ /** Balance-sheet asset element for net book value. */
465
+ assetElementId?: string;
466
+ /**
467
+ * The day the cost went on the books (YYYY-MM-DD), when that is before
468
+ * the schedule's first period. The schedule reconciliation carries the
469
+ * cost from that day.
470
+ */
471
+ bookedOn?: string;
472
+ /**
473
+ * `custom` only: one cents value per month, non-negative, summing to
474
+ * `originalAmount` less `residualValue`.
475
+ */
476
+ periodicAmounts?: number[];
477
+ /** `effective_interest` only. */
478
+ loanTerms?: LoanTerms;
479
+ }
480
+ /**
481
+ * A schedule's definition: what `createSchedule` and `previewSchedule`
482
+ * take, and what `rebuildSchedule` saves back.
483
+ */
371
484
  export interface CreateScheduleOptions {
372
485
  name: string;
373
486
  elementIds: string[];
374
487
  periodStart: string;
375
488
  periodEnd: string;
376
- monthlyAmount: number;
377
- entryTemplate: {
378
- debitElementId: string;
379
- creditElementId: string;
380
- entryType?: LedgerEntryType;
381
- memoTemplate?: string;
382
- };
489
+ /**
490
+ * Monthly amount in cents. Required for a straight-line schedule; a
491
+ * custom or loan schedule takes its amounts from its curve.
492
+ */
493
+ monthlyAmount?: number;
494
+ entryTemplate: ScheduleEntryTemplate;
383
495
  taxonomyId?: string;
384
- scheduleMetadata?: {
385
- method?: string;
386
- originalAmount?: number;
387
- residualValue?: number;
388
- usefulLifeMonths?: number;
389
- assetElementId?: string;
390
- /**
391
- * The day the cost went on the books (YYYY-MM-DD), when that is before
392
- * the schedule's first period. The schedule reconciliation carries the
393
- * cost from that day.
394
- */
395
- bookedOn?: string;
396
- };
496
+ scheduleMetadata?: ScheduleMetadata;
397
497
  /** The entity whose books the schedule belongs to. Omit for the group parent. */
398
498
  entityId?: string | null;
499
+ /**
500
+ * Onboarding watermark: months ending on or before it are history the
501
+ * schedule records but never drafts. Defaults to the calendar's
502
+ * closed-through month.
503
+ */
504
+ closedThrough?: string;
505
+ }
506
+ export interface PreviewScheduleOptions extends CreateScheduleOptions {
507
+ /** The schedule this definition would replace, when editing or recreating one. */
508
+ replacesStructureId?: string | null;
509
+ }
510
+ export interface RebuildScheduleOptions {
511
+ idempotencyKey?: string;
512
+ periodStart?: string;
513
+ periodEnd?: string;
514
+ monthlyAmount?: number;
515
+ /** A new entry template, replacing the stored one whole. */
516
+ entryTemplate?: ScheduleEntryTemplate;
517
+ /** The schedule_metadata fields to change; the rest keep their stored values. */
518
+ scheduleMetadata?: ScheduleMetadata;
519
+ }
520
+ /** One period of a previewed schedule: the balance it carries, and what moves it. */
521
+ export interface ScheduleRollForwardPeriod {
522
+ periodStart: string;
523
+ periodEnd: string;
524
+ opening: number;
525
+ /** What the period recognizes: the entry's debit amount. */
526
+ amount: number;
527
+ closing: number;
528
+ /** `historical` for a month already in the books' history; `in_scope` for one a close drafts. */
529
+ scope: 'historical' | 'in_scope';
530
+ /** Loan schedules only. */
531
+ interest: number | null;
532
+ payment: number | null;
533
+ principal: number | null;
534
+ currentPortion: number | null;
535
+ }
536
+ /** What an existing schedule's entries mean for replacing it. */
537
+ export interface ScheduleReplacement {
538
+ structureId: string;
539
+ name: string;
540
+ postedEntryCount: number;
541
+ /** The months (YYYY-MM) its posted entries are in. */
542
+ postedPeriods: string[];
543
+ draftEntryCount: number;
544
+ /** `rebuild` while nothing has posted; `terminate_and_succeed` once an entry has. */
545
+ path: 'rebuild' | 'terminate_and_succeed';
546
+ }
547
+ /** Result of `previewSchedule`: a generated schedule nobody kept. */
548
+ export interface SchedulePreview {
549
+ /**
550
+ * The envelope create would leave, in the operation's own snake_case
551
+ * shape; its ids are provisional. `artifact.mechanics` reads the
552
+ * definition back.
553
+ */
554
+ envelope: InformationBlockEnvelope;
555
+ rollForward: ScheduleRollForwardPeriod[];
556
+ /** Another active schedule already posting the same accounts over the same months. */
557
+ warnings: string[];
558
+ replaces: ScheduleReplacement | null;
399
559
  }
400
560
  export interface JournalEntryLineItem {
401
561
  elementId: string;
@@ -901,6 +1061,22 @@ export declare class LedgerClient {
901
1061
  deleteInformationBlock(graphId: string, body: DeleteInformationBlockRequest): Promise<DeleteInformationBlockResponse>;
902
1062
  /** Create a new schedule with pre-generated monthly facts. */
903
1063
  createSchedule(graphId: string, options: CreateScheduleOptions): Promise<ScheduleBlockCreated>;
1064
+ /**
1065
+ * Generate a schedule from a definition without keeping it: the same
1066
+ * generator and guards as `createSchedule`, run and rolled back. Returns
1067
+ * the envelope create would leave (its ids provisional), the roll-forward
1068
+ * (the balance the schedule carries period by period; a loan's note, with
1069
+ * its interest, payment, principal and current portion), and warnings
1070
+ * naming any active schedule already posting the same accounts in the
1071
+ * same months. A definition create would refuse (a roll-forward that
1072
+ * climbs where it should fall, legs that do not balance) is refused here
1073
+ * with the period that breaks. With `replacesStructureId`, `replaces`
1074
+ * says what the schedule being edited or recreated has posted, by month,
1075
+ * and the path the change takes: `rebuild` (save through
1076
+ * `rebuildSchedule`) while nothing has posted, `terminate_and_succeed`
1077
+ * after.
1078
+ */
1079
+ previewSchedule(graphId: string, options: PreviewScheduleOptions): Promise<SchedulePreview>;
904
1080
  /**
905
1081
  * Rename a schedule. For other block fields use `updateInformationBlock`
906
1082
  * with a `schedule` payload.
@@ -921,12 +1097,19 @@ export declare class LedgerClient {
921
1097
  * a rebuild re-scopes the schedule to today's close state. Use this to
922
1098
  * pick up a fixed generator without orphaning obligations.
923
1099
  *
1100
+ * It is also how an edit is saved while nothing has posted: the
1101
+ * definition fields on `options` (`periodStart`, `periodEnd`,
1102
+ * `monthlyAmount`, `entryTemplate` replacing the stored one whole,
1103
+ * `scheduleMetadata` for only the fields named) replace the stored
1104
+ * definition before it regenerates, as the schedule's envelope reads them
1105
+ * back (`artifact.mechanics`). Omitted fields keep their stored values.
1106
+ * Refused once an entry has posted; `previewSchedule` with
1107
+ * `replacesStructureId` says which path an edit takes.
1108
+ *
924
1109
  * Returns the {@link ScheduleCreated} rebuild summary (periods, facts,
925
1110
  * rule results) — richer than `createSchedule`'s {@link ScheduleBlockCreated}.
926
1111
  */
927
- rebuildSchedule(graphId: string, structureId: string, options?: {
928
- idempotencyKey?: string;
929
- }): Promise<ScheduleCreated>;
1112
+ rebuildSchedule(graphId: string, structureId: string, options?: RebuildScheduleOptions): Promise<ScheduleCreated>;
930
1113
  /**
931
1114
  * Dispose of a schedule asset — atomically truncates forward facts,
932
1115
  * deletes the SumEquals rule, and posts a balanced disposal entry.
@@ -11,6 +11,59 @@ const rest_1 = require("./rest");
11
11
  // from the `@robosystems/client/ledger` subpath can `instanceof` it.
12
12
  var client_2 = require("./graphql/client");
13
13
  Object.defineProperty(exports, "GraphQLError", { enumerable: true, get: function () { return client_2.GraphQLError; } });
14
+ const toScheduleLeg = (leg) => ({
15
+ element_id: leg.elementId,
16
+ side: leg.side,
17
+ amount_source: leg.amountSource,
18
+ });
19
+ const toEntryTemplate = (template) => ({
20
+ debit_element_id: template.debitElementId,
21
+ credit_element_id: template.creditElementId,
22
+ entry_type: template.entryType,
23
+ memo_template: template.memoTemplate,
24
+ auto_reverse: template.autoReverse,
25
+ dimension_ids: template.dimensionIds,
26
+ legs: template.legs?.map(toScheduleLeg),
27
+ });
28
+ const toLoanTerms = (terms) => ({
29
+ principal: terms.principal,
30
+ annual_rate: terms.annualRate,
31
+ start_date: terms.startDate,
32
+ day_count: terms.dayCount,
33
+ payment_frequency: terms.paymentFrequency,
34
+ first_payment_date: terms.firstPaymentDate,
35
+ payment_amount: terms.paymentAmount,
36
+ interest_only: terms.interestOnly,
37
+ maturity_date: terms.maturityDate,
38
+ capitalize_interest: terms.capitalizeInterest,
39
+ note_element_id: terms.noteElementId,
40
+ current_portion_element_id: terms.currentPortionElementId,
41
+ });
42
+ const toScheduleMetadata = (metadata) => ({
43
+ method: metadata.method,
44
+ original_amount: metadata.originalAmount,
45
+ residual_value: metadata.residualValue,
46
+ useful_life_months: metadata.usefulLifeMonths,
47
+ asset_element_id: metadata.assetElementId,
48
+ booked_on: metadata.bookedOn,
49
+ periodic_amounts: metadata.periodicAmounts,
50
+ loan_terms: metadata.loanTerms ? toLoanTerms(metadata.loanTerms) : undefined,
51
+ });
52
+ /** The definition as the schedule operations take it. */
53
+ const toScheduleDefinition = (options) => ({
54
+ name: options.name,
55
+ element_ids: options.elementIds,
56
+ period_start: options.periodStart,
57
+ period_end: options.periodEnd,
58
+ monthly_amount: options.monthlyAmount,
59
+ entry_template: toEntryTemplate(options.entryTemplate),
60
+ taxonomy_id: options.taxonomyId,
61
+ ...(options.entityId ? { entity_id: options.entityId } : {}),
62
+ closed_through: options.closedThrough,
63
+ schedule_metadata: options.scheduleMetadata
64
+ ? toScheduleMetadata(options.scheduleMetadata)
65
+ : undefined,
66
+ });
14
67
  class LedgerClient {
15
68
  constructor(config) {
16
69
  this.config = config;
@@ -599,31 +652,7 @@ class LedgerClient {
599
652
  async createSchedule(graphId, options) {
600
653
  const body = {
601
654
  block_type: 'schedule',
602
- payload: {
603
- name: options.name,
604
- element_ids: options.elementIds,
605
- period_start: options.periodStart,
606
- period_end: options.periodEnd,
607
- monthly_amount: options.monthlyAmount,
608
- entry_template: {
609
- debit_element_id: options.entryTemplate.debitElementId,
610
- credit_element_id: options.entryTemplate.creditElementId,
611
- entry_type: options.entryTemplate.entryType,
612
- memo_template: options.entryTemplate.memoTemplate,
613
- },
614
- taxonomy_id: options.taxonomyId,
615
- ...(options.entityId ? { entity_id: options.entityId } : {}),
616
- schedule_metadata: options.scheduleMetadata
617
- ? {
618
- method: options.scheduleMetadata.method,
619
- original_amount: options.scheduleMetadata.originalAmount,
620
- residual_value: options.scheduleMetadata.residualValue,
621
- useful_life_months: options.scheduleMetadata.usefulLifeMonths,
622
- asset_element_id: options.scheduleMetadata.assetElementId,
623
- booked_on: options.scheduleMetadata.bookedOn,
624
- }
625
- : undefined,
626
- },
655
+ payload: toScheduleDefinition(options),
627
656
  };
628
657
  const envelope = await this.callOperation('Create schedule', (o) => (0, sdk_gen_1.createInformationBlock)({ ...o, path: { graph_id: graphId }, body }));
629
658
  // `create-information-block` returns an InformationBlockEnvelope, not the
@@ -641,6 +670,55 @@ class LedgerClient {
641
670
  totalFacts: block.facts?.length ?? null,
642
671
  };
643
672
  }
673
+ /**
674
+ * Generate a schedule from a definition without keeping it: the same
675
+ * generator and guards as `createSchedule`, run and rolled back. Returns
676
+ * the envelope create would leave (its ids provisional), the roll-forward
677
+ * (the balance the schedule carries period by period; a loan's note, with
678
+ * its interest, payment, principal and current portion), and warnings
679
+ * naming any active schedule already posting the same accounts in the
680
+ * same months. A definition create would refuse (a roll-forward that
681
+ * climbs where it should fall, legs that do not balance) is refused here
682
+ * with the period that breaks. With `replacesStructureId`, `replaces`
683
+ * says what the schedule being edited or recreated has posted, by month,
684
+ * and the path the change takes: `rebuild` (save through
685
+ * `rebuildSchedule`) while nothing has posted, `terminate_and_succeed`
686
+ * after.
687
+ */
688
+ async previewSchedule(graphId, options) {
689
+ const body = {
690
+ ...toScheduleDefinition(options),
691
+ replaces_structure_id: options.replacesStructureId ?? undefined,
692
+ };
693
+ const envelope = await this.callOperation('Preview schedule', (o) => (0, sdk_gen_1.previewSchedule)({ ...o, path: { graph_id: graphId }, body }));
694
+ const raw = this.requireResult('Preview schedule', envelope.result);
695
+ return {
696
+ envelope: raw.envelope,
697
+ rollForward: (raw.roll_forward ?? []).map((row) => ({
698
+ periodStart: row.period_start,
699
+ periodEnd: row.period_end,
700
+ opening: row.opening,
701
+ amount: row.amount,
702
+ closing: row.closing,
703
+ scope: row.scope,
704
+ interest: row.interest ?? null,
705
+ payment: row.payment ?? null,
706
+ principal: row.principal ?? null,
707
+ currentPortion: row.current_portion ?? null,
708
+ })),
709
+ warnings: raw.warnings ?? [],
710
+ replaces: raw.replaces
711
+ ? {
712
+ structureId: raw.replaces.structure_id,
713
+ name: raw.replaces.name,
714
+ postedEntryCount: raw.replaces.posted_entry_count,
715
+ postedPeriods: raw.replaces.posted_periods ?? [],
716
+ draftEntryCount: raw.replaces.draft_entry_count ?? 0,
717
+ path: raw.replaces.path,
718
+ }
719
+ : null,
720
+ };
721
+ }
644
722
  /**
645
723
  * Rename a schedule. For other block fields use `updateInformationBlock`
646
724
  * with a `schedule` payload.
@@ -673,11 +751,29 @@ class LedgerClient {
673
751
  * a rebuild re-scopes the schedule to today's close state. Use this to
674
752
  * pick up a fixed generator without orphaning obligations.
675
753
  *
754
+ * It is also how an edit is saved while nothing has posted: the
755
+ * definition fields on `options` (`periodStart`, `periodEnd`,
756
+ * `monthlyAmount`, `entryTemplate` replacing the stored one whole,
757
+ * `scheduleMetadata` for only the fields named) replace the stored
758
+ * definition before it regenerates, as the schedule's envelope reads them
759
+ * back (`artifact.mechanics`). Omitted fields keep their stored values.
760
+ * Refused once an entry has posted; `previewSchedule` with
761
+ * `replacesStructureId` says which path an edit takes.
762
+ *
676
763
  * Returns the {@link ScheduleCreated} rebuild summary (periods, facts,
677
764
  * rule results) — richer than `createSchedule`'s {@link ScheduleBlockCreated}.
678
765
  */
679
766
  async rebuildSchedule(graphId, structureId, options) {
680
- const body = { structure_id: structureId };
767
+ const body = {
768
+ structure_id: structureId,
769
+ period_start: options?.periodStart,
770
+ period_end: options?.periodEnd,
771
+ monthly_amount: options?.monthlyAmount,
772
+ entry_template: options?.entryTemplate ? toEntryTemplate(options.entryTemplate) : undefined,
773
+ schedule_metadata: options?.scheduleMetadata
774
+ ? toScheduleMetadata(options.scheduleMetadata)
775
+ : undefined,
776
+ };
681
777
  const envelope = await this.callOperation('Rebuild schedule', (o) => (0, sdk_gen_1.rebuildSchedule)({
682
778
  ...(0, rest_1.withIdempotencyKey)(o, options?.idempotencyKey),
683
779
  path: { graph_id: graphId },