@revenexx/cover 0.2.7 → 0.2.9

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.
@@ -1,6 +1,7 @@
1
1
  export const accountApi = {
2
2
  profile: () => "/api/account/profile",
3
3
  orders: () => "/api/account/orders",
4
+ orderReturn: (id: string) => `/api/account/orders/${id}/return`,
4
5
  addresses: () => "/api/account/addresses",
5
6
  addressUpdate: (id: string) => `/api/account/address/${id}`,
6
7
  addressCreate: () => "/api/account/address",
@@ -1,4 +1,5 @@
1
1
  <script setup lang="ts">
2
+ import { accountApi } from "../../../api/account";
2
3
  import type { AccountOrder, AccountOrderStatus, AccountOrderPaymentStatus } from "../../../interfaces/account/order-list";
3
4
 
4
5
  /**
@@ -19,7 +20,7 @@ const cart = useCartStore();
19
20
  const { getImage } = useProductImage();
20
21
  const { formatCurrency } = useCartSummaryFormatting();
21
22
 
22
- const { data: order, status, error } = useFetch<AccountOrder>(
23
+ const { data: order, status, error, refresh } = useFetch<AccountOrder>(
23
24
  `/api/account/orders/${props.orderId}`,
24
25
  { key: `account-order:${props.orderId}` },
25
26
  );
@@ -119,6 +120,82 @@ async function orderAgain(): Promise<void> {
119
120
  });
120
121
  await navigateTo(to("/cart"));
121
122
  }
123
+
124
+ /* ---- self-service returns -------------------------------------------- */
125
+ /** Positions that still have units available to return. */
126
+ const returnablePositions = computed(() =>
127
+ (order.value?.positions ?? []).filter(p => (p.returnableQuantity ?? 0) > 0 && p.orderItemId));
128
+
129
+ const canRequestReturn = computed(() =>
130
+ (order.value?.status === "shipped" || order.value?.status === "delivered")
131
+ && returnablePositions.value.length > 0);
132
+
133
+ const returnStatusColors: Record<string, "info" | "warning" | "success" | "neutral"> = {
134
+ requested: "warning",
135
+ approved: "info",
136
+ received: "info",
137
+ completed: "success",
138
+ rejected: "neutral",
139
+ };
140
+
141
+ const returnOpen = ref(false);
142
+ const submittingReturn = ref(false);
143
+ const returnReason = ref("");
144
+ /** order_item id → quantity to return. */
145
+ const returnQuantities = reactive<Record<string, number>>({});
146
+
147
+ function openReturn(): void {
148
+ returnReason.value = "";
149
+ for (const key of Object.keys(returnQuantities)) {
150
+ delete returnQuantities[key];
151
+ }
152
+ for (const position of returnablePositions.value) {
153
+ if (position.orderItemId) {
154
+ returnQuantities[position.orderItemId] = 0;
155
+ }
156
+ }
157
+ returnOpen.value = true;
158
+ }
159
+
160
+ const selectedReturnPositions = computed(() =>
161
+ returnablePositions.value
162
+ .filter(p => p.orderItemId && (returnQuantities[p.orderItemId] ?? 0) > 0)
163
+ .map(p => ({ orderItemId: p.orderItemId as string, quantity: returnQuantities[p.orderItemId as string]! })));
164
+
165
+ async function submitReturn(): Promise<void> {
166
+ if (!order.value || selectedReturnPositions.value.length === 0) {
167
+ return;
168
+ }
169
+ submittingReturn.value = true;
170
+ try {
171
+ await $fetch(accountApi.orderReturn(order.value.id), {
172
+ method: "POST",
173
+ body: {
174
+ positions: selectedReturnPositions.value,
175
+ ...(returnReason.value.trim() ? { reason: returnReason.value.trim() } : {}),
176
+ },
177
+ });
178
+ returnOpen.value = false;
179
+ toast.add({
180
+ title: t("orders.returns.success"),
181
+ color: "success",
182
+ icon: icon("success"),
183
+ duration: 2500,
184
+ });
185
+ await refresh();
186
+ }
187
+ catch {
188
+ toast.add({
189
+ title: t("orders.returns.error"),
190
+ color: "error",
191
+ icon: icon("error"),
192
+ duration: 3000,
193
+ });
194
+ }
195
+ finally {
196
+ submittingReturn.value = false;
197
+ }
198
+ }
122
199
  </script>
123
200
 
124
201
  <template>
@@ -382,8 +459,62 @@ async function orderAgain(): Promise<void> {
382
459
  </dl>
383
460
  </section>
384
461
 
462
+ <!-- Existing returns -->
463
+ <section
464
+ v-if="order.returns?.length"
465
+ class="border border-(--ui-border) rounded-xl overflow-hidden"
466
+ >
467
+ <h2 class="px-4 sm:px-5 py-3 text-sm font-semibold text-highlighted bg-elevated/60 border-b border-(--ui-border)">
468
+ {{ t('orders.returns.existingTitle') }}
469
+ </h2>
470
+ <ul class="divide-y divide-(--ui-border) px-4 sm:px-5">
471
+ <li
472
+ v-for="ret in order.returns"
473
+ :key="ret.id"
474
+ class="py-3"
475
+ >
476
+ <div class="flex items-center gap-3">
477
+ <UIcon
478
+ :name="icon('package')"
479
+ class="size-5 text-primary shrink-0"
480
+ />
481
+ <span class="text-sm font-medium text-highlighted">
482
+ {{ ret.number }}
483
+ </span>
484
+ <UBadge
485
+ class="ms-auto"
486
+ :color="returnStatusColors[ret.status] ?? 'neutral'"
487
+ variant="subtle"
488
+ size="sm"
489
+ :label="t(`orders.returns.status.${ret.status}`, ret.status)"
490
+ />
491
+ </div>
492
+ <ul
493
+ v-if="ret.positions.length"
494
+ class="mt-1.5 ps-8 text-xs text-muted"
495
+ >
496
+ <li
497
+ v-for="(pos, posIndex) in ret.positions"
498
+ :key="posIndex"
499
+ >
500
+ {{ pos.quantity }}× {{ pos.name }}
501
+ </li>
502
+ </ul>
503
+ </li>
504
+ </ul>
505
+ </section>
506
+
385
507
  <!-- Actions -->
386
- <div class="flex justify-end">
508
+ <div class="flex flex-wrap justify-end gap-2">
509
+ <UButton
510
+ v-if="canRequestReturn"
511
+ color="neutral"
512
+ variant="outline"
513
+ tabindex="0"
514
+ :icon="icon('package')"
515
+ :label="t('orders.returns.requestReturn')"
516
+ @click="openReturn"
517
+ />
387
518
  <UButton
388
519
  v-if="order.status !== 'cancelled'"
389
520
  color="primary"
@@ -394,6 +525,71 @@ async function orderAgain(): Promise<void> {
394
525
  @click="orderAgain"
395
526
  />
396
527
  </div>
528
+
529
+ <!-- Request return modal -->
530
+ <UModal
531
+ v-model:open="returnOpen"
532
+ :title="t('orders.returns.modalTitle')"
533
+ >
534
+ <template #body>
535
+ <div class="space-y-4">
536
+ <p
537
+ v-if="returnablePositions.length === 0"
538
+ class="text-sm text-muted"
539
+ >
540
+ {{ t('orders.returns.emptyReturnable') }}
541
+ </p>
542
+ <template v-else>
543
+ <div
544
+ v-for="position in returnablePositions"
545
+ :key="position.orderItemId"
546
+ class="flex items-center gap-3"
547
+ >
548
+ <div class="min-w-0 flex-1">
549
+ <p class="text-sm font-medium text-highlighted truncate">
550
+ {{ position.name }}
551
+ </p>
552
+ <p class="text-xs text-muted">
553
+ {{ t('orders.returns.maxReturnable', { count: position.returnableQuantity ?? 0 }) }}
554
+ </p>
555
+ </div>
556
+ <UInputNumber
557
+ v-model="returnQuantities[position.orderItemId as string]"
558
+ :min="0"
559
+ :max="position.returnableQuantity ?? 0"
560
+ class="w-28 shrink-0"
561
+ :aria-label="t('orders.returns.quantity')"
562
+ />
563
+ </div>
564
+ <UFormField :label="t('orders.returns.reason')">
565
+ <UTextarea
566
+ v-model="returnReason"
567
+ class="w-full"
568
+ :rows="3"
569
+ :placeholder="t('orders.returns.reasonPlaceholder')"
570
+ />
571
+ </UFormField>
572
+ </template>
573
+ </div>
574
+ </template>
575
+ <template #footer>
576
+ <div class="flex items-center justify-end gap-2 w-full">
577
+ <UButton
578
+ color="neutral"
579
+ variant="ghost"
580
+ :label="t('orders.returns.cancel')"
581
+ @click="returnOpen = false"
582
+ />
583
+ <UButton
584
+ color="primary"
585
+ :loading="submittingReturn"
586
+ :disabled="selectedReturnPositions.length === 0"
587
+ :label="t('orders.returns.submit')"
588
+ @click="submitReturn"
589
+ />
590
+ </div>
591
+ </template>
592
+ </UModal>
397
593
  </div>
398
594
  </div>
399
595
  </template>
@@ -17,6 +17,17 @@ export interface AccountOrderPosition {
17
17
  readonly lineTotal: number;
18
18
  readonly categorySlug?: string;
19
19
  readonly subcategorySlug?: string;
20
+ /** The order_item id — needed to request a return for this position. */
21
+ readonly orderItemId?: string;
22
+ /** How many units of this position can still be returned (shipped − already returned). */
23
+ readonly returnableQuantity?: number;
24
+ }
25
+
26
+ export interface AccountOrderReturn {
27
+ readonly id: string;
28
+ readonly number: string;
29
+ readonly status: string;
30
+ readonly positions: { readonly name: string; readonly quantity: number }[];
20
31
  }
21
32
 
22
33
  export interface AccountOrder {
@@ -46,6 +57,8 @@ export interface AccountOrder {
46
57
  readonly progress?: { step: "ordered" | "processing" | "shipped" | "delivered"; date?: string }[];
47
58
  /** Approvers when the order awaits approval. */
48
59
  readonly approvers?: string[];
60
+ /** Returns already requested against this order. */
61
+ readonly returns?: AccountOrderReturn[];
49
62
  }
50
63
 
51
64
  export interface AccountOrderListResponse {
@@ -96,6 +96,27 @@
96
96
  "refresh": "Aktualisieren",
97
97
  "notFound": "Bestellung nicht gefunden",
98
98
  "searchPlaceholder": "Nach Bestellnummer oder Artikel suchen …",
99
+ "returns": {
100
+ "requestReturn": "Rücksendung anfragen",
101
+ "modalTitle": "Rücksendung anfragen",
102
+ "reason": "Grund (optional)",
103
+ "reasonPlaceholder": "Warum möchten Sie diese Artikel zurücksenden?",
104
+ "quantity": "Menge",
105
+ "maxReturnable": "Bis zu {count} rücksendbar",
106
+ "submit": "Rücksendung absenden",
107
+ "cancel": "Abbrechen",
108
+ "success": "Rücksendung angefragt",
109
+ "error": "Rücksendung konnte nicht angefragt werden",
110
+ "existingTitle": "Rücksendungen",
111
+ "emptyReturnable": "Keine dieser Positionen kann zurückgesendet werden.",
112
+ "status": {
113
+ "requested": "Angefragt",
114
+ "approved": "Genehmigt",
115
+ "received": "Eingegangen",
116
+ "completed": "Abgeschlossen",
117
+ "rejected": "Abgelehnt"
118
+ }
119
+ },
99
120
  "detail": {
100
121
  "progressTitle": "Bestellstatus",
101
122
  "steps": {
@@ -96,6 +96,27 @@
96
96
  "refresh": "Refresh",
97
97
  "notFound": "Order not found",
98
98
  "searchPlaceholder": "Search by order number or item…",
99
+ "returns": {
100
+ "requestReturn": "Request return",
101
+ "modalTitle": "Request a return",
102
+ "reason": "Reason (optional)",
103
+ "reasonPlaceholder": "Tell us why you're returning these items…",
104
+ "quantity": "Quantity",
105
+ "maxReturnable": "Up to {count} returnable",
106
+ "submit": "Submit return",
107
+ "cancel": "Cancel",
108
+ "success": "Return requested",
109
+ "error": "Return could not be requested",
110
+ "existingTitle": "Returns",
111
+ "emptyReturnable": "None of these positions can be returned.",
112
+ "status": {
113
+ "requested": "Requested",
114
+ "approved": "Approved",
115
+ "received": "Received",
116
+ "completed": "Completed",
117
+ "rejected": "Rejected"
118
+ }
119
+ },
99
120
  "detail": {
100
121
  "progressTitle": "Order progress",
101
122
  "steps": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/cover",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "Cover — revenexx design system for Nuxt. Distributed as a Nuxt layer: generic UI components, theming tokens and stores shared by the demo shop, custom storefronts and the Blokkli theme.",
5
5
  "type": "module",
6
6
  "main": "./nuxt.config.ts",
@@ -38,7 +38,7 @@
38
38
  "@formkit/vue": "^1.6.0",
39
39
  "@iconify-json/lucide": "^1.2.111",
40
40
  "@internationalized/date": "^3.12.0",
41
- "@revenexx/sdk": "^0.0.11",
41
+ "@revenexx/sdk": "^0.0.12",
42
42
  "@revenexx/storage-model-viewer": "^0.3.0",
43
43
  "@vueuse/core": "^14.3.0",
44
44
  "typesense": "^3.0.5"
@@ -0,0 +1,69 @@
1
+ import type { AccountOrder, AccountOrderListResponse, AccountOrderReturn } from "../../../../../app/interfaces/account/order-list";
2
+ import { enrichMockOrderReturnables } from "../[id].get";
3
+
4
+ interface ReturnRequestBody {
5
+ positions?: { orderItemId: string; quantity: number }[];
6
+ reason?: string;
7
+ }
8
+
9
+ /**
10
+ * Request a return for shipped positions of one order. Live: hands the
11
+ * positions to the orders app (which guards each quantity against the still-
12
+ * returnable amount). Mock: appends a demo return so the demo shop surfaces
13
+ * the feature end-to-end. Returns the refreshed order either way.
14
+ */
15
+ export default defineEventHandler(async (event): Promise<AccountOrder> => {
16
+ const user = await getAuthService(event).me(event);
17
+ if (!user) {
18
+ throw createError({ statusCode: 401, message: "Unauthorized" });
19
+ }
20
+
21
+ const id = getRouterParam(event, "id") ?? "";
22
+ const body = await readBody<ReturnRequestBody>(event);
23
+ const positions = (body?.positions ?? []).filter(p => p.orderItemId && Number(p.quantity) > 0);
24
+ if (positions.length === 0) {
25
+ throw createError({ statusCode: 422, message: "No positions to return" });
26
+ }
27
+
28
+ if (resolveOrderServiceKey(event) === "api") {
29
+ try {
30
+ const order = await requestOrderReturn(
31
+ id,
32
+ positions.map(p => ({ orderItemId: p.orderItemId, quantity: Number(p.quantity) })),
33
+ body?.reason,
34
+ );
35
+ if (!order) {
36
+ throw createError({ statusCode: 404, message: "Order not found" });
37
+ }
38
+ return order;
39
+ }
40
+ catch (err) {
41
+ if (isError(err)) {
42
+ throw err;
43
+ }
44
+ getLogService().error("Live order return failed", apiErrorContext(err));
45
+ throw createError({ statusCode: 502, message: "Order service unavailable" });
46
+ }
47
+ }
48
+
49
+ // Mock: persist a demo return on the order and echo it back enriched.
50
+ const history = await readCoverMutableJson<AccountOrderListResponse>("account/order-list.json");
51
+ const index = history.orders.findIndex(o => o.id === id);
52
+ if (index < 0) {
53
+ throw createError({ statusCode: 404, message: "Order not found" });
54
+ }
55
+ const order = history.orders[index]!;
56
+ const demoReturn: AccountOrderReturn = {
57
+ id: `ret-${Date.now()}`,
58
+ number: `RMA-${order.id}-${(order.returns?.length ?? 0) + 1}`,
59
+ status: "requested",
60
+ positions: positions.map((p) => {
61
+ const match = order.positions.find(pos => (pos.orderItemId ?? pos.id) === p.orderItemId);
62
+ return { name: match?.name ?? p.orderItemId, quantity: Number(p.quantity) };
63
+ }),
64
+ };
65
+ const updated: AccountOrder = { ...order, returns: [...(order.returns ?? []), demoReturn] };
66
+ history.orders[index] = updated;
67
+ await writeCoverMutableJson("account/order-list.json", history);
68
+ return enrichMockOrderReturnables(updated);
69
+ });
@@ -1,4 +1,4 @@
1
- import type { AccountOrderListResponse } from "../../../../app/interfaces/account/order-list";
1
+ import type { AccountOrder, AccountOrderListResponse } from "../../../../app/interfaces/account/order-list";
2
2
 
3
3
  /** Single order from the account history (live: by display number). */
4
4
  export default defineEventHandler(async (event) => {
@@ -31,5 +31,30 @@ export default defineEventHandler(async (event) => {
31
31
  if (!order) {
32
32
  throw createError({ statusCode: 404, message: "Order not found" });
33
33
  }
34
- return order;
34
+ return enrichMockOrderReturnables(order);
35
35
  });
36
+
37
+ /**
38
+ * Mock orders carry no fulfillment quantities — surface the self-service
39
+ * return feature in the demo by treating every position of a shipped/delivered
40
+ * order as fully returnable (minus any already-requested demo return).
41
+ */
42
+ export function enrichMockOrderReturnables(order: AccountOrder): AccountOrder {
43
+ if (order.status !== "shipped" && order.status !== "delivered") {
44
+ return order;
45
+ }
46
+ const returnedByItem: Record<string, number> = {};
47
+ for (const ret of order.returns ?? []) {
48
+ for (const pos of ret.positions) {
49
+ returnedByItem[pos.name] = (returnedByItem[pos.name] ?? 0) + pos.quantity;
50
+ }
51
+ }
52
+ return {
53
+ ...order,
54
+ positions: order.positions.map(p => ({
55
+ ...p,
56
+ orderItemId: p.orderItemId ?? p.id,
57
+ returnableQuantity: Math.max(0, p.quantity - (returnedByItem[p.name] ?? 0)),
58
+ })),
59
+ };
60
+ }
@@ -91,42 +91,49 @@ export class ApiAuthService implements IAuthService {
91
91
  return null;
92
92
  }
93
93
 
94
- try {
95
- // session_id makes the customers app validate the session is still
96
- // alive — a logged-out/revoked session answers 401 here. Raw call:
97
- // the AuthMeRequest contract does not declare session_id yet, so
98
- // the generated customersAuthMe() would drop the session check.
99
- const { user, contact } = await useRevenexxSdk().call<{
100
- user: { $id: string; name?: string; email: string };
101
- contact: ApiContact | null;
102
- }>("POST", "/v1/customers/auth/me", { body: { user_id: parsed.userId, session_id: parsed.id } });
94
+ // Validate the session against the customers app, retrying transient
95
+ // failures. A 401 is the only proof the session is gone (revoked/expired)
96
+ // → clear the cookie + log out. Anything else (5xx "capability dispatch
97
+ // failed", network blip, cold-start dispatch) is transient infra trouble:
98
+ // returning null on the FIRST blip bounced a still-valid session to login
99
+ // mid-flight (worst on a cold storefront's first SSR me()). So retry a
100
+ // couple times before giving up; the cookie is never dropped on transient
101
+ // errors, and the request only degrades to guest if every attempt blips.
102
+ const MAX_ATTEMPTS = 3;
103
+ let lastErr: unknown;
104
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
105
+ try {
106
+ // session_id makes the customers app validate the session is still
107
+ // alive — a logged-out/revoked session answers 401 here. Raw call:
108
+ // the AuthMeRequest contract does not declare session_id yet, so
109
+ // the generated customersAuthMe() would drop the session check.
110
+ const { user, contact } = await useRevenexxSdk().call<{
111
+ user: { $id: string; name?: string; email: string };
112
+ contact: ApiContact | null;
113
+ }>("POST", "/v1/customers/auth/me", { body: { user_id: parsed.userId, session_id: parsed.id } });
103
114
 
104
- return {
105
- $id: user.$id,
106
- name: contactName(contact, user.name ?? user.email),
107
- email: user.email,
108
- role: toAuthRole(contact?.role),
109
- ...(contact?.id ? { contactId: contact.id } : {}),
110
- ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
111
- };
112
- }
113
- catch (err) {
114
- // Only a genuine auth failure (401 = revoked/expired session) proves
115
- // the session is gone — clear the cookie so the user logs out cleanly.
116
- // Any other error (5xx like the gateway's "capability dispatch failed",
117
- // or a network blip) is transient infrastructure trouble, NOT proof the
118
- // session is invalid. Deleting the cookie here turned a flaky gateway
119
- // into a SILENT LOGOUT + empty order history (the account history is
120
- // filtered strictly by contact_id and falls back to me()). So keep the
121
- // cookie and return null: callers still degrade to the guest path for
122
- // this one request, and the session self-heals on the next.
123
- if (isApiUserError(err) && err.code === 401) {
124
- deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
125
- return null;
115
+ return {
116
+ $id: user.$id,
117
+ name: contactName(contact, user.name ?? user.email),
118
+ email: user.email,
119
+ role: toAuthRole(contact?.role),
120
+ ...(contact?.id ? { contactId: contact.id } : {}),
121
+ ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
122
+ };
123
+ }
124
+ catch (err) {
125
+ lastErr = err;
126
+ if (isApiUserError(err) && err.code === 401) {
127
+ deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
128
+ return null;
129
+ }
130
+ if (attempt < MAX_ATTEMPTS) {
131
+ await new Promise(resolve => setTimeout(resolve, 300 * attempt));
132
+ }
126
133
  }
127
- getLogService().error("API request failed: auth/me", apiErrorContext(err));
128
- return null;
129
134
  }
135
+ getLogService().error("API request failed: auth/me", apiErrorContext(lastErr));
136
+ return null;
130
137
  }
131
138
 
132
139
  async logout(event: H3Event): Promise<void> {
@@ -52,10 +52,13 @@ export class ApiTeamService implements ITeamService {
52
52
  return [];
53
53
  }
54
54
  try {
55
- const { items } = await useRevenexxSdk().customers.customersContactsList() as unknown as { items: ApiContactRow[] };
56
- return (items ?? [])
57
- .filter(row => row.organization_id === organization_id)
58
- .map(toAccountTeamMember);
55
+ // Typed list filter (customers.contacts.list declares its query
56
+ // params — @revenexx/sdk >= 0.0.12), so org scoping is server-side.
57
+ const { items } = await useRevenexxSdk().customers.customersContactsList({
58
+ organizationId: organization_id,
59
+ limit: 200,
60
+ }) as unknown as { items: ApiContactRow[] };
61
+ return (items ?? []).map(toAccountTeamMember);
59
62
  }
60
63
  catch (err) {
61
64
  getLogService().error("API request failed: team/list", apiErrorContext(err));
@@ -1,7 +1,7 @@
1
1
  import type { H3Event } from "h3";
2
2
 
3
3
  import type { StoredSession } from "../../app/interfaces/auth";
4
- import type { AccountOrder, AccountOrderPosition, AccountOrderStatus, AccountOrderPaymentStatus } from "../../app/interfaces/account/order-list";
4
+ import type { AccountOrder, AccountOrderPosition, AccountOrderReturn, AccountOrderStatus, AccountOrderPaymentStatus } from "../../app/interfaces/account/order-list";
5
5
 
6
6
  /**
7
7
  * Live orders via the orders app — placing from the checkout snapshot and
@@ -42,6 +42,14 @@ export interface LiveOrder {
42
42
  completed_at: string | null;
43
43
  items?: LiveOrderItem[];
44
44
  shipments?: Array<{ number: string; carrier: string | null; tracking_code: string | null; shipped_at: string }>;
45
+ returns?: LiveOrderReturn[];
46
+ }
47
+
48
+ export interface LiveOrderReturn {
49
+ id: string;
50
+ number: string;
51
+ status: string;
52
+ positions?: Array<{ order_item_id?: string; name?: string | null; quantity: number }>;
45
53
  }
46
54
 
47
55
  /** The buyer's identity refs from the session cookie (guests place openly). */
@@ -78,9 +86,25 @@ const addressLine = (a: Record<string, unknown> | null | undefined): string =>
78
86
  [a?.companyName, a?.street, `${a?.postalCode ?? ""} ${a?.city ?? ""}`.trim()]
79
87
  .filter(Boolean).join(" · ");
80
88
 
81
- function mapPositions(items: LiveOrderItem[] | undefined): AccountOrderPosition[] {
89
+ /** Units already returned per order_item id, summed across all return records. */
90
+ function returnedByOrderItem(returns: LiveOrderReturn[] | undefined): Record<string, number> {
91
+ const totals: Record<string, number> = {};
92
+ for (const ret of returns ?? []) {
93
+ for (const pos of ret.positions ?? []) {
94
+ if (pos.order_item_id) {
95
+ totals[pos.order_item_id] = (totals[pos.order_item_id] ?? 0) + Number(pos.quantity);
96
+ }
97
+ }
98
+ }
99
+ return totals;
100
+ }
101
+
102
+ function mapPositions(items: LiveOrderItem[] | undefined, returns: LiveOrderReturn[] | undefined): AccountOrderPosition[] {
103
+ const returned = returnedByOrderItem(returns);
82
104
  return (items ?? []).map((item) => {
83
105
  const snapshot = (item.product ?? {}) as Record<string, unknown>;
106
+ const shipped = Number(item.quantity_shipped) || 0;
107
+ const returnable = Math.max(0, shipped - (returned[item.id] ?? 0));
84
108
  return {
85
109
  id: item.product_id ?? item.sku ?? item.id,
86
110
  sku: item.sku ?? "",
@@ -91,10 +115,24 @@ function mapPositions(items: LiveOrderItem[] | undefined): AccountOrderPosition[
91
115
  lineTotal: Number(item.line_total),
92
116
  ...(snapshot.categorySlug ? { categorySlug: String(snapshot.categorySlug) } : {}),
93
117
  ...(snapshot.subcategorySlug ? { subcategorySlug: String(snapshot.subcategorySlug) } : {}),
118
+ orderItemId: item.id,
119
+ returnableQuantity: returnable,
94
120
  };
95
121
  });
96
122
  }
97
123
 
124
+ function mapReturns(returns: LiveOrderReturn[] | undefined): AccountOrderReturn[] {
125
+ return (returns ?? []).map(ret => ({
126
+ id: ret.id,
127
+ number: ret.number,
128
+ status: ret.status,
129
+ positions: (ret.positions ?? []).map(pos => ({
130
+ name: pos.name ?? "",
131
+ quantity: Number(pos.quantity),
132
+ })),
133
+ }));
134
+ }
135
+
98
136
  /** Live order aggregate → the account history contract. */
99
137
  export function mapLiveOrderToAccount(order: LiveOrder): AccountOrder {
100
138
  const placed = order.placed_at ?? order.created_at;
@@ -122,7 +160,8 @@ export function mapLiveOrderToAccount(order: LiveOrder): AccountOrder {
122
160
  total: Number(order.grand_total),
123
161
  currency: order.currency,
124
162
  ...(order.customer_order_number ? { orderNumber: order.customer_order_number } : {}),
125
- positions: mapPositions(order.items),
163
+ positions: mapPositions(order.items, order.returns),
164
+ ...(order.returns?.length ? { returns: mapReturns(order.returns) } : {}),
126
165
  deliveryAddress: addressLine(order.shipping_address),
127
166
  billingAddress: addressLine(order.billing_address),
128
167
  ...(order.payment?.method ? { paymentMethod: order.payment.method } : {}),
@@ -146,3 +185,29 @@ export async function getLiveOrderByNumber(number: string): Promise<LiveOrder |
146
185
  }
147
186
  return await sdk.orders.ordersGet({ id: row.id }) as unknown as LiveOrder;
148
187
  }
188
+
189
+ /**
190
+ * Request a return for shipped positions of an order (by display number).
191
+ * Resolves the order id, submits the return via the orders app — which guards
192
+ * each quantity against the still-returnable amount — and returns the freshly
193
+ * mapped order aggregate so the UI reflects the new return immediately.
194
+ */
195
+ export async function requestOrderReturn(
196
+ orderNumber: string,
197
+ positions: { orderItemId: string; quantity: number }[],
198
+ reason?: string,
199
+ ): Promise<AccountOrder | null> {
200
+ const sdk = useRevenexxSdk();
201
+ const { items } = await sdk.orders.ordersList({ number: orderNumber, limit: 1 }) as unknown as { items: LiveOrder[] };
202
+ const row = items[0];
203
+ if (!row) {
204
+ return null;
205
+ }
206
+ await sdk.orders.ordersReturn({
207
+ id: row.id,
208
+ positions: positions.map(p => ({ order_item_id: p.orderItemId, quantity: p.quantity })),
209
+ ...(reason ? { reason } : {}),
210
+ } as unknown as Parameters<typeof sdk.orders.ordersReturn>[0]);
211
+ const refreshed = await sdk.orders.ordersGet({ id: row.id }) as unknown as LiveOrder;
212
+ return mapLiveOrderToAccount(refreshed);
213
+ }