summaryrefslogtreecommitdiff
path: root/packages/merchant-backoffice-ui/src/paths/instance/orders/list/Table.tsx
blob: 5ece34409daa71045b1cf902dc92a1d263270bb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
 This file is part of GNU Taler
 (C) 2021-2024 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 *
 * @author Sebastian Javier Marchano (sebasjm)
 */

import { Amounts, TalerMerchantApi } from "@gnu-taler/taler-util";
import {
  useTranslationContext
} from "@gnu-taler/web-util/browser";
import { format } from "date-fns";
import { VNode, h } from "preact";
import { StateUpdater, useState } from "preact/hooks";
import {
  FormErrors,
  FormProvider,
} from "../../../../components/form/FormProvider.js";
import { Input } from "../../../../components/form/Input.js";
import { InputCurrency } from "../../../../components/form/InputCurrency.js";
import { InputGroup } from "../../../../components/form/InputGroup.js";
import { InputSelector } from "../../../../components/form/InputSelector.js";
import { ConfirmModal } from "../../../../components/modal/index.js";
import { useSessionContext } from "../../../../context/session.js";
import {
  datetimeFormatForSettings,
  usePreference,
} from "../../../../hooks/preference.js";
import { mergeRefunds } from "../../../../utils/amount.js";

type Entity = TalerMerchantApi.OrderHistoryEntry & WithId;
interface Props {
  orders: Entity[];
  onRefund: (value: Entity) => void;
  onCopyURL: (id: string) => void;
  onCreate: () => void;
  onSelect: (order: Entity) => void;
  onLoadMoreBefore?: () => void;
  onLoadMoreAfter?: () => void;
}

export function CardTable({
  orders,
  onCreate,
  onRefund,
  onCopyURL,
  onSelect,
  onLoadMoreAfter,
  onLoadMoreBefore,
}: Props): VNode {
  const [rowSelection, rowSelectionHandler] = useState<string[]>([]);

  const { i18n } = useTranslationContext();

  return (
    <div class="card has-table">
      <header class="card-header">
        <p class="card-header-title">
          <span class="icon">
            <i class="mdi mdi-cash-register" />
          </span>
          <i18n.Translate>Orders</i18n.Translate>
        </p>

        <div class="card-header-icon" aria-label="more options" />

        <div class="card-header-icon" aria-label="more options">
          <span class="has-tooltip-left" data-tooltip={i18n.str`create order`}>
            <button class="button is-info" type="button" onClick={onCreate}>
              <span class="icon is-small">
                <i class="mdi mdi-plus mdi-36px" />
              </span>
            </button>
          </span>
        </div>
      </header>
      <div class="card-content">
        <div class="b-table has-pagination">
          <div class="table-wrapper has-mobile-cards">
            {orders.length > 0 ? (
              <Table
                instances={orders}
                onSelect={onSelect}
                onRefund={onRefund}
                onCopyURL={(o) => onCopyURL(o.id)}
                rowSelection={rowSelection}
                rowSelectionHandler={rowSelectionHandler}
                onLoadMoreAfter={onLoadMoreAfter}
                onLoadMoreBefore={onLoadMoreBefore}
              />
            ) : (
              <EmptyTable />
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
interface TableProps {
  rowSelection: string[];
  instances: Entity[];
  onRefund: (id: Entity) => void;
  onCopyURL: (id: Entity) => void;
  onSelect: (id: Entity) => void;
  rowSelectionHandler: StateUpdater<string[]>;
  onLoadMoreBefore?: () => void;
  onLoadMoreAfter?: () => void;
}

function Table({
  instances,
  onSelect,
  onRefund,
  onCopyURL,
  onLoadMoreAfter,
  onLoadMoreBefore,
}: TableProps): VNode {
  const { i18n } = useTranslationContext();
  const [settings] = usePreference();
  return (
    <div class="table-container">
      {onLoadMoreBefore && (
        <button class="button is-fullwidth" onClick={onLoadMoreBefore}>
          <i18n.Translate>load first page</i18n.Translate>
        </button>
      )}
      <table class="table is-striped is-hoverable is-fullwidth">
        <thead>
          <tr>
            <th style={{ minWidth: 100 }}>
              <i18n.Translate>Date</i18n.Translate>
            </th>
            <th style={{ minWidth: 100 }}>
              <i18n.Translate>Amount</i18n.Translate>
            </th>
            <th style={{ minWidth: 400 }}>
              <i18n.Translate>Summary</i18n.Translate>
            </th>
            <th style={{ minWidth: 50 }} />
          </tr>
        </thead>
        <tbody>
          {instances.map((i) => {
            return (
              <tr key={i.id}>
                <td
                  onClick={(): void => onSelect(i)}
                  style={{ cursor: "pointer" }}
                >
                  {i.timestamp.t_s === "never"
                    ? "never"
                    : format(
                        new Date(i.timestamp.t_s * 1000),
                        datetimeFormatForSettings(settings),
                      )}
                </td>
                <td
                  onClick={(): void => onSelect(i)}
                  style={{ cursor: "pointer" }}
                >
                  {i.amount}
                </td>
                <td
                  onClick={(): void => onSelect(i)}
                  style={{ cursor: "pointer" }}
                >
                  {i.summary}
                </td>
                <td class="is-actions-cell right-sticky">
                  <div class="buttons is-right">
                    {i.refundable && (
                      <button
                        class="button is-small is-danger jb-modal"
                        type="button"
                        onClick={(): void => onRefund(i)}
                      >
                        <i18n.Translate>Refund</i18n.Translate>
                      </button>
                    )}
                    {!i.paid && (
                      <button
                        class="button is-small is-info jb-modal"
                        type="button"
                        onClick={(): void => onCopyURL(i)}
                      >
                        <i18n.Translate>copy url</i18n.Translate>
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      {onLoadMoreAfter && (
        <button class="button is-fullwidth" 
        data-tooltip={i18n.str`load more orders after the last one`}
        onClick={onLoadMoreAfter}>
          <i18n.Translate>load next page</i18n.Translate>
        </button>
      )}
    </div>
  );
}

function EmptyTable(): VNode {
  const { i18n } = useTranslationContext();
  return (
    <div class="content has-text-grey has-text-centered">
      <p>
        <span class="icon is-large">
          <i class="mdi mdi-magnify mdi-48px" />
        </span>
      </p>
      <p>
        <i18n.Translate>
          No orders have been found matching your query!
        </i18n.Translate>
      </p>
    </div>
  );
}

interface RefundModalProps {
  onCancel: () => void;
  onConfirm: (value: TalerMerchantApi.RefundRequest) => void;
  order: TalerMerchantApi.MerchantOrderStatusResponse;
}

export function RefundModal({
  order,
  onCancel,
  onConfirm,
}: RefundModalProps): VNode {
  type State = { mainReason?: string; description?: string; refund?: string };
  const [form, setValue] = useState<State>({});
  const [settings] = usePreference();
  const { i18n } = useTranslationContext();
  // const [errors, setErrors] = useState<FormErrors<State>>({});

  const refunds = (
    order.order_status === "paid" ? order.refund_details : []
  ).reduce(mergeRefunds, []);

  const { config } = useSessionContext();
  const totalRefunded = refunds
    .map((r) => r.amount)
    .reduce(
      (p, c) => Amounts.add(p, Amounts.parseOrThrow(c)).amount,
      Amounts.zeroOfCurrency(config.currency),
    );
  const orderPrice =
    order.order_status === "paid"
      ? Amounts.parseOrThrow(order.contract_terms.amount)
      : undefined;
  const totalRefundable = !orderPrice
    ? Amounts.zeroOfCurrency(totalRefunded.currency)
    : refunds.length
      ? Amounts.sub(orderPrice, totalRefunded).amount
      : orderPrice;

  const isRefundable = Amounts.isNonZero(totalRefundable);
  const duplicatedText = i18n.str`duplicated`;

  const errors: FormErrors<State> = {
    mainReason: !form.mainReason ? i18n.str`required` : undefined,
    description:
      !form.description && form.mainReason !== duplicatedText
        ? i18n.str`required`
        : undefined,
    refund: !form.refund
      ? i18n.str`required`
      : !Amounts.parse(form.refund)
        ? i18n.str`invalid format`
        : Amounts.cmp(totalRefundable, Amounts.parse(form.refund)!) === -1
          ? i18n.str`this value exceed the refundable amount`
          : undefined,
  };
  const hasErrors = Object.keys(errors).some(
    (k) => (errors as Record<string, unknown>)[k] !== undefined,
  );

  const validateAndConfirm = () => {
    try {
      if (!form.refund) return;
      onConfirm({
        refund: Amounts.stringify(
          Amounts.add(Amounts.parse(form.refund)!, totalRefunded).amount,
        ),
        reason:
          form.description === undefined
            ? form.mainReason || ""
            : `${form.mainReason}: ${form.description}`,
      });
    } catch (err) {
      console.log(err);
    }
  };

  //FIXME: parameters in the translation
  return (
    <ConfirmModal
      description="refund"
      danger
      active
      disabled={!isRefundable || hasErrors}
      onCancel={onCancel}
      onConfirm={validateAndConfirm}
    >
      {refunds.length > 0 && (
        <div class="columns">
          <div class="column is-12">
            <InputGroup
              name="asd"
              label={`${Amounts.stringify(totalRefunded)} was already refunded`}
            >
              <table class="table is-fullwidth">
                <thead>
                  <tr>
                    <th>
                      <i18n.Translate>date</i18n.Translate>
                    </th>
                    <th>
                      <i18n.Translate>amount</i18n.Translate>
                    </th>
                    <th>
                      <i18n.Translate>reason</i18n.Translate>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {refunds.map((r) => {
                    return (
                      <tr key={r.timestamp.t_s}>
                        <td>
                          {r.timestamp.t_s === "never"
                            ? "never"
                            : format(
                                new Date(r.timestamp.t_s * 1000),
                                datetimeFormatForSettings(settings),
                              )}
                        </td>
                        <td>{r.amount}</td>
                        <td>{r.reason}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </InputGroup>
          </div>
        </div>
      )}

      {isRefundable && (
        <FormProvider<State>
          errors={errors}
          object={form}
          valueHandler={(d) => setValue(d)}
        >
          <InputCurrency<State>
            name="refund"
            label={i18n.str`Refund`}
            tooltip={i18n.str`amount to be refunded`}
          >
            <i18n.Translate>Max refundable:</i18n.Translate>{" "}
            {Amounts.stringify(totalRefundable)}
          </InputCurrency>
          <InputSelector
            name="mainReason"
            label={i18n.str`Reason`}
            values={[
              i18n.str`Choose one...`,
              duplicatedText,
              i18n.str`requested by the customer`,
              i18n.str`other`,
            ]}
            tooltip={i18n.str`why this order is being refunded`}
          />
          {form.mainReason && form.mainReason !== duplicatedText ? (
            <Input<State>
              label={i18n.str`Description`}
              name="description"
              tooltip={i18n.str`more information to give context`}
            />
          ) : undefined}
        </FormProvider>
      )}
    </ConfirmModal>
  );
}