@wix/himalaya-cli 0.1666.0 → 0.1668.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.
Files changed (24) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +2 -1
  2. package/dist/browser-plane/assets.json +5 -5
  3. package/dist/browser-plane/preview-deferred/{7700021a25a8d932331f2abf6ba6c2f13b2a18cabfc4ce8b02aa0ed1ae973ffc.bin → 6eb8e06efae709dec91b845b9df5a93594d4a91d157b435e053cc7789d005253.bin} +1 -1
  4. package/dist/browser-plane/sw.js +9 -9
  5. package/dist/cli.mjs +192 -50
  6. package/dist/preview-assets.generated.bin +0 -0
  7. package/fixtures/wix-canned.json +3 -0
  8. package/guides/component-reference.json +1 -1
  9. package/guides/component-reference.md +2 -1
  10. package/package.json +2 -2
  11. package/templates/branded-lite/dev/index.ts +32 -1
  12. package/templates/branded-lite/l10n/en.json +16 -3
  13. package/templates/branded-lite/l10n/es.json +15 -0
  14. package/templates/branded-lite/l10n/he.json +15 -0
  15. package/templates/branded-lite/tier5-src/_shared/program-standing.ts +40 -0
  16. package/templates/branded-lite/tier5-src/himi-branded-lite-member-programs/index.ts +4 -35
  17. package/templates/branded-lite/tier5-src/himi-branded-lite-program/index.ts +302 -9
  18. package/templates/yoga-studio/dev/index.ts +32 -1
  19. package/templates/yoga-studio/l10n/en.json +16 -3
  20. package/templates/yoga-studio/l10n/es.json +15 -0
  21. package/templates/yoga-studio/l10n/he.json +15 -0
  22. package/templates/yoga-studio/tier5-src/_shared/program-standing.ts +40 -0
  23. package/templates/yoga-studio/tier5-src/himi-branded-lite-member-programs/index.ts +4 -35
  24. package/templates/yoga-studio/tier5-src/himi-branded-lite-program/index.ts +302 -9
@@ -92,10 +92,8 @@
92
92
  },
93
93
  "h_050a944c6675": {
94
94
  "source": "Enrol",
95
- "kind": "Button.title",
96
- "translation": "",
97
95
  "key": "program.enrolCta",
98
- "keyOrigin": "string-table"
96
+ "translation": ""
99
97
  },
100
98
  "h_0559813da230": {
101
99
  "source": "Back to projects",
@@ -707,6 +705,11 @@
707
705
  "key": "donation.notFoundBody",
708
706
  "keyOrigin": "string-table"
709
707
  },
708
+ "h_287d0c97c3f8": {
709
+ "source": "Your join request was cancelled.",
710
+ "key": "program.requestCancelledMessage",
711
+ "translation": ""
712
+ },
710
713
  "h_295468e69a99": {
711
714
  "source": "It may have been removed.",
712
715
  "kind": "Text.text",
@@ -1819,6 +1822,11 @@
1819
1822
  "key": "planDetail.message",
1820
1823
  "keyOrigin": "string-table"
1821
1824
  },
1825
+ "h_6dd1d806fc51": {
1826
+ "source": "The request could not be cancelled. Try again.",
1827
+ "key": "program.cancelRequestFailedMessage",
1828
+ "translation": ""
1829
+ },
1822
1830
  "h_6df910132a36": {
1823
1831
  "source": "Suggestion sent.",
1824
1832
  "kind": "Worker.copy",
@@ -2157,6 +2165,11 @@
2157
2165
  "key": "loyalty.sampleBody",
2158
2166
  "keyOrigin": "string-table"
2159
2167
  },
2168
+ "h_84837a216817": {
2169
+ "source": "Cancel request",
2170
+ "key": "program.cancelRequestCta",
2171
+ "translation": ""
2172
+ },
2160
2173
  "h_849594a18598": {
2161
2174
  "source": "Address not found",
2162
2175
  "kind": "Text.text",
@@ -17,6 +17,21 @@
17
17
  "key": "product.galleryPage",
18
18
  "translation": "Imagen {index} de {count}"
19
19
  },
20
+ "h_84837a216817": {
21
+ "source": "Cancel request",
22
+ "key": "program.cancelRequestCta",
23
+ "translation": "Cancelar solicitud"
24
+ },
25
+ "h_287d0c97c3f8": {
26
+ "source": "Your join request was cancelled.",
27
+ "key": "program.requestCancelledMessage",
28
+ "translation": "Tu solicitud de inscripción se ha cancelado."
29
+ },
30
+ "h_6dd1d806fc51": {
31
+ "source": "The request could not be cancelled. Try again.",
32
+ "key": "program.cancelRequestFailedMessage",
33
+ "translation": "No se ha podido cancelar la solicitud. Inténtalo de nuevo."
34
+ },
20
35
  "h_0d049cb0b019": {
21
36
  "source": "This site is not accepting online payments. Go back or contact the business for other payment options.",
22
37
  "translation": "Este sitio no acepta pagos en línea. Vuelve atrás o contacta con el negocio para consultar otras opciones de pago."
@@ -3185,6 +3185,21 @@
3185
3185
  "key": "cms.searchEmptyText",
3186
3186
  "translation": "אין אוספים שתואמים לחיפוש."
3187
3187
  },
3188
+ "h_84837a216817": {
3189
+ "source": "Cancel request",
3190
+ "key": "program.cancelRequestCta",
3191
+ "translation": "ביטול בקשה"
3192
+ },
3193
+ "h_287d0c97c3f8": {
3194
+ "source": "Your join request was cancelled.",
3195
+ "key": "program.requestCancelledMessage",
3196
+ "translation": "בקשת ההצטרפות שלך בוטלה."
3197
+ },
3198
+ "h_6dd1d806fc51": {
3199
+ "source": "The request could not be cancelled. Try again.",
3200
+ "key": "program.cancelRequestFailedMessage",
3201
+ "translation": "לא ניתן לבטל את הבקשה. יש לנסות שוב."
3202
+ },
3188
3203
  "h_a689a999a5e6": {
3189
3204
  "source": "Expired",
3190
3205
  "key": "mySubscriptions.expired",
@@ -0,0 +1,40 @@
1
+ // The member's standing on one Online Program — the One App participant/application states, folded.
2
+ // Shared by the programs list cards and the program detail screen so both read a member the same way.
3
+ import type { WixJoinApplication, WixParticipant } from "@himalaya/wix-online-programs";
4
+
5
+ export type Standing = "none" | "joined" | "completed" | "finished" | "suspended" | "pending" | "approved" | "invited";
6
+
7
+ export function standingOf(ended: boolean, participant: WixParticipant | undefined, application: WixJoinApplication | undefined): Standing {
8
+ if (participant) {
9
+ const progress = (participant.progressStatus ?? "").toUpperCase();
10
+ const enrollment = (participant.enrollmentStatus ?? "").toUpperCase();
11
+ if (progress === "COMPLETED") return "completed";
12
+ if (progress === "FAILED" || ended) return "finished";
13
+ if (enrollment === "SUSPENDED") return "suspended";
14
+ return "joined";
15
+ }
16
+ const status = (application?.status ?? "").toUpperCase();
17
+ const payment = (application?.paymentStatus ?? "").toUpperCase();
18
+ if (status === "APPROVAL_PENDING") return "pending";
19
+ if (status === "SUSPENDED") return "suspended";
20
+ if (status === "APPROVED") {
21
+ // The same reading as joinProgram: a free or settled approval is enrolling, and an offline payment
22
+ // waits on the owner. Only an approval that still owes money asks the member to pay.
23
+ if (payment === "NO_PAYMENT_REQUIRED" || payment === "PAYMENT_SUCCESSFUL") return application?.participantId ? "joined" : "pending";
24
+ if (payment === "PENDING_OWNER_APPROVAL") return "pending";
25
+ return "approved";
26
+ }
27
+ if (status === "PAYMENT_PENDING") return "approved";
28
+ if (status === "INVITED") return "invited";
29
+ return "none";
30
+ }
31
+
32
+ export const STATUS: Record<Exclude<Standing, "none">, { key: string; fallback: string; icon: string; color: string }> = {
33
+ joined: { key: "memberPrograms.status.joined", fallback: "Joined", icon: "checkmark", color: "accentPrimary" },
34
+ completed: { key: "memberPrograms.status.completed", fallback: "Program complete", icon: "trophy", color: "success" },
35
+ finished: { key: "memberPrograms.status.ended", fallback: "Program ended", icon: "flag", color: "textSecondary" },
36
+ suspended: { key: "memberPrograms.status.suspended", fallback: "Participation suspended", icon: "close", color: "warning" },
37
+ pending: { key: "memberPrograms.status.pending", fallback: "Pending request", icon: "clock", color: "warning" },
38
+ approved: { key: "memberPrograms.status.approved", fallback: "Request approved", icon: "checkmark", color: "success" },
39
+ invited: { key: "memberPrograms.status.invited", fallback: "Invited", icon: "mail", color: "accentPrimary" },
40
+ };
@@ -21,6 +21,7 @@ import { getMyMember } from "@himalaya/wix-members";
21
21
  import { iapPriceFields, onlineProgramItem, type IapPollDirective } from "@himalaya/iap";
22
22
  import { createIapCommerce } from "@himalaya/iap-checkout";
23
23
  import { createCollectionQuery, type CollectionPage, type CollectionQueryState } from "../_shared/collection-query.js";
24
+ import { standingOf as sharedStandingOf, STATUS, type Standing } from "../_shared/program-standing.js";
24
25
  import { memberAccess, memberAccessChanged, memberAccessDenied, type MemberAccess } from "../_shared/member-access.js";
25
26
  import { cleanTitle, initials } from "../_shared/himi-text.js";
26
27
  import { programImage } from "../_shared/himi-media.js";
@@ -37,8 +38,7 @@ const DETAIL_SCREEN = "himi_program";
37
38
 
38
39
  // ── Row model ────────────────────────────────────────────────────────────────
39
40
 
40
- /** The member's standing on one program — the One App participant/application states, folded. */
41
- export type Standing = "none" | "joined" | "completed" | "finished" | "suspended" | "pending" | "approved" | "invited";
41
+ export type { Standing };
42
42
 
43
43
  /** A card as loaded, before pricing. */
44
44
  export interface ProgramContent {
@@ -166,39 +166,8 @@ function daysBetween(fromIso: string, now: number): number {
166
166
 
167
167
  // ── Member standing ──────────────────────────────────────────────────────────
168
168
 
169
- function standingOf(p: WixProgram, participant: WixParticipant | undefined, application: WixJoinApplication | undefined): Standing {
170
- if (participant) {
171
- const progress = (participant.progressStatus ?? "").toUpperCase();
172
- const enrollment = (participant.enrollmentStatus ?? "").toUpperCase();
173
- if (progress === "COMPLETED") return "completed";
174
- if (progress === "FAILED" || isEnded(p)) return "finished";
175
- if (enrollment === "SUSPENDED") return "suspended";
176
- return "joined";
177
- }
178
- const status = (application?.status ?? "").toUpperCase();
179
- const payment = (application?.paymentStatus ?? "").toUpperCase();
180
- if (status === "APPROVAL_PENDING") return "pending";
181
- if (status === "APPROVED") {
182
- // The same reading as joinProgram: a free or settled approval is enrolling, and an offline payment
183
- // waits on the owner. Only an approval that still owes money asks the member to pay.
184
- if (payment === "NO_PAYMENT_REQUIRED" || payment === "PAYMENT_SUCCESSFUL") return application?.participantId ? "joined" : "pending";
185
- if (payment === "PENDING_OWNER_APPROVAL") return "pending";
186
- return "approved";
187
- }
188
- if (status === "PAYMENT_PENDING") return "approved";
189
- if (status === "INVITED") return "invited";
190
- return "none";
191
- }
192
-
193
- const STATUS: Record<Exclude<Standing, "none">, { key: string; fallback: string; icon: string; color: string }> = {
194
- joined: { key: "memberPrograms.status.joined", fallback: "Joined", icon: "checkmark", color: "accentPrimary" },
195
- completed: { key: "memberPrograms.status.completed", fallback: "Program complete", icon: "trophy", color: "success" },
196
- finished: { key: "memberPrograms.status.ended", fallback: "Program ended", icon: "flag", color: "textSecondary" },
197
- suspended: { key: "memberPrograms.status.suspended", fallback: "Participation suspended", icon: "close", color: "warning" },
198
- pending: { key: "memberPrograms.status.pending", fallback: "Pending request", icon: "clock", color: "warning" },
199
- approved: { key: "memberPrograms.status.approved", fallback: "Request approved", icon: "checkmark", color: "success" },
200
- invited: { key: "memberPrograms.status.invited", fallback: "Invited", icon: "mail", color: "accentPrimary" },
201
- };
169
+ const standingOf = (p: WixProgram, participant: WixParticipant | undefined, application: WixJoinApplication | undefined): Standing =>
170
+ sharedStandingOf(isEnded(p), participant, application);
202
171
 
203
172
  function timelineLine(p: WixProgram, participant: WixParticipant | undefined, standing: Standing, now: number): string {
204
173
  const timeline = full(p).timeline;
@@ -1,6 +1,6 @@
1
1
  import { paymentSetupMessage } from "../_shared/payment-setup.js";
2
2
  import { dispatch } from "@himalaya/dispatch";
3
- import { memberAccess, assertMemberAccess } from "../_shared/member-access.js";
3
+ import { memberAccess, assertMemberAccess, type MemberAccess } from "../_shared/member-access.js";
4
4
  import { signInPageStyle, signInSheetStyle } from "../_shared/sign-in-sheet.js";
5
5
  import { offlineWriteMessage, withOnlineWrites } from "../_shared/online-actions.js";
6
6
  // Tier-5 bundle: himi-branded-lite — single online-program detail (design §3.5
@@ -31,14 +31,20 @@ import { descriptionBody } from "../_shared/rich-body.js";
31
31
  import { programDescription } from "../_shared/program-description.js";
32
32
  import { openRichLink } from "../_shared/rich-content-link.js";
33
33
  import {
34
+ cancelJoinApplication,
34
35
  getProgram,
35
36
  joinProgram,
36
37
  payableIdOf,
38
+ participationsByProgram,
39
+ queryJoinApplications,
37
40
  queryPrograms,
38
41
  searchMemberParticipation,
42
+ type WixJoinApplication,
43
+ type WixParticipant,
39
44
  type WixProgram,
40
45
  type WixProgramFull,
41
46
  } from "@himalaya/wix-online-programs";
47
+ import { standingOf, STATUS, type Standing } from "../_shared/program-standing.js";
42
48
  import { createRedirectSession } from "@himalaya/wix-redirects";
43
49
  import { getMyMember } from "@himalaya/wix-members";
44
50
  import { session as wixPlatformSession, i18n } from "@himalaya/wix-platform";
@@ -55,6 +61,9 @@ import { iapPriceCopy, iapPurchaseCopy, resetUnhydratedKeysOnOlderRuntime } from
55
61
  * paid under (mirrors AppDefId.CHALLENGES in Wix's RN apps). */
56
62
  const WIX_PROGRAMS_APP_ID = "2936372a-a1ed-4d5c-8f27-0a6a70a1a7d1";
57
63
 
64
+ interface CancelledApplication { programId: string; id: string; member: MemberAccess }
65
+ interface StandingRead { application?: WixJoinApplication; participant?: WixParticipant }
66
+
58
67
  interface State {
59
68
  status: "loading" | "ready" | "error";
60
69
  /** Outcome line for the Enrol CTA — joined / pending approval / payment / failure. */
@@ -89,6 +98,17 @@ interface State {
89
98
  enrollNote: string;
90
99
  /** An App Store program sells through Get access instead. */
91
100
  enrollHidden: boolean;
101
+ /** The Enrol CTA's label for the member's standing: Enrol, Request to join or Complete payment. */
102
+ enrollLabel: string;
103
+ /** The member's standing as one line ("Joined", "Pending request"…); empty for a visitor or a new member. */
104
+ standingLine: string;
105
+ /** Withdraws a pending join request; shown only while one is pending. */
106
+ cancelHidden: boolean;
107
+ cancelDisabled: boolean;
108
+ cancelLabel: string;
109
+ /** One member-scoped receipt survives worker recreation while Wix's query catches up. */
110
+ confirmedCancellation: CancelledApplication | null;
111
+ cancellationFeedback: string;
92
112
  /** The shared checkout's action (`commerce.purchaseFields`): shown only on the App Store route. */
93
113
  buyHidden: boolean;
94
114
  buyLabel: string;
@@ -278,7 +298,7 @@ async function enrollmentMessage(id: string, name: string, guards: CommerceGuard
278
298
  const commerce = createIapCommerce({ adapters: [onlineProgramOrders], onChange: () => { void svc.pricingPublish(); } });
279
299
  const pricing = commerce.pricing;
280
300
  const PRICING_NOT_HYDRATED = [
281
- "priceLine", "priceNote", "hidePriceRetry", "enrollDisabled", "enrollNote", "enrollHidden", "buyHidden", "buyLabel", "buyDisabled", "buyNote",
301
+ "priceLine", "priceNote", "hidePriceRetry", "enrollDisabled", "enrollNote", "enrollHidden", "enrollLabel", "standingLine", "cancelHidden", "cancelDisabled", "cancelLabel", "buyHidden", "buyLabel", "buyDisabled", "buyNote",
282
302
  ] as const;
283
303
  const CONTENT_KEYS = ["status", "name", "description", "descriptionJson", "meta", "facts", "image", "initial", "emptyText"] as const;
284
304
  type Content = Pick<State, (typeof CONTENT_KEYS)[number]>;
@@ -290,6 +310,28 @@ let actionMessage = "";
290
310
  let loadSeq = 0;
291
311
  let commerceStarted = false;
292
312
  let enrollmentInFlight = false;
313
+ // Unknown initial standing stays "none"; known standing survives transient reads only
314
+ // for its original program and revalidated member. `joinProgram` still guards every enrollment.
315
+ let standing: Standing = "none";
316
+ let standingContext: { programId: string; member: MemberAccess } | undefined;
317
+ let standingProgramId = "";
318
+ let standingMember: MemberAccess | undefined;
319
+ let pendingApplicationId = "";
320
+ let pendingProgramId = "";
321
+ let pendingMember: MemberAccess | undefined;
322
+ // One confirmed withdrawal, scoped to its program and member. Wix may keep returning the old
323
+ // pending row while cancellation propagates; it must not resurrect that request's cancel action.
324
+ let cancelledApplication: CancelledApplication | undefined;
325
+ let cancellationFeedback = "";
326
+ // A failed attempt belongs only to the pending request that can still be retried.
327
+ let failedCancellationFeedback: (CancelledApplication & { message: string }) | undefined;
328
+ let cancellationReconciliation: (CancelledApplication & { afterSeq: number; confirmed: boolean }) | undefined;
329
+ let standingSeq = 0;
330
+ let latestStandingRead: { programId: string; seq: number; promise: Promise<StandingRead | undefined> } | undefined;
331
+ let programEnded = false;
332
+ let programPrivate = false;
333
+ let programSecret = false;
334
+ let cancelInFlight = false;
293
335
  // Presentation dedupe only. The host remains the sole authority to resume a join.
294
336
  let openedAuthToken = "";
295
337
  let signInPresentation: "sheet" | "full_screen" = "sheet";
@@ -307,6 +349,14 @@ function contentOf(state: State): Content {
307
349
  }
308
350
 
309
351
  const programReference = () => onlineProgramItem({ id: inputId() })?.reference;
352
+ const standingForInput = () => standingContext?.programId === inputId();
353
+ const ownsStanding = (context: typeof standingContext, member: MemberAccess, id: string): boolean => {
354
+ const current = standingContext;
355
+ // A same-owner refresh may replace the verdict while identity is read; its keys remain valid.
356
+ return !!context && !!current && context.programId === id && current.programId === id && id === inputId()
357
+ && context.member.email === member.email && context.member.scope === member.scope
358
+ && current.member.email === member.email && current.member.scope === member.scope;
359
+ };
310
360
 
311
361
  async function load(state: State, arg?: unknown): Promise<undefined> {
312
362
  stashCopy(arg);
@@ -323,6 +373,14 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
323
373
  ]);
324
374
  if (seq !== loadSeq || inputId() !== id) return undefined;
325
375
  content = found ? contentOf(ready(state, found.program, locale)) : { ...content, status: "error" };
376
+ programEnded = found?.program ? programIsEnded(found.program) : false;
377
+ programPrivate = ((found?.program as WixProgramFull | undefined)?.restrictions?.accessType ?? "").toUpperCase() === "PRIVATE";
378
+ programSecret = ((found?.program as WixProgramFull | undefined)?.restrictions?.accessType ?? "").toUpperCase() === "SECRET";
379
+ // A first load can paint content before standing; a warm refresh keeps its owned view.
380
+ // Initial pricing remains guarded until the standing read below settles.
381
+ if (state.status !== "ready") void svc.pricingPublish();
382
+ if (found?.program) await loadStanding(id);
383
+ if (seq !== loadSeq || inputId() !== id) return undefined;
326
384
  pricedItem = found?.program ? onlineProgramItem({ id: inputId() }, priceOf(found.program)) : pricedItem;
327
385
  void svc.pricingPublish();
328
386
  const prices = found?.program ? priceProgram() : Promise.resolve();
@@ -334,7 +392,7 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
334
392
  const waiting = await continuation("check", id);
335
393
  if (waiting?.confirmed && found?.program) {
336
394
  await prices;
337
- if (seq === loadSeq && inputId() === id) {
395
+ if (seq === loadSeq && inputId() === id && standingForInput()) {
338
396
  // Authority stays in the host until the last asynchronous prerequisite completes:
339
397
  // expiry, cancellation or an intervening account switch can still revoke it.
340
398
  const permit = await continuation("consume", id);
@@ -345,6 +403,205 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
345
403
  return undefined;
346
404
  }
347
405
 
406
+ const programIsEnded = (program: WixProgram): boolean => {
407
+ const status = (program.status ?? program.state ?? "").toUpperCase();
408
+ return status === "ENDED" || status === "FINISHED";
409
+ };
410
+
411
+ /** Reads scoped standing. An unknown read preserves a known pending action only after revalidating
412
+ * its owner; a visitor or changed identity makes no standing claim. */
413
+ function loadStanding(id: string): Promise<StandingRead | undefined> {
414
+ const seq = ++standingSeq;
415
+ const promise = readStanding(id, seq);
416
+ if (seq === standingSeq) latestStandingRead = { programId: id, seq, promise };
417
+ return promise;
418
+ }
419
+
420
+ async function readStanding(id: string, seq: number): Promise<StandingRead | undefined> {
421
+ const previous = { standing, id: pendingApplicationId, programId: standingProgramId, member: standingMember };
422
+ const cancelled = cancelledApplication;
423
+ const failedFeedback = failedCancellationFeedback;
424
+ let failedFeedbackInvalidated = !!failedFeedback && failedFeedback.programId !== id;
425
+ let next: Standing = "none";
426
+ let applicationId = "";
427
+ let owner: MemberAccess | undefined;
428
+ let read: StandingRead | undefined;
429
+ let readOwner: MemberAccess | undefined;
430
+ let sameCancelledStanding = false;
431
+ let feedbackKnown = false;
432
+ let visitorKnown = false;
433
+ let readIdentity: MemberAccess | undefined;
434
+ try {
435
+ const member = await memberAccess();
436
+ readIdentity = member;
437
+ visitorKnown = !member.email;
438
+ failedFeedbackInvalidated ||= !!failedFeedback && (failedFeedback.member.email !== member.email
439
+ || failedFeedback.member.scope !== member.scope);
440
+ // Identity alone disproves ownership of the previous confirmation, even when
441
+ // this member's profile/standing cannot be read. The same identity stays unknown.
442
+ feedbackKnown = !!cancelled && (cancelled.programId !== id
443
+ || cancelled.member.email !== member.email || cancelled.member.scope !== member.scope);
444
+ const memberId = member.email ? (await getMyMember()).member?.id : undefined;
445
+ if (memberId) {
446
+ let participationKnown = true;
447
+ let applicationKnown = true;
448
+ const [participation, applicationRead] = await Promise.all([
449
+ searchMemberParticipation(id, memberId).catch(() => { participationKnown = false; return undefined; }),
450
+ // The query, not `getCurrentJoinApplication`: that read belongs to the join itself, which re-reads it to decide.
451
+ queryJoinApplications({ memberId, programIds: [id] }).then((r) => {
452
+ if (!Array.isArray(r?.joinApplications)) {
453
+ applicationKnown = false;
454
+ return undefined;
455
+ }
456
+ const rows = r.joinApplications;
457
+ const application = rows.find(row => row.memberId === memberId && row.programId === id);
458
+ // A broader/malformed response is not evidence that this member has no application.
459
+ if (rows.length && !application) applicationKnown = false;
460
+ return application;
461
+ }, (): WixJoinApplication | undefined => { applicationKnown = false; return undefined; }),
462
+ ]);
463
+ await assertMemberAccess(member);
464
+ // An omitted array cannot prove absence after an unconfirmed write.
465
+ participationKnown &&= Array.isArray(participation?.participants);
466
+ const rows = Array.isArray(participation?.participants) ? participation.participants : [];
467
+ const scoped = rows.filter(row => row.memberId === memberId && row.programId === id);
468
+ if (rows.length && !scoped.length) participationKnown = false;
469
+ const cancelledRow = cancelled?.programId === id && cancelled.id === applicationRead?.id
470
+ && cancelled.member.email === member.email && cancelled.member.scope === member.scope
471
+ && applicationRead?.status?.toUpperCase() === "APPROVAL_PENDING";
472
+ const application = cancelledRow ? undefined : applicationRead;
473
+ const participant: WixParticipant | undefined = participationsByProgram(scoped).get(id);
474
+ // Either read can supply standing, but only both known reads can prove an absent
475
+ // application without participation after an unconfirmed cancellation response.
476
+ if (participationKnown && applicationKnown) {
477
+ read = { application: applicationRead, participant };
478
+ readOwner = member;
479
+ }
480
+ sameCancelledStanding = cancelledRow && !participant;
481
+ feedbackKnown ||= applicationKnown || !!participant;
482
+ next = standingOf(programEnded, participant, application);
483
+ if (next !== "none") owner = member;
484
+ if (failedFeedback && (applicationKnown || participant)) {
485
+ failedFeedbackInvalidated ||= !!participant || applicationRead?.id !== failedFeedback.id
486
+ || applicationRead?.status?.toUpperCase() !== "APPROVAL_PENDING";
487
+ }
488
+ if (!participant && application?.status?.toUpperCase() === "APPROVAL_PENDING") {
489
+ applicationId = application.id ?? "";
490
+ owner = member;
491
+ }
492
+ }
493
+ } catch { /* unknown standing */ }
494
+ const previousWithdrawn = cancelled?.programId === id && cancelled.id === previous.id
495
+ && cancelled.member.email === previous.member?.email && cancelled.member.scope === previous.member?.scope;
496
+ if (!read && next === "none" && previous.standing !== "none" && previous.programId === id && previous.member && !previousWithdrawn) {
497
+ try {
498
+ await assertMemberAccess(previous.member);
499
+ next = previous.standing;
500
+ applicationId = previous.id;
501
+ owner = previous.member;
502
+ } catch { /* never retain another member's standing */ }
503
+ }
504
+ if (seq !== standingSeq || id !== inputId()) return undefined;
505
+ const reconciliation = cancellationReconciliation;
506
+ // A published, owned read started after the write can confirm it, including
507
+ // a screen refresh that superseded the action's own read. Unknown reads cannot undo it.
508
+ if (reconciliation && !reconciliation.confirmed && read && readOwner
509
+ && seq > reconciliation.afterSeq && id === reconciliation.programId
510
+ && readOwner.email === reconciliation.member.email && readOwner.scope === reconciliation.member.scope
511
+ && !read.participant && (!read.application || isCancelledApplication(read.application, reconciliation.id))) {
512
+ reconciliation.confirmed = true;
513
+ cancelledApplication = { programId: id, id: reconciliation.id, member: reconciliation.member };
514
+ }
515
+ if (failedFeedbackInvalidated && failedFeedback === failedCancellationFeedback) {
516
+ if (actionMessage === failedFeedback?.message) actionMessage = "";
517
+ failedCancellationFeedback = undefined;
518
+ }
519
+ if (cancellationFeedback && feedbackKnown && !sameCancelledStanding) {
520
+ if (actionMessage === cancellationFeedback) actionMessage = "";
521
+ cancellationFeedback = "";
522
+ }
523
+ standing = next;
524
+ const knownMember = owner ?? readIdentity;
525
+ standingContext = (visitorKnown || !!read || next !== "none") && knownMember ? { programId: id, member: knownMember } : undefined;
526
+ standingProgramId = next !== "none" ? id : "";
527
+ standingMember = next !== "none" ? owner : undefined;
528
+ pendingApplicationId = applicationId;
529
+ pendingProgramId = applicationId ? id : "";
530
+ pendingMember = applicationId ? owner : undefined;
531
+ return read;
532
+ }
533
+
534
+ const isCancelledApplication = (application: WixJoinApplication | undefined, id: string): boolean =>
535
+ application?.id === id && ["CANCELED", "CANCELLED"].includes((application.status ?? "").toUpperCase());
536
+
537
+ /** Withdraws the member's pending join request, then re-reads the standing. */
538
+ async function cancelRequest(): Promise<undefined> {
539
+ const id = inputId();
540
+ const applicationId = pendingApplicationId;
541
+ const owner = pendingMember;
542
+ if (!id || pendingProgramId !== id || !applicationId || !owner || cancelInFlight || enrollmentInFlight) return undefined;
543
+ if (!connectivity().online) {
544
+ actionMessage = offlineWriteMessage;
545
+ void svc.pricingPublish();
546
+ return undefined;
547
+ }
548
+ cancelInFlight = true;
549
+ void svc.pricingPublish();
550
+ try {
551
+ await assertMemberAccess(owner);
552
+ if (id !== inputId()) return undefined;
553
+ const result = await cancelJoinApplication(applicationId);
554
+ const application = result.joinApplication;
555
+ const confirmed = isCancelledApplication(application, applicationId);
556
+ const reconciliation = { programId: id, id: applicationId, member: owner, afterSeq: standingSeq, confirmed };
557
+ cancellationReconciliation = reconciliation;
558
+ // The response confirms the initiating member's write even if the active account
559
+ // changed while it was in flight. Keep the scoped receipt before checking UI ownership.
560
+ if (confirmed) cancelledApplication = { programId: id, id: applicationId, member: owner };
561
+ await assertMemberAccess(owner);
562
+ if (id !== inputId()) return undefined;
563
+ let settledSeq = standingSeq + 1;
564
+ await loadStanding(id);
565
+ // A superseded read is not the end of reconciliation. Join newer refreshes
566
+ // until one settles or a scoped confirmation has already been retained.
567
+ for (;;) {
568
+ await assertMemberAccess(owner);
569
+ if (id !== inputId()) return undefined;
570
+ const latest = latestStandingRead;
571
+ if (reconciliation.confirmed || !latest || latest.programId !== id || latest.seq <= settledSeq) break;
572
+ await latest.promise;
573
+ settledSeq = latest.seq;
574
+ }
575
+ if (id === inputId()) {
576
+ const succeeded = reconciliation.confirmed;
577
+ actionMessage = succeeded ? copyParam("program.requestCancelledMessage", "Your join request was cancelled.")
578
+ : copyParam("program.cancelRequestFailedMessage", "The request could not be cancelled. Try again.");
579
+ cancellationFeedback = succeeded ? actionMessage : "";
580
+ failedCancellationFeedback = succeeded ? undefined : { programId: id, id: applicationId, member: owner, message: actionMessage };
581
+ }
582
+ } catch {
583
+ let stillOwner = false;
584
+ try { await assertMemberAccess(owner); stillOwner = true; } catch { /* no feedback for another member */ }
585
+ if (id === inputId()) {
586
+ if (stillOwner) {
587
+ actionMessage = copyParam("program.cancelRequestFailedMessage", "The request could not be cancelled. Try again.");
588
+ failedCancellationFeedback = { programId: id, id: applicationId, member: owner, message: actionMessage };
589
+ }
590
+ else {
591
+ actionMessage = "";
592
+ cancellationFeedback = "";
593
+ failedCancellationFeedback = undefined;
594
+ await loadStanding(id);
595
+ }
596
+ }
597
+ } finally {
598
+ cancellationReconciliation = undefined;
599
+ cancelInFlight = false;
600
+ void svc.pricingPublish();
601
+ }
602
+ return undefined;
603
+ }
604
+
348
605
  /** First entry recovers held purchases; every later one (a return to the screen) reconciles. */
349
606
  async function resumeCommerce(): Promise<void> {
350
607
  const first = !commerceStarted;
@@ -364,7 +621,8 @@ async function priceProgram(): Promise<void> {
364
621
  async function enroll(afterAuthAccount = ""): Promise<undefined> {
365
622
  const id = inputId();
366
623
  const reference = programReference();
367
- if (!reference || enrollmentInFlight) return undefined;
624
+ const context = standingContext;
625
+ if (!reference || enrollmentInFlight || !standingForInput()) return undefined;
368
626
  if (!connectivity().online) {
369
627
  actionMessage = offlineWriteMessage;
370
628
  void svc.pricingPublish();
@@ -379,7 +637,7 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
379
637
  void svc.pricingPublish();
380
638
  try {
381
639
  const member = await memberAccess();
382
- if (id !== inputId()) return undefined;
640
+ if (!ownsStanding(context, member, id)) return undefined;
383
641
  if (afterAuthAccount && member.email !== afterAuthAccount) return undefined;
384
642
  if (!member.email) {
385
643
  const request = await continuation("begin", id);
@@ -443,18 +701,33 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
443
701
  enrollmentInFlight = false;
444
702
  void svc.pricingPublish();
445
703
  }
704
+ if (id === inputId()) {
705
+ await loadStanding(id);
706
+ void svc.pricingPublish();
707
+ }
446
708
  return undefined;
447
709
  }
448
710
 
449
711
  /** The App Store sale: only through the shared checkout, and only for the route the price shows. */
450
712
  async function buy(): Promise<undefined> {
713
+ const id = inputId();
451
714
  const reference = programReference();
452
- if (!reference) return undefined;
715
+ const context = standingContext;
716
+ if (!reference || !standingForInput()) return undefined;
717
+ if (!ownsStanding(context, await memberAccess(), id)) return undefined;
453
718
  await commerce.buy({ reference });
454
719
  void svc.pricingPublish();
455
720
  return undefined;
456
721
  }
457
722
 
723
+ const canEnrol = (value: Standing): boolean => !programEnded && ((value === "none" && !programSecret) || value === "approved");
724
+
725
+ function enrollLabelFor(value: Standing): string {
726
+ return value === "approved" ? copyParam("memberPrograms.action.pay", "Complete payment")
727
+ : programPrivate ? copyParam("memberPrograms.action.request", "Request to join")
728
+ : copyParam("program.enrolCta", "Enrol");
729
+ }
730
+
458
731
  function pricedState(state: State): State {
459
732
  const reference = programReference();
460
733
  const view = reference && pricing.view(reference);
@@ -466,8 +739,16 @@ function pricedState(state: State): State {
466
739
  actionMessage: purchase.accessReady ? copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name }) : actionMessage,
467
740
  // `disabled`: this app sells nothing through the App Store, so the program shows its own price.
468
741
  priceLine: view?.route === "disabled" ? pricedItem?.commerceDisplayPrice ?? "" : price.priceText, priceNote: price.priceNote, hidePriceRetry: view?.route === "disabled" || (price.hidePriceRetry && commerce.scopeComplete()),
469
- enrollDisabled: price.actionDisabled || enrollmentInFlight, enrollNote: price.actionNote, enrollHidden: purchase.appleRoute,
470
- buyHidden: !purchase.appleRoute || purchase.accessReady, buyLabel: purchase.buyLabel, buyDisabled: purchase.buyDisabled, buyNote: purchase.buyNote,
742
+ enrollDisabled: !standingForInput() || price.actionDisabled || enrollmentInFlight || cancelInFlight, enrollNote: price.actionNote,
743
+ // A member who has joined, asked to join or been invited has nothing to enrol in: the standing line
744
+ // says where they are. Only a new member, or one whose payment is owed, sees the CTA.
745
+ enrollHidden: purchase.appleRoute || !canEnrol(standing), enrollLabel: enrollLabelFor(standing),
746
+ standingLine: standing === "none" ? "" : copyParam(STATUS[standing].key, STATUS[standing].fallback),
747
+ cancelHidden: standing !== "pending" || !pendingApplicationId, cancelLabel: copyParam("program.cancelRequestCta", "Cancel request"),
748
+ cancelDisabled: cancelInFlight || enrollmentInFlight,
749
+ confirmedCancellation: cancelledApplication ?? null,
750
+ cancellationFeedback,
751
+ buyHidden: !purchase.appleRoute || purchase.accessReady || !canEnrol(standing), buyLabel: purchase.buyLabel, buyDisabled: !standingForInput() || purchase.buyDisabled, buyNote: purchase.buyNote,
471
752
  ...(poll ? { _poll: poll } : {}),
472
753
  });
473
754
  }
@@ -499,6 +780,13 @@ const INITIAL_STATE: State = derive({
499
780
  enrollDisabled: true,
500
781
  enrollNote: "",
501
782
  enrollHidden: false,
783
+ enrollLabel: copyParam("program.enrolCta", "Enrol"),
784
+ standingLine: "",
785
+ cancelHidden: true,
786
+ cancelDisabled: false,
787
+ cancelLabel: copyParam("program.cancelRequestCta", "Cancel request"),
788
+ confirmedCancellation: null,
789
+ cancellationFeedback: "",
502
790
  buyHidden: true,
503
791
  buyLabel: "",
504
792
  buyDisabled: true,
@@ -509,6 +797,7 @@ type Actions = {
509
797
  openLink: (state: State, arg?: unknown) => Promise<undefined>;
510
798
  load: (state: State, arg?: unknown) => Promise<State | undefined>;
511
799
  enroll: (state: State) => Promise<State | undefined>;
800
+ cancelRequest: (state: State) => Promise<State | undefined>;
512
801
  buy: (state: State) => Promise<State | undefined>;
513
802
  pricingPublish: (state: State) => State;
514
803
  pricingStart: (state: State) => State;
@@ -516,13 +805,14 @@ type Actions = {
516
805
  iapPoll: (state: State) => Promise<undefined>;
517
806
  };
518
807
 
519
- const defineService = withOnlineWrites(registerService, ["enroll","buy"], { derive, messageFields: ["actionMessage"] });
808
+ const defineService = withOnlineWrites(registerService, ["enroll","cancelRequest","buy"], { derive, messageFields: ["actionMessage"] });
520
809
  const svc = defineService<State, Actions>("himiBrandedProgram", {
521
810
  state: INITIAL_STATE,
522
811
  notHydrated: [...PRICING_NOT_HYDRATED],
523
812
  actions: {
524
813
  load,
525
814
  enroll: () => enroll(),
815
+ cancelRequest,
526
816
  buy,
527
817
  pricingPublish: pricedState,
528
818
  openLink: async (_state, arg) => { await openRichLink(arg); return undefined; },
@@ -533,6 +823,9 @@ const svc = defineService<State, Actions>("himiBrandedProgram", {
533
823
  });
534
824
 
535
825
  content = contentOf(svc.getState());
826
+ cancelledApplication = svc.getState().confirmedCancellation ?? undefined;
827
+ cancellationFeedback = svc.getState().cancellationFeedback ?? "";
828
+ if (svc.getState().actionMessage === cancellationFeedback) actionMessage = cancellationFeedback;
536
829
  resetUnhydratedKeysOnOlderRuntime(svc, INITIAL_STATE, PRICING_NOT_HYDRATED);
537
830
  void svc.pricingStart();
538
831