@odla-ai/chapter 0.3.0 → 0.4.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.
package/dist/index.js CHANGED
@@ -427,7 +427,7 @@ async function submitApplication(db, chapter, fields, opts) {
427
427
  );
428
428
  return { ok: true, id: id2, duplicate, status: chapter.pipeline.initial };
429
429
  }
430
- function joinConfig(group, paymentsReady) {
430
+ function joinConfig(group, paymentsReady2) {
431
431
  return {
432
432
  id: group.id,
433
433
  name: group.name,
@@ -438,7 +438,7 @@ function joinConfig(group, paymentsReady) {
438
438
  trustCopy: group.trustCopy ?? "",
439
439
  commitmentText: group.commitmentText ?? "",
440
440
  normsText: group.normsText ?? "",
441
- paymentsReady
441
+ paymentsReady: paymentsReady2
442
442
  };
443
443
  }
444
444
 
@@ -587,6 +587,70 @@ async function verifyStripeSignature(payload, header, secret, opts = {}) {
587
587
  const mac = await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${payload}`));
588
588
  return timingSafeEqual(toHex(mac), v1);
589
589
  }
590
+ function paymentsReady(group, hasSecretKey) {
591
+ return Boolean(group.stripePublishableKey && group.stripePriceId && hasSecretKey);
592
+ }
593
+ function stripeForm(params) {
594
+ const out = new URLSearchParams();
595
+ for (const [k, v] of Object.entries(params)) {
596
+ if (v === void 0 || v === null) continue;
597
+ if (typeof v === "object") {
598
+ for (const [k2, v2] of Object.entries(v)) {
599
+ if (v2 !== void 0 && v2 !== null) out.append(`${k}[${k2}]`, String(v2));
600
+ }
601
+ } else {
602
+ out.append(k, String(v));
603
+ }
604
+ }
605
+ return out.toString();
606
+ }
607
+ function subscriptionIdempotencyKey(applicationId) {
608
+ return `sub:${applicationId}`;
609
+ }
610
+ function webhookMutationId(eventId) {
611
+ return `stripe:${eventId}`;
612
+ }
613
+ function findApplicationRef(obj) {
614
+ const metaOf = (v) => v && typeof v === "object" ? v.metadata ?? {} : {};
615
+ const pick = (m) => typeof m.applicationId === "string" ? m.applicationId : void 0;
616
+ const applicationId = pick(metaOf(obj)) ?? pick(metaOf(obj.subscription_details)) ?? pick(metaOf(obj.parent?.subscription_details));
617
+ const customerId = typeof obj.customer === "string" ? obj.customer : void 0;
618
+ return { ...applicationId ? { applicationId } : {}, ...customerId ? { customerId } : {} };
619
+ }
620
+ function normalizeWebhookEvent(event) {
621
+ const obj = event.data?.object ?? {};
622
+ const ref = findApplicationRef(obj);
623
+ switch (event.type) {
624
+ case "invoice.paid": {
625
+ const lines = obj.lines?.data ?? [];
626
+ const periodEnd = lines[0]?.period?.end;
627
+ const renewalAt = typeof periodEnd === "number" ? periodEnd * 1e3 : void 0;
628
+ const kind = obj.billing_reason === "subscription_create" ? "first_payment" : "renewal";
629
+ return { kind, ...ref, ...renewalAt !== void 0 ? { renewalAt } : {} };
630
+ }
631
+ case "charge.refunded":
632
+ return { kind: "refunded", ...ref };
633
+ case "customer.subscription.deleted":
634
+ return { kind: "canceled", ...ref };
635
+ default:
636
+ return { kind: "ignored", type: event.type };
637
+ }
638
+ }
639
+ function firstPaymentPatch(currentStatus, renewalAt) {
640
+ return {
641
+ ...currentStatus === "submitted" ? { status: "paid_pending_vetting" } : {},
642
+ ...renewalAt !== void 0 ? { renewalAt } : {}
643
+ };
644
+ }
645
+ function renewalPatch(renewalAt) {
646
+ return { renewalAt };
647
+ }
648
+ function refundedPatch() {
649
+ return { status: "refunded" };
650
+ }
651
+ function canceledPatch() {
652
+ return { canceled: true };
653
+ }
590
654
 
591
655
  // src/network.ts
592
656
  import { createRecord, updateRecord } from "@odla-ai/crm";
@@ -616,31 +680,194 @@ async function projectSharedRecord(deps, person) {
616
680
  const created = await createRecord(crmDeps, { type: "person", input, mutationId: `share:${person.hubRecordId}` });
617
681
  return { recordId: created.id };
618
682
  }
683
+
684
+ // src/session.ts
685
+ function applicationSummary(app) {
686
+ return {
687
+ id: app.id,
688
+ firstName: app.firstName ?? null,
689
+ lastName: app.lastName ?? null,
690
+ email: app.email ?? null,
691
+ status: app.status,
692
+ createdAt: app.createdAt ?? null,
693
+ meetingLink: app.meetingLink ?? null,
694
+ paid: Boolean(app.stripeSubscriptionId) && app.status !== "refunded",
695
+ renewalAt: app.renewalAt ?? null,
696
+ canceled: app.canceled === true
697
+ };
698
+ }
699
+ function memberApplication(app, meeting, defaultTimezone) {
700
+ const summary = applicationSummary(app);
701
+ let meetingAt = app.meetingAt ?? null;
702
+ let meetUrl = null;
703
+ let timezone = defaultTimezone;
704
+ if (meeting) {
705
+ timezone = meeting.timezone ?? timezone;
706
+ if (meeting.status === "scheduled") {
707
+ meetingAt = meeting.startAt ?? null;
708
+ meetUrl = meeting.meetUrl ?? null;
709
+ } else {
710
+ meetingAt = null;
711
+ }
712
+ }
713
+ return { ...summary, meetingAt, meetUrl, timezone };
714
+ }
715
+ function memberSession(user, opts) {
716
+ return {
717
+ userId: user.userId,
718
+ email: user.email ?? null,
719
+ role: user.role,
720
+ superAdmin: opts.superAdmin,
721
+ application: opts.application
722
+ };
723
+ }
724
+
725
+ // src/scheduling.ts
726
+ var SCHEDULING_DEFAULTS = {
727
+ slotMinutes: 45,
728
+ days: [1, 2, 3, 4, 5],
729
+ startHour: 9,
730
+ endHour: 17,
731
+ timezone: "America/Los_Angeles",
732
+ minNoticeHours: 24,
733
+ windowDays: 14,
734
+ summaryTemplate: "Introduction call with {{firstName}} {{lastName}}"
735
+ };
736
+ function isValidTimeZone(tz) {
737
+ try {
738
+ new Intl.DateTimeFormat(void 0, { timeZone: tz });
739
+ return true;
740
+ } catch {
741
+ return false;
742
+ }
743
+ }
744
+ function resolveScheduling(config) {
745
+ const d = config ?? {};
746
+ const c = {
747
+ slotMinutes: d.slotMinutes ?? SCHEDULING_DEFAULTS.slotMinutes,
748
+ days: d.days ?? SCHEDULING_DEFAULTS.days,
749
+ startHour: d.startHour ?? SCHEDULING_DEFAULTS.startHour,
750
+ endHour: d.endHour ?? SCHEDULING_DEFAULTS.endHour,
751
+ timezone: d.timezone ?? SCHEDULING_DEFAULTS.timezone,
752
+ minNoticeHours: d.minNoticeHours ?? SCHEDULING_DEFAULTS.minNoticeHours,
753
+ windowDays: d.windowDays ?? SCHEDULING_DEFAULTS.windowDays,
754
+ summaryTemplate: d.summaryTemplate ?? SCHEDULING_DEFAULTS.summaryTemplate
755
+ };
756
+ const fail = (msg) => {
757
+ throw new Error(`scheduling: ${msg}`);
758
+ };
759
+ if (!(c.slotMinutes >= 15 && c.slotMinutes <= 240)) fail("slotMinutes must be 15\u2013240");
760
+ if (!(c.windowDays >= 1 && c.windowDays <= 62)) fail("windowDays must be 1\u201362 (FreeBusy caps at 62)");
761
+ if (!(c.minNoticeHours >= 0 && c.minNoticeHours <= 336)) fail("minNoticeHours must be 0\u2013336");
762
+ if (!(c.startHour >= 0 && c.startHour < c.endHour && c.endHour <= 24)) fail("require 0 \u2264 startHour < endHour \u2264 24");
763
+ const days = [...c.days];
764
+ if (!days.length || !days.every((n) => Number.isInteger(n) && n >= 0 && n <= 6)) {
765
+ fail("days must be a non-empty list of weekday integers 0\u20136");
766
+ }
767
+ if (typeof c.timezone !== "string" || !isValidTimeZone(c.timezone)) fail(`invalid IANA timezone "${c.timezone}"`);
768
+ if (typeof c.summaryTemplate !== "string") fail("summaryTemplate must be a string");
769
+ return { ...c, days };
770
+ }
771
+ var BOOKABLE_STATUSES = ["submitted", "paid_pending_vetting", "call_scheduled"];
772
+ function canBookFrom(status) {
773
+ return BOOKABLE_STATUSES.includes(status);
774
+ }
775
+ function slotWindow(now, windowDays) {
776
+ return { from: now, to: now + windowDays * 864e5 };
777
+ }
778
+ function endForSlot(startAt, slotMinutes) {
779
+ return startAt + slotMinutes * 6e4;
780
+ }
781
+ function isSlotAvailable(slots, startAt) {
782
+ return slots.some((s) => s.startAt === startAt);
783
+ }
784
+ function renderSummary(template, app) {
785
+ return template.replace("{{firstName}}", app.firstName ?? "").replace("{{lastName}}", app.lastName ?? "");
786
+ }
787
+ function bookingDecision(existing) {
788
+ const eventId = existing?.googleEventId ?? null;
789
+ return { reschedule: Boolean(eventId), eventId };
790
+ }
791
+ function introIdempotencyKey(applicationId) {
792
+ return `application:${applicationId}:intro`;
793
+ }
794
+ function meetingCreateRow(i) {
795
+ return {
796
+ id: i.meetingId,
797
+ applicationId: i.applicationId,
798
+ groupId: i.groupId,
799
+ startAt: i.startAt,
800
+ endAt: i.endAt,
801
+ timezone: i.timezone,
802
+ status: "scheduled",
803
+ googleEventId: i.googleEventId,
804
+ ...i.meetUrl ? { meetUrl: i.meetUrl } : {},
805
+ ...i.htmlLink ? { htmlLink: i.htmlLink } : {},
806
+ drift: "none",
807
+ createdAt: i.createdAt
808
+ };
809
+ }
810
+ function meetingRescheduleUpdate(startAt, endAt) {
811
+ return { startAt, endAt, drift: "none" };
812
+ }
813
+ function applicationBookingUpdate(currentStatus, startAt, htmlLink) {
814
+ return {
815
+ meetingAt: startAt,
816
+ ...htmlLink ? { meetingLink: htmlLink } : {},
817
+ ...currentStatus !== "call_scheduled" ? { status: "call_scheduled" } : {}
818
+ };
819
+ }
619
820
  export {
821
+ BOOKABLE_STATUSES,
822
+ SCHEDULING_DEFAULTS,
823
+ applicationBookingUpdate,
824
+ applicationSummary,
825
+ bookingDecision,
620
826
  buildGroupSeed,
621
827
  canApprove,
622
828
  canBook,
829
+ canBookFrom,
623
830
  canChangeRole,
624
831
  canTransition,
832
+ canceledPatch,
625
833
  chapterDb,
626
834
  createChapterIntegration,
627
835
  defaultCrm,
628
836
  defineChapter,
837
+ endForSlot,
838
+ findApplicationRef,
839
+ firstPaymentPatch,
629
840
  getVaultSecret,
841
+ introIdempotencyKey,
630
842
  isAdminRole,
631
843
  isAlreadySent,
844
+ isSlotAvailable,
632
845
  joinConfig,
846
+ meetingCreateRow,
847
+ meetingRescheduleUpdate,
848
+ memberApplication,
849
+ memberSession,
850
+ normalizeWebhookEvent,
851
+ paymentsReady,
633
852
  planDelivery,
634
853
  projectSharedRecord,
854
+ refundedPatch,
635
855
  render,
856
+ renderSummary,
636
857
  renderTemplateBody,
858
+ renewalPatch,
637
859
  resolveApplication,
638
860
  resolveAuth,
639
861
  resolvePipeline,
862
+ resolveScheduling,
640
863
  roleFromClaim,
641
864
  sharedPersonInput,
865
+ slotWindow,
642
866
  stageIndex,
867
+ stripeForm,
643
868
  submitApplication,
644
- verifyStripeSignature
869
+ subscriptionIdempotencyKey,
870
+ verifyStripeSignature,
871
+ webhookMutationId
645
872
  };
646
873
  //# sourceMappingURL=index.js.map