@developerx12/invoices-medusa 0.1.2 → 0.1.4

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,5 +1,6 @@
1
1
  "use strict";
2
2
  const jsxRuntime = require("react/jsx-runtime");
3
+ const react = require("react");
3
4
  const ui = require("@medusajs/ui");
4
5
  const adminSdk = require("@medusajs/admin-sdk");
5
6
  const Medusa = require("@medusajs/js-sdk");
@@ -18,13 +19,15 @@ const sdk = new Medusa__default.default({
18
19
  const OrderInvoiceWidget = ({ data: order }) => {
19
20
  var _a;
20
21
  const queryClient = reactQuery.useQueryClient();
22
+ const fileInputRef = react.useRef(null);
23
+ const uploadTargetRef = react.useRef(null);
21
24
  const {
22
25
  data: expandedOrder,
23
26
  isLoading,
24
27
  isError
25
28
  } = reactQuery.useQuery({
26
29
  queryFn: () => sdk.admin.order.retrieve(order.id, {
27
- fields: "+invoices.*"
30
+ fields: "+invoices.*,+payment_collections.payments.refunds.*"
28
31
  }),
29
32
  queryKey: [order.id, "order_invoices"]
30
33
  });
@@ -41,7 +44,11 @@ const OrderInvoiceWidget = ({ data: order }) => {
41
44
  }
42
45
  });
43
46
  const downloadInvoice = reactQuery.useMutation({
44
- mutationFn: async ({ invoiceId, displayId, type }) => {
47
+ mutationFn: async ({
48
+ invoiceId,
49
+ displayId,
50
+ type
51
+ }) => {
45
52
  const response = await fetch(
46
53
  `/admin/orders/${order.id}/invoice/${invoiceId}`,
47
54
  { credentials: "include" }
@@ -63,54 +70,238 @@ const OrderInvoiceWidget = ({ data: order }) => {
63
70
  ui.toast.error("Failed to download invoice");
64
71
  }
65
72
  });
73
+ const generateInvoice = reactQuery.useMutation({
74
+ mutationFn: () => sdk.client.fetch(`/admin/orders/${order.id}/invoice`, {
75
+ method: "POST"
76
+ }),
77
+ onSuccess: (result) => {
78
+ ui.toast.success(`Invoice #${result == null ? void 0 : result.display_id} generated`);
79
+ queryClient.invalidateQueries({ queryKey: [order.id, "order_invoices"] });
80
+ },
81
+ onError: (error) => {
82
+ var _a2, _b;
83
+ ui.toast.error(
84
+ (error == null ? void 0 : error.message) ?? ((_b = (_a2 = error == null ? void 0 : error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b.message) ?? "Failed to generate invoice"
85
+ );
86
+ }
87
+ });
88
+ const generateCreditInvoice = reactQuery.useMutation({
89
+ mutationFn: (refundId) => sdk.client.fetch(`/admin/orders/${order.id}/credit-invoice`, {
90
+ method: "POST",
91
+ body: refundId ? { refund_id: refundId } : {}
92
+ }),
93
+ onSuccess: (result) => {
94
+ ui.toast.success(`Credit invoice #${result == null ? void 0 : result.display_id} generated`);
95
+ queryClient.invalidateQueries({ queryKey: [order.id, "order_invoices"] });
96
+ },
97
+ onError: (error) => {
98
+ var _a2, _b;
99
+ ui.toast.error(
100
+ (error == null ? void 0 : error.message) ?? ((_b = (_a2 = error == null ? void 0 : error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b.message) ?? "Failed to generate credit invoice"
101
+ );
102
+ }
103
+ });
104
+ const uploadInvoice = reactQuery.useMutation({
105
+ mutationFn: async ({
106
+ invoiceId,
107
+ file
108
+ }) => {
109
+ const formData = new FormData();
110
+ formData.append("file", file);
111
+ const headers = {};
112
+ try {
113
+ const token = await sdk.client.getToken();
114
+ if (token) {
115
+ headers.Authorization = `Bearer ${token}`;
116
+ }
117
+ } catch {
118
+ }
119
+ const response = await fetch(
120
+ `/admin/orders/${order.id}/invoice/${invoiceId}/upload`,
121
+ {
122
+ method: "POST",
123
+ body: formData,
124
+ credentials: "include",
125
+ headers
126
+ }
127
+ );
128
+ if (!response.ok) {
129
+ let message = "Failed to upload invoice PDF";
130
+ try {
131
+ const body = await response.json();
132
+ message = (body == null ? void 0 : body.message) ?? message;
133
+ } catch {
134
+ }
135
+ throw new Error(message);
136
+ }
137
+ return response.json();
138
+ },
139
+ onSuccess: () => {
140
+ ui.toast.success("Invoice PDF uploaded");
141
+ queryClient.invalidateQueries({ queryKey: [order.id, "order_invoices"] });
142
+ },
143
+ onError: (error) => {
144
+ ui.toast.error((error == null ? void 0 : error.message) ?? "Failed to upload invoice PDF");
145
+ }
146
+ });
66
147
  const orderWithInvoices = expandedOrder == null ? void 0 : expandedOrder.order;
67
- const orderHasInvoices = ((_a = orderWithInvoices == null ? void 0 : orderWithInvoices.invoices) == null ? void 0 : _a.length) > 0;
148
+ const orderHasInvoices = (((_a = orderWithInvoices == null ? void 0 : orderWithInvoices.invoices) == null ? void 0 : _a.length) ?? 0) > 0;
68
149
  const invoices = orderWithInvoices == null ? void 0 : orderWithInvoices.invoices;
69
- return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Container, { className: "divide-y p-0", children: [
70
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-between px-6 py-4", children: /* @__PURE__ */ jsxRuntime.jsx("div", { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Heading, { level: "h1", children: "Invoices" }) }) }),
71
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-ui-fg-subtle px-6 py-4", children: isLoading ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: "small", className: "text-ui-fg-muted", children: "Loading..." }) : isError ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: "small", className: "text-ui-fg-error", children: "Failed to load invoices" }) : orderHasInvoices ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-col gap-3", children: invoices == null ? void 0 : invoices.map((invoice) => {
72
- var _a2;
73
- return /* @__PURE__ */ jsxRuntime.jsxs(
74
- "div",
75
- {
76
- className: "flex items-center justify-between",
77
- children: [
78
- /* @__PURE__ */ jsxRuntime.jsxs(
79
- "button",
150
+ const hasDebitInvoice = (invoices == null ? void 0 : invoices.some((invoice) => invoice.type === "debit")) ?? false;
151
+ const refunds = ((orderWithInvoices == null ? void 0 : orderWithInvoices.payment_collections) ?? []).flatMap((pc) => pc.payments ?? []).flatMap((payment) => payment.refunds ?? []);
152
+ const formatAmount = (amount) => {
153
+ try {
154
+ const formatter = new Intl.NumberFormat(void 0, {
155
+ style: "currency",
156
+ currency: order.currency_code
157
+ });
158
+ const fractionDigits = formatter.resolvedOptions().maximumFractionDigits ?? 2;
159
+ return formatter.format(amount / Math.pow(10, fractionDigits));
160
+ } catch {
161
+ return (amount / 100).toFixed(2);
162
+ }
163
+ };
164
+ const openFilePicker = (invoiceId) => {
165
+ uploadTargetRef.current = invoiceId;
166
+ if (fileInputRef.current) {
167
+ fileInputRef.current.value = "";
168
+ fileInputRef.current.click();
169
+ }
170
+ };
171
+ const handleFileSelected = (event) => {
172
+ var _a2;
173
+ const file = (_a2 = event.target.files) == null ? void 0 : _a2[0];
174
+ const invoiceId = uploadTargetRef.current;
175
+ if (!file || !invoiceId) {
176
+ return;
177
+ }
178
+ if (file.type && file.type !== "application/pdf") {
179
+ ui.toast.error("Only PDF files are supported");
180
+ return;
181
+ }
182
+ uploadInvoice.mutate({ invoiceId, file });
183
+ };
184
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
185
+ /* @__PURE__ */ jsxRuntime.jsxs(ui.Container, { className: "divide-y p-0", children: [
186
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between gap-2 px-6 py-4", children: [
187
+ /* @__PURE__ */ jsxRuntime.jsx("div", { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Heading, { level: "h1", children: "Invoices" }) }),
188
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
189
+ /* @__PURE__ */ jsxRuntime.jsxs(
190
+ ui.Button,
191
+ {
192
+ size: "small",
193
+ variant: "secondary",
194
+ isLoading: generateInvoice.isPending,
195
+ disabled: hasDebitInvoice,
196
+ onClick: () => generateInvoice.mutate(),
197
+ children: [
198
+ /* @__PURE__ */ jsxRuntime.jsx(icons.DocumentText, {}),
199
+ "Generate invoice"
200
+ ]
201
+ }
202
+ ),
203
+ /* @__PURE__ */ jsxRuntime.jsxs(ui.DropdownMenu, { children: [
204
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenu.Trigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
205
+ ui.Button,
80
206
  {
81
- type: "button",
82
- className: "font-normal font-sans txt-compact-small text-ui-fg-subtle flex items-center gap-2 hover:text-ui-fg-base cursor-pointer bg-transparent border-none p-0",
83
- disabled: downloadInvoice.isPending && ((_a2 = downloadInvoice.variables) == null ? void 0 : _a2.invoiceId) === invoice.id,
84
- onClick: () => downloadInvoice.mutate({
85
- invoiceId: invoice.id,
86
- displayId: invoice.display_id,
87
- type: invoice.type
88
- }),
207
+ size: "small",
208
+ variant: "secondary",
209
+ isLoading: generateCreditInvoice.isPending,
210
+ disabled: !refunds.length,
89
211
  children: [
90
- /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowDownTray, {}),
91
- invoice.display_id,
92
- ".pdf",
93
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: `txt-xsmall px-1.5 py-0.5 rounded-base ${invoice.type === "credit" ? "bg-ui-green-10 text-ui-green-700" : "bg-ui-bg-subtle text-ui-fg-muted"}`, children: invoice.type })
212
+ /* @__PURE__ */ jsxRuntime.jsx(icons.ReceiptPercent, {}),
213
+ "Credit invoice"
94
214
  ]
95
215
  }
96
- ),
97
- /* @__PURE__ */ jsxRuntime.jsx(
98
- ui.IconButton,
216
+ ) }),
217
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenu.Content, { align: "end", children: refunds.map((refund) => /* @__PURE__ */ jsxRuntime.jsxs(
218
+ ui.DropdownMenu.Item,
99
219
  {
100
- size: "small",
101
- variant: "transparent",
102
- disabled: refreshInvoice.isPending && refreshInvoice.variables === invoice.id,
103
- onClick: () => refreshInvoice.mutate(invoice.id),
104
- "aria-label": "Regenerate invoice PDF",
105
- children: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowPath, {})
106
- }
107
- )
108
- ]
109
- },
110
- invoice.id
111
- );
112
- }) }) : /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: "small", className: "text-ui-fg-muted", children: "No invoices found" }) })
113
- ] }) });
220
+ onClick: () => generateCreditInvoice.mutate(refund.id),
221
+ children: [
222
+ formatAmount(refund.amount),
223
+ refund.note ? ` - ${refund.note}` : ""
224
+ ]
225
+ },
226
+ refund.id
227
+ )) })
228
+ ] })
229
+ ] })
230
+ ] }),
231
+ hasDebitInvoice || !refunds.length ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-6 py-4", children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: "small", className: "text-ui-fg-muted", children: hasDebitInvoice ? "This order already has an invoice. Upload a PDF to replace its document." : "A credit invoice is created from a refund. This order has no refunds yet." }) }) : null,
232
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-ui-fg-subtle px-6 py-4", children: isLoading ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: "small", className: "text-ui-fg-muted", children: "Loading..." }) : isError ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: "small", className: "text-ui-fg-error", children: "Failed to load invoices" }) : orderHasInvoices ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-col gap-3", children: invoices == null ? void 0 : invoices.map((invoice) => {
233
+ var _a2, _b;
234
+ return /* @__PURE__ */ jsxRuntime.jsxs(
235
+ "div",
236
+ {
237
+ className: "flex items-center justify-between",
238
+ children: [
239
+ /* @__PURE__ */ jsxRuntime.jsxs(
240
+ "button",
241
+ {
242
+ type: "button",
243
+ className: "font-normal font-sans txt-compact-small text-ui-fg-subtle flex items-center gap-2 hover:text-ui-fg-base cursor-pointer bg-transparent border-none p-0",
244
+ disabled: downloadInvoice.isPending && ((_a2 = downloadInvoice.variables) == null ? void 0 : _a2.invoiceId) === invoice.id,
245
+ onClick: () => downloadInvoice.mutate({
246
+ invoiceId: invoice.id,
247
+ displayId: invoice.display_id,
248
+ type: invoice.type
249
+ }),
250
+ children: [
251
+ /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowDownTray, {}),
252
+ invoice.display_id,
253
+ ".pdf",
254
+ /* @__PURE__ */ jsxRuntime.jsx(
255
+ "span",
256
+ {
257
+ className: `txt-xsmall px-1.5 py-0.5 rounded-base ${invoice.type === "credit" ? "bg-ui-green-10 text-ui-green-700" : "bg-ui-bg-subtle text-ui-fg-muted"}`,
258
+ children: invoice.type
259
+ }
260
+ )
261
+ ]
262
+ }
263
+ ),
264
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1", children: [
265
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Tooltip, { content: "Upload PDF", children: /* @__PURE__ */ jsxRuntime.jsx(
266
+ ui.IconButton,
267
+ {
268
+ size: "small",
269
+ variant: "transparent",
270
+ "aria-label": "Upload invoice PDF",
271
+ disabled: uploadInvoice.isPending && ((_b = uploadInvoice.variables) == null ? void 0 : _b.invoiceId) === invoice.id,
272
+ onClick: () => openFilePicker(invoice.id),
273
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowUpTray, {})
274
+ }
275
+ ) }),
276
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Tooltip, { content: "Regenerate invoice PDF", children: /* @__PURE__ */ jsxRuntime.jsx(
277
+ ui.IconButton,
278
+ {
279
+ size: "small",
280
+ variant: "transparent",
281
+ "aria-label": "Regenerate invoice PDF",
282
+ disabled: refreshInvoice.isPending && refreshInvoice.variables === invoice.id,
283
+ onClick: () => refreshInvoice.mutate(invoice.id),
284
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowPath, {})
285
+ }
286
+ ) })
287
+ ] })
288
+ ]
289
+ },
290
+ invoice.id
291
+ );
292
+ }) }) : /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: "small", className: "text-ui-fg-muted", children: "No invoices found" }) })
293
+ ] }),
294
+ /* @__PURE__ */ jsxRuntime.jsx(
295
+ "input",
296
+ {
297
+ ref: fileInputRef,
298
+ type: "file",
299
+ accept: "application/pdf,.pdf",
300
+ className: "hidden",
301
+ onChange: handleFileSelected
302
+ }
303
+ )
304
+ ] });
114
305
  };
115
306
  adminSdk.defineWidgetConfig({
116
307
  zone: "order.details.side.before"
@@ -1,9 +1,10 @@
1
- import { jsx, Fragment, jsxs } from "react/jsx-runtime";
2
- import { toast, Container, Heading, Text, IconButton } from "@medusajs/ui";
1
+ import { jsxs, Fragment, jsx } from "react/jsx-runtime";
2
+ import { useRef } from "react";
3
+ import { toast, Container, Heading, Button, DropdownMenu, Text, Tooltip, IconButton } from "@medusajs/ui";
3
4
  import { defineWidgetConfig } from "@medusajs/admin-sdk";
4
5
  import Medusa from "@medusajs/js-sdk";
5
6
  import { useQueryClient, useQuery, useMutation } from "@tanstack/react-query";
6
- import { ArrowDownTray, ArrowPath } from "@medusajs/icons";
7
+ import { DocumentText, ReceiptPercent, ArrowDownTray, ArrowUpTray, ArrowPath } from "@medusajs/icons";
7
8
  import "@medusajs/admin-shared";
8
9
  const sdk = new Medusa({
9
10
  baseUrl: __BACKEND_URL__,
@@ -15,13 +16,15 @@ const sdk = new Medusa({
15
16
  const OrderInvoiceWidget = ({ data: order }) => {
16
17
  var _a;
17
18
  const queryClient = useQueryClient();
19
+ const fileInputRef = useRef(null);
20
+ const uploadTargetRef = useRef(null);
18
21
  const {
19
22
  data: expandedOrder,
20
23
  isLoading,
21
24
  isError
22
25
  } = useQuery({
23
26
  queryFn: () => sdk.admin.order.retrieve(order.id, {
24
- fields: "+invoices.*"
27
+ fields: "+invoices.*,+payment_collections.payments.refunds.*"
25
28
  }),
26
29
  queryKey: [order.id, "order_invoices"]
27
30
  });
@@ -38,7 +41,11 @@ const OrderInvoiceWidget = ({ data: order }) => {
38
41
  }
39
42
  });
40
43
  const downloadInvoice = useMutation({
41
- mutationFn: async ({ invoiceId, displayId, type }) => {
44
+ mutationFn: async ({
45
+ invoiceId,
46
+ displayId,
47
+ type
48
+ }) => {
42
49
  const response = await fetch(
43
50
  `/admin/orders/${order.id}/invoice/${invoiceId}`,
44
51
  { credentials: "include" }
@@ -60,54 +67,238 @@ const OrderInvoiceWidget = ({ data: order }) => {
60
67
  toast.error("Failed to download invoice");
61
68
  }
62
69
  });
70
+ const generateInvoice = useMutation({
71
+ mutationFn: () => sdk.client.fetch(`/admin/orders/${order.id}/invoice`, {
72
+ method: "POST"
73
+ }),
74
+ onSuccess: (result) => {
75
+ toast.success(`Invoice #${result == null ? void 0 : result.display_id} generated`);
76
+ queryClient.invalidateQueries({ queryKey: [order.id, "order_invoices"] });
77
+ },
78
+ onError: (error) => {
79
+ var _a2, _b;
80
+ toast.error(
81
+ (error == null ? void 0 : error.message) ?? ((_b = (_a2 = error == null ? void 0 : error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b.message) ?? "Failed to generate invoice"
82
+ );
83
+ }
84
+ });
85
+ const generateCreditInvoice = useMutation({
86
+ mutationFn: (refundId) => sdk.client.fetch(`/admin/orders/${order.id}/credit-invoice`, {
87
+ method: "POST",
88
+ body: refundId ? { refund_id: refundId } : {}
89
+ }),
90
+ onSuccess: (result) => {
91
+ toast.success(`Credit invoice #${result == null ? void 0 : result.display_id} generated`);
92
+ queryClient.invalidateQueries({ queryKey: [order.id, "order_invoices"] });
93
+ },
94
+ onError: (error) => {
95
+ var _a2, _b;
96
+ toast.error(
97
+ (error == null ? void 0 : error.message) ?? ((_b = (_a2 = error == null ? void 0 : error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b.message) ?? "Failed to generate credit invoice"
98
+ );
99
+ }
100
+ });
101
+ const uploadInvoice = useMutation({
102
+ mutationFn: async ({
103
+ invoiceId,
104
+ file
105
+ }) => {
106
+ const formData = new FormData();
107
+ formData.append("file", file);
108
+ const headers = {};
109
+ try {
110
+ const token = await sdk.client.getToken();
111
+ if (token) {
112
+ headers.Authorization = `Bearer ${token}`;
113
+ }
114
+ } catch {
115
+ }
116
+ const response = await fetch(
117
+ `/admin/orders/${order.id}/invoice/${invoiceId}/upload`,
118
+ {
119
+ method: "POST",
120
+ body: formData,
121
+ credentials: "include",
122
+ headers
123
+ }
124
+ );
125
+ if (!response.ok) {
126
+ let message = "Failed to upload invoice PDF";
127
+ try {
128
+ const body = await response.json();
129
+ message = (body == null ? void 0 : body.message) ?? message;
130
+ } catch {
131
+ }
132
+ throw new Error(message);
133
+ }
134
+ return response.json();
135
+ },
136
+ onSuccess: () => {
137
+ toast.success("Invoice PDF uploaded");
138
+ queryClient.invalidateQueries({ queryKey: [order.id, "order_invoices"] });
139
+ },
140
+ onError: (error) => {
141
+ toast.error((error == null ? void 0 : error.message) ?? "Failed to upload invoice PDF");
142
+ }
143
+ });
63
144
  const orderWithInvoices = expandedOrder == null ? void 0 : expandedOrder.order;
64
- const orderHasInvoices = ((_a = orderWithInvoices == null ? void 0 : orderWithInvoices.invoices) == null ? void 0 : _a.length) > 0;
145
+ const orderHasInvoices = (((_a = orderWithInvoices == null ? void 0 : orderWithInvoices.invoices) == null ? void 0 : _a.length) ?? 0) > 0;
65
146
  const invoices = orderWithInvoices == null ? void 0 : orderWithInvoices.invoices;
66
- return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", children: [
67
- /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between px-6 py-4", children: /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Heading, { level: "h1", children: "Invoices" }) }) }),
68
- /* @__PURE__ */ jsx("div", { className: "text-ui-fg-subtle px-6 py-4", children: isLoading ? /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-muted", children: "Loading..." }) : isError ? /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-error", children: "Failed to load invoices" }) : orderHasInvoices ? /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-3", children: invoices == null ? void 0 : invoices.map((invoice) => {
69
- var _a2;
70
- return /* @__PURE__ */ jsxs(
71
- "div",
72
- {
73
- className: "flex items-center justify-between",
74
- children: [
75
- /* @__PURE__ */ jsxs(
76
- "button",
147
+ const hasDebitInvoice = (invoices == null ? void 0 : invoices.some((invoice) => invoice.type === "debit")) ?? false;
148
+ const refunds = ((orderWithInvoices == null ? void 0 : orderWithInvoices.payment_collections) ?? []).flatMap((pc) => pc.payments ?? []).flatMap((payment) => payment.refunds ?? []);
149
+ const formatAmount = (amount) => {
150
+ try {
151
+ const formatter = new Intl.NumberFormat(void 0, {
152
+ style: "currency",
153
+ currency: order.currency_code
154
+ });
155
+ const fractionDigits = formatter.resolvedOptions().maximumFractionDigits ?? 2;
156
+ return formatter.format(amount / Math.pow(10, fractionDigits));
157
+ } catch {
158
+ return (amount / 100).toFixed(2);
159
+ }
160
+ };
161
+ const openFilePicker = (invoiceId) => {
162
+ uploadTargetRef.current = invoiceId;
163
+ if (fileInputRef.current) {
164
+ fileInputRef.current.value = "";
165
+ fileInputRef.current.click();
166
+ }
167
+ };
168
+ const handleFileSelected = (event) => {
169
+ var _a2;
170
+ const file = (_a2 = event.target.files) == null ? void 0 : _a2[0];
171
+ const invoiceId = uploadTargetRef.current;
172
+ if (!file || !invoiceId) {
173
+ return;
174
+ }
175
+ if (file.type && file.type !== "application/pdf") {
176
+ toast.error("Only PDF files are supported");
177
+ return;
178
+ }
179
+ uploadInvoice.mutate({ invoiceId, file });
180
+ };
181
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
182
+ /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", children: [
183
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2 px-6 py-4", children: [
184
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Heading, { level: "h1", children: "Invoices" }) }),
185
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
186
+ /* @__PURE__ */ jsxs(
187
+ Button,
188
+ {
189
+ size: "small",
190
+ variant: "secondary",
191
+ isLoading: generateInvoice.isPending,
192
+ disabled: hasDebitInvoice,
193
+ onClick: () => generateInvoice.mutate(),
194
+ children: [
195
+ /* @__PURE__ */ jsx(DocumentText, {}),
196
+ "Generate invoice"
197
+ ]
198
+ }
199
+ ),
200
+ /* @__PURE__ */ jsxs(DropdownMenu, { children: [
201
+ /* @__PURE__ */ jsx(DropdownMenu.Trigger, { asChild: true, children: /* @__PURE__ */ jsxs(
202
+ Button,
77
203
  {
78
- type: "button",
79
- className: "font-normal font-sans txt-compact-small text-ui-fg-subtle flex items-center gap-2 hover:text-ui-fg-base cursor-pointer bg-transparent border-none p-0",
80
- disabled: downloadInvoice.isPending && ((_a2 = downloadInvoice.variables) == null ? void 0 : _a2.invoiceId) === invoice.id,
81
- onClick: () => downloadInvoice.mutate({
82
- invoiceId: invoice.id,
83
- displayId: invoice.display_id,
84
- type: invoice.type
85
- }),
204
+ size: "small",
205
+ variant: "secondary",
206
+ isLoading: generateCreditInvoice.isPending,
207
+ disabled: !refunds.length,
86
208
  children: [
87
- /* @__PURE__ */ jsx(ArrowDownTray, {}),
88
- invoice.display_id,
89
- ".pdf",
90
- /* @__PURE__ */ jsx("span", { className: `txt-xsmall px-1.5 py-0.5 rounded-base ${invoice.type === "credit" ? "bg-ui-green-10 text-ui-green-700" : "bg-ui-bg-subtle text-ui-fg-muted"}`, children: invoice.type })
209
+ /* @__PURE__ */ jsx(ReceiptPercent, {}),
210
+ "Credit invoice"
91
211
  ]
92
212
  }
93
- ),
94
- /* @__PURE__ */ jsx(
95
- IconButton,
213
+ ) }),
214
+ /* @__PURE__ */ jsx(DropdownMenu.Content, { align: "end", children: refunds.map((refund) => /* @__PURE__ */ jsxs(
215
+ DropdownMenu.Item,
96
216
  {
97
- size: "small",
98
- variant: "transparent",
99
- disabled: refreshInvoice.isPending && refreshInvoice.variables === invoice.id,
100
- onClick: () => refreshInvoice.mutate(invoice.id),
101
- "aria-label": "Regenerate invoice PDF",
102
- children: /* @__PURE__ */ jsx(ArrowPath, {})
103
- }
104
- )
105
- ]
106
- },
107
- invoice.id
108
- );
109
- }) }) : /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-muted", children: "No invoices found" }) })
110
- ] }) });
217
+ onClick: () => generateCreditInvoice.mutate(refund.id),
218
+ children: [
219
+ formatAmount(refund.amount),
220
+ refund.note ? ` - ${refund.note}` : ""
221
+ ]
222
+ },
223
+ refund.id
224
+ )) })
225
+ ] })
226
+ ] })
227
+ ] }),
228
+ hasDebitInvoice || !refunds.length ? /* @__PURE__ */ jsx("div", { className: "px-6 py-4", children: /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-muted", children: hasDebitInvoice ? "This order already has an invoice. Upload a PDF to replace its document." : "A credit invoice is created from a refund. This order has no refunds yet." }) }) : null,
229
+ /* @__PURE__ */ jsx("div", { className: "text-ui-fg-subtle px-6 py-4", children: isLoading ? /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-muted", children: "Loading..." }) : isError ? /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-error", children: "Failed to load invoices" }) : orderHasInvoices ? /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-3", children: invoices == null ? void 0 : invoices.map((invoice) => {
230
+ var _a2, _b;
231
+ return /* @__PURE__ */ jsxs(
232
+ "div",
233
+ {
234
+ className: "flex items-center justify-between",
235
+ children: [
236
+ /* @__PURE__ */ jsxs(
237
+ "button",
238
+ {
239
+ type: "button",
240
+ className: "font-normal font-sans txt-compact-small text-ui-fg-subtle flex items-center gap-2 hover:text-ui-fg-base cursor-pointer bg-transparent border-none p-0",
241
+ disabled: downloadInvoice.isPending && ((_a2 = downloadInvoice.variables) == null ? void 0 : _a2.invoiceId) === invoice.id,
242
+ onClick: () => downloadInvoice.mutate({
243
+ invoiceId: invoice.id,
244
+ displayId: invoice.display_id,
245
+ type: invoice.type
246
+ }),
247
+ children: [
248
+ /* @__PURE__ */ jsx(ArrowDownTray, {}),
249
+ invoice.display_id,
250
+ ".pdf",
251
+ /* @__PURE__ */ jsx(
252
+ "span",
253
+ {
254
+ className: `txt-xsmall px-1.5 py-0.5 rounded-base ${invoice.type === "credit" ? "bg-ui-green-10 text-ui-green-700" : "bg-ui-bg-subtle text-ui-fg-muted"}`,
255
+ children: invoice.type
256
+ }
257
+ )
258
+ ]
259
+ }
260
+ ),
261
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
262
+ /* @__PURE__ */ jsx(Tooltip, { content: "Upload PDF", children: /* @__PURE__ */ jsx(
263
+ IconButton,
264
+ {
265
+ size: "small",
266
+ variant: "transparent",
267
+ "aria-label": "Upload invoice PDF",
268
+ disabled: uploadInvoice.isPending && ((_b = uploadInvoice.variables) == null ? void 0 : _b.invoiceId) === invoice.id,
269
+ onClick: () => openFilePicker(invoice.id),
270
+ children: /* @__PURE__ */ jsx(ArrowUpTray, {})
271
+ }
272
+ ) }),
273
+ /* @__PURE__ */ jsx(Tooltip, { content: "Regenerate invoice PDF", children: /* @__PURE__ */ jsx(
274
+ IconButton,
275
+ {
276
+ size: "small",
277
+ variant: "transparent",
278
+ "aria-label": "Regenerate invoice PDF",
279
+ disabled: refreshInvoice.isPending && refreshInvoice.variables === invoice.id,
280
+ onClick: () => refreshInvoice.mutate(invoice.id),
281
+ children: /* @__PURE__ */ jsx(ArrowPath, {})
282
+ }
283
+ ) })
284
+ ] })
285
+ ]
286
+ },
287
+ invoice.id
288
+ );
289
+ }) }) : /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-muted", children: "No invoices found" }) })
290
+ ] }),
291
+ /* @__PURE__ */ jsx(
292
+ "input",
293
+ {
294
+ ref: fileInputRef,
295
+ type: "file",
296
+ accept: "application/pdf,.pdf",
297
+ className: "hidden",
298
+ onChange: handleFileSelected
299
+ }
300
+ )
301
+ ] });
111
302
  };
112
303
  defineWidgetConfig({
113
304
  zone: "order.details.side.before"