summaryrefslogtreecommitdiff
path: root/src/lib/transaction/components/Transactions.jsx
blob: a8685105500573f5f30f5ded8266facc9f722dea (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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import { toast } from 'react-hot-toast';
import {
  EllipsisVerticalIcon,
  MagnifyingGlassIcon,
  ChevronDownIcon,
  ChevronUpIcon,
} from '@heroicons/react/24/outline';
import useAuth from '@/core/hooks/useAuth';
import {
  downloadPurchaseOrder,
  downloadQuotation,
} from '../utils/transactions';
import useTransactions from '../hooks/useTransactions';
import currencyFormat from '@/core/utils/currencyFormat';
import cancelTransactionApi from '../api/cancelTransactionApi';
import TransactionStatusBadge from './TransactionStatusBadge';
import Spinner from '@/core/components/elements/Spinner/Spinner';
import Link from '@/core/components/elements/Link/Link';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import Pagination from '@/core/components/elements/Pagination/Pagination';
import { toQuery } from 'lodash-contrib';
import _ from 'lodash';
import Alert from '@/core/components/elements/Alert/Alert';
import MobileView from '@/core/components/views/MobileView';
import DesktopView from '@/core/components/views/DesktopView';
import Menu from '@/lib/auth/components/Menu';
import * as XLSX from 'xlsx';
import getSite from '../api/listSiteApi';
import transactionsApi from '../api/transactionsApi';
import { motion } from 'framer-motion';
import Image from '@/core/components/elements/Image/Image';
const Transactions = ({ context = '' }) => {
  const auth = useAuth();
  const router = useRouter();
  const { q = '', page = 1, site = null, limit = 15 } = router.query;

  const [inputQuery, setInputQuery] = useState(q);
  const [toOthers, setToOthers] = useState(null);
  const [toCancel, setToCancel] = useState(null);
  const [listSites, setListSites] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [siteFilter, setSiteFilter] = useState(site);
  const [pageNew, setPageNew] = useState(page);
  const [limitNew, setLimitNew] = useState(limit);
  const query = {
    name: q,
    offset: (pageNew - 1) * limitNew,
    context,
    limit: limitNew,
    site:
      siteFilter || (auth?.webRole === null && auth?.site ? auth.site : null),
  };
  const { transactions } = useTransactions({ query });
  console.log('transactions', transactions);
  const fetchSite = async () => {
    const site = await getSite();
    setListSites(site.sites);
  };

  const submitCancelTransaction = async () => {
    const isCancelled = await cancelTransactionApi({
      transaction: toCancel,
    });
    if (isCancelled) {
      toast.success('Berhasil batalkan transaksi');
      transactions.refetch();
    }
    setToCancel(null);
  };

  const pageCount = Math.ceil(transactions?.data?.saleOrderTotal / limitNew);
  let pageQuery = _.omit(query, ['limit', 'offset', 'context']);
  pageQuery = _.pickBy(
    pageQuery,
    (value, key) => value !== '' && !(key === 'page' && value === '1')
  );
  pageQuery = toQuery(pageQuery);

  const handleSubmit = (e) => {
    e.preventDefault();
    const queryParams = {};
    if (inputQuery) queryParams.q = inputQuery;
    if (siteFilter) queryParams.site = siteFilter;
    router.push({
      pathname: router.pathname,
      query: queryParams,
    });
  };

  const handleSiteFilterChange = (e) => {
    setSiteFilter(e.target.value);
    const queryParams = {};
    if (inputQuery) queryParams.q = inputQuery;
    if (e.target.value) queryParams.site = e.target.value;
    router.push({
      pathname: router.pathname,
      query: queryParams,
    });
  };

  const exportToExcel = (data, siteFilter) => {
    const fieldsToExport = [
      'No. Transaksi',
      'No. PO',
      'Tanggal',
      'Created By',
      'Salesperson',
      'Total',
      'Status',
    ];
    const rowsToExport = [];

    data.forEach((saleOrder) => {
      const row = {
        'No. Transaksi': saleOrder.name,
        'No. PO': saleOrder.purchaseOrderName || '-',
        Tanggal: saleOrder.dateOrder || '-',
        'Created By': saleOrder.address.customer?.name || '-',
        Salesperson: saleOrder.sales,
        Total: currencyFormat(saleOrder.amountTotal),
        Status: saleOrder.status,
      };
      if (siteFilter) {
        row['Site'] = siteFilter;
      }
      rowsToExport.push(row);
    });

    const worksheet = XLSX.utils.json_to_sheet(rowsToExport, {
      header: fieldsToExport,
    });

    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'transactions.xlsx');
  };

  const handleExportCSV = async () => {
    const dataToExport = await getAllData();

    exportToCSV(dataToExport?.saleOrders, siteFilter);
  };

  const exportToCSV = (data, siteFilter) => {
    const fieldsToExport = [
      'No. Transaksi',
      'No. PO',
      'Tanggal',
      'Created By',
      'Salesperson',
      'Total',
      'Status',
    ];

    if (siteFilter) {
      fieldsToExport.push('Site');
    }

    const rowsToExport = data.map((saleOrder) => {
      const row = [
        saleOrder.name,
        saleOrder.purchaseOrderName || '-',
        saleOrder.dateOrder || '-',
        saleOrder.address.customer?.name || '-',
        saleOrder.sales,
        currencyFormat(saleOrder.amountTotal),
        saleOrder.status,
      ];

      if (siteFilter) {
        row.push(siteFilter);
      }

      return row.join(',');
    });

    const csvContent =
      'data:text/csv;charset=utf-8,' +
      [fieldsToExport.join(','), ...rowsToExport].join('\n');

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', 'transactions.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const getAllData = async () => {
    const query = {
      name: q,
      context,
      site:
        siteFilter || (auth?.webRole === null && auth?.site ? auth.site : null),
    };
    const queryString = toQuery(query);
    const data = await transactionsApi({ query: queryString });
    return data;
  };

  const handleExportExcel = async () => {
    const dataToExport = await getAllData();

    exportToExcel(dataToExport?.saleOrders, siteFilter);
  };

  const handleDownload = (format) => {
    handleExport(format);
    setIsOpen(false);
  };

  const handleExport = (format) => {
    if (format === 'csv') {
      handleExportCSV();
    } else if (format === 'xlsx') {
      handleExportExcel();
    }
  };

  const startItem = 1 + (pageNew - 1) * limitNew;
  const endItem = Math.min(
    limitNew * pageNew,
    transactions?.data?.saleOrderTotal
  );

  useEffect(() => {
    fetchSite();
  }, []);
  return (
    <>
      <MobileView>
        <div className='p-4 flex flex-col gap-y-4'>
          <form className='flex gap-x-3' onSubmit={handleSubmit}>
            <input
              type='text'
              className='form-input'
              placeholder='Cari Transaksi...'
              value={inputQuery}
              onChange={(e) => setInputQuery(e.target.value)}
            />
            <button className='btn-light bg-transparent px-3' type='submit'>
              <MagnifyingGlassIcon className='w-6' />
            </button>
          </form>

          {transactions.isLoading && (
            <div className='flex justify-center my-4'>
              <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
            </div>
          )}

          {!transactions.isLoading &&
            transactions.data?.saleOrders?.length === 0 && (
              <Alert type='info' className='text-center'>
                Tidak ada transaksi
              </Alert>
            )}

          {transactions.data?.saleOrders?.map((saleOrder, index) => (
            <div
              className='p-4 shadow border border-gray_r-3 rounded-md'
              key={index}
            >
              <div className='grid grid-cols-2'>
                <Link href={`${router.pathname}/${saleOrder.id}`}>
                  <span className='text-caption-2 text-gray_r-11'>
                    No. Transaksi
                  </span>
                  <h2 className='text-danger-500 mt-1'>{saleOrder.name}</h2>
                </Link>
                <div className='flex gap-x-1 justify-end'>
                  <TransactionStatusBadge status={saleOrder.status} />
                  <EllipsisVerticalIcon
                    className='w-5 h-5'
                    onClick={() => setToOthers(saleOrder)}
                  />
                </div>
              </div>
              <Link href={`${router.pathname}/${saleOrder.id}`}>
                <div className='grid grid-cols-2 mt-3'>
                  <div>
                    <span className='text-caption-2 text-gray_r-11'>
                      No. Purchase Order
                    </span>
                    <p className='mt-1 font-medium text-gray_r-12'>
                      {saleOrder.purchaseOrderName || '-'}
                    </p>
                  </div>
                  <div className='text-right'>
                    <span className='text-caption-2 text-gray_r-11'>
                      Total Invoice
                    </span>
                    <p className='mt-1 font-medium text-gray_r-12'>
                      {saleOrder.invoiceCount} Invoice
                    </p>
                  </div>
                </div>
                <div className='grid grid-cols-2 mt-3'>
                  <div>
                    <span className='text-caption-2 text-gray_r-11'>Sales</span>
                    <p className='mt-1 font-medium text-gray_r-12'>
                      {saleOrder.sales}
                    </p>
                  </div>
                  <div className='text-right'>
                    <span className='text-caption-2 text-gray_r-11'>
                      Total Harga
                    </span>
                    <p className='mt-1 font-medium text-gray_r-12'>
                      {currencyFormat(saleOrder.amountTotal)}
                    </p>
                  </div>
                </div>
              </Link>
            </div>
          ))}

          <Pagination
            pageCount={pageCount}
            currentPage={parseInt(page)}
            url={router.pathname + pageQuery}
            className='mt-2 mb-2'
          />

          <BottomPopup
            title='Lainnya'
            active={toOthers}
            close={() => setToOthers(null)}
          >
            <div className='flex flex-col gap-y-4 mt-2'>
              <button
                className='text-left disabled:opacity-60'
                disabled={!toOthers?.purchaseOrderFile}
                onClick={() => {
                  downloadPurchaseOrder(toOthers);
                  setToOthers(null);
                }}
              >
                Download PO
              </button>
              <button
                className='text-left disabled:opacity-60'
                disabled={toOthers?.status != 'draft'}
                onClick={() => {
                  downloadQuotation(toOthers);
                  setToOthers(null);
                }}
              >
                Download Quotation
              </button>
              <button
                className='text-left disabled:opacity-60'
                disabled={toOthers?.status != 'waiting'}
                onClick={() => {
                  setToCancel(toOthers);
                  setToOthers(null);
                }}
              >
                Batalkan Transaksi
              </button>
            </div>
          </BottomPopup>

          <BottomPopup
            active={toCancel}
            close={() => setToCancel(null)}
            title='Batalkan Transaksi'
          >
            <div className='leading-7 text-gray_r-12/80'>
              Apakah anda yakin membatalkan transaksi{' '}
              <span className='underline'>{toCancel?.name}</span>?
            </div>
            <div className='flex mt-6 gap-x-4'>
              <button
                className='btn-solid-red flex-1'
                type='button'
                onClick={submitCancelTransaction}
              >
                Ya, Batalkan
              </button>
              <button
                className='btn-light flex-1'
                type='button'
                onClick={() => setToCancel(null)}
              >
                Batal
              </button>
            </div>
          </BottomPopup>
        </div>
      </MobileView>

      <DesktopView>
        <div className='container mx-auto flex py-10'>
          <div className='w-3/12 pr-4'>
            <Menu />
          </div>
          <div className='w-9/12 p-4 bg-white border border-gray_r-6 rounded'>
            <div className='flex mb-6 items-center justify-between '>
              <h1 className='text-title-sm font-semibold'>
                Daftar Transaksi{' '}
                {transactions?.data?.saleOrders
                  ? `(${transactions?.data?.saleOrderTotal})`
                  : ''}
              </h1>
              <div className='relative inline-block text-left'>
                <button
                  onClick={() => setIsOpen(!isOpen)}
                  type='button'
                  className='btn-light bg-slate-50 mt-3 w-full gap-2 items-center flex flex-row !text-gray_r-11 px-4 py-3 mb-2'
                >
                  <p>Export</p>
                  <motion.div
                    animate={{ rotate: isOpen ? 180 : 0 }}
                    transition={{ duration: 0.2, ease: 'easeInOut' }}
                  >
                    <ChevronDownIcon className='w-5' />
                  </motion.div>
                </button>

                {isOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.2, ease: 'easeInOut' }}
                    className='absolute mt-2 w-fit py-1 bg-white border border-gray-300 rounded-md shadow-lg'
                  >
                    <button
                      onClick={() => handleDownload('csv')}
                      className='block w-full px-4 py-2 text-left hover:bg-gray-200 text-nowrap'
                    >
                      Download CSV
                    </button>
                    <button
                      onClick={() => handleDownload('xlsx')}
                      className='block w-full px-4 py-2 text-left hover:bg-gray-200 text-nowrap'
                    >
                      Download XLSX
                    </button>
                  </motion.div>
                )}
              </div>
            </div>
            <div className='flex flex-row items-center justify-between mb-2'>
              <div className='flex flex-col gap-2 pb-2'>
                {listSites?.length > 0 ? (
                  <select
                    value={siteFilter}
                    onChange={handleSiteFilterChange}
                    className='form-input'
                  >
                    <option value=''>Pilih Site</option>
                    {listSites.map((site) => (
                      <option value={site} key={site}>
                        {site}
                      </option>
                    ))}
                  </select>
                ) : (
                  <div></div>
                )}

                <form className='flex gap-x-1' onSubmit={handleSubmit}>
                  <input
                    type='text'
                    className='form-input'
                    placeholder='Cari Transaksi...'
                    value={inputQuery}
                    onChange={(e) => setInputQuery(e.target.value)}
                  />
                  <button
                    className='btn-light bg-transparent px-3'
                    type='submit'
                  >
                    <MagnifyingGlassIcon className='w-6' />
                  </button>
                </form>
              </div>
              <div className='flex flex-row gap-4 items-center justify-center'>
                <p>
                  Menampilkan {startItem}-
                  {endItem ? endItem : transactions?.data?.saleOrderTotal} dari{' '}
                  {transactions?.data?.saleOrderTotal}
                </p>
                <select
                  id='limitSelect'
                  value={limitNew}
                  onChange={(e) => {
                    setLimitNew(Number(e.target.value));
                    setPageNew(1);
                  }}
                  className='border p-2'
                >
                  <option value={10}>10</option>
                  <option value={15}>15</option>
                  <option value={20}>20</option>
                </select>
              </div>
            </div>
            <div className='flex'>
              {!transactions.isLoading &&
                (!transactions?.data?.saleOrders ||
                  transactions?.data?.saleOrders?.length == 0) && (
                  <div className='justify-center p-4'>
                    <p className='text-gray-500 text-center '>
                      Tidak Ada Transaksi
                    </p>
                  </div>
                )}

              {transactions && transactions.data?.saleOrders?.length > 0 && (
                <div className='flex flex-col gap-4 w-full'>
                  {transactions.data.saleOrders.map((saleOrder, index) => (
                    <div
                      key={index}
                      className='border p-2 hover:border-red-500 w-full rounded-sm'
                    >
                      {/* <Link
                        href={`/my/quotations/${saleOrder?.id}`}
                        className='hover:border-red-500 block w-full'
                      > */}
                      <div className='flex flex-row justify-between items-center py-2'>
                        <div className='flex justify-center gap-3'>
                          <TransactionStatusBadge status={saleOrder.status} />
                          <p className='text-red-500'>{saleOrder.name}</p>
                          <p>
                            Salesperson:{' '}
                            {
                              <span className='font-semibold'>
                                {saleOrder.sales}
                              </span>
                            }
                          </p>
                        </div>
                        <div>
                          Tanggal Pesanan:{' '}
                          <span className='font-semibold'>
                            {saleOrder.dateOrder.split(' ')[0] || '-'}
                          </span>
                        </div>
                      </div>
                      <hr className='mt-3 mb-3 border border-gray-100' />
                      <div className='flex flex-row gap-2 justify-between items-center '>
                        <div className='flex justify-start w-4/5 flex-col gap-2'>
                          <div className='flex gap-2'>
                            <div>
                              <Image
                                src={saleOrder.products[0]?.parent?.image}
                                alt={saleOrder.products[0]?.name}
                                className='object-contain object-center border border-gray_r-6 h-32 w-full rounded-md'
                              />
                            </div>
                            <div className='flex flex-col gap-3 justify-start'>
                              <p className='flex flex-row gap-2'>
                                <span className='text-sm'>Nomor PO:</span>
                                <span className='text-sm text-red-500 font-semibold'>
                                  {saleOrder.purchaseOrderName || '-'}
                                </span>
                              </p>
                              <p className='line-clamp-2 leading-6 tracking-wide opacity-90 !text-gray_r-12 font-semibold text-nowrap'>
                                {saleOrder.products[0]?.parent?.name}
                              </p>
                              <p className='opacity-85 !text-gray_r-12'>
                                {saleOrder.products[0]?.quantity} x{' '}
                                {currencyFormat(
                                  saleOrder.products[0]?.price?.priceDiscount
                                )}
                              </p>
                              <div className='flex flex-row justify-start items-center'>
                                {saleOrder.products?.length > 1 && (
                                  <div className='flex flex-row gap-1 justify-start items-center'>
                                    {saleOrder.products
                                      .slice(1)
                                      .map((product, index) => (
                                        <Image
                                          key={index} // Tambahkan key untuk setiap elemen dalam map()
                                          src={product?.parent?.image}
                                          alt={product?.name}
                                          className='object-contain object-center border border-gray_r-6 h-8 w-8 rounded-md'
                                        />
                                      ))}
                                    <Link
                                      href={`/my/quotations/${saleOrder?.id}`}
                                      className='text-sm text-red-500 text-nowrap'
                                    >
                                      Lihat semua produk
                                    </Link>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                          <div className='flex flex-row w-full text-nowrap gap-2'>
                            <span className='text-sm'>
                              pesanan dibuat oleh:
                            </span>
                            <p className='text-sm font-semibold'>
                              {saleOrder.address.customer?.name || '-'}
                            </p>
                          </div>
                        </div>
                        <div className='w-[1px] h-24 bg-gray-300'></div>
                        <div className='w-1/5'>Total harga</div>
                      </div>
                      {/* </Link> */}
                    </div>
                  ))}
                </div>
              )}
            </div>
            <table className='table-data'>
              <thead>
                <tr>
                  <th>No. Transaksi</th>
                  <th>No. PO</th>
                  <th>Tanggal</th>
                  <th>Created By</th>
                  {auth?.feature?.soApproval && <th>Site</th>}
                  <th className='!text-left'>Salesperson</th>
                  <th className='!text-left'>Total</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {transactions.isLoading && (
                  <tr>
                    <td colSpan={7}>
                      <div className='flex justify-center my-2'>
                        <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
                      </div>
                    </td>
                  </tr>
                )}
                {!transactions.isLoading &&
                  (!transactions?.data?.saleOrders ||
                    transactions?.data?.saleOrders?.length == 0) && (
                    <tr>
                      <td colSpan={7}>Tidak ada transaksi</td>
                    </tr>
                  )}
                {transactions.data?.saleOrders?.map((saleOrder) => (
                  <tr key={saleOrder.id}>
                    <td>
                      <Link
                        className='whitespace-nowrap'
                        href={`${router.pathname}/${saleOrder.id}`}
                      >
                        {saleOrder.name}
                      </Link>
                    </td>
                    <td>{saleOrder.purchaseOrderName || '-'}</td>
                    <td>{saleOrder.dateOrder || '-'}</td>
                    <td>{saleOrder.address.customer?.name || '-'}</td>
                    {auth?.feature?.soApproval && (
                      <td>{saleOrder.sitePartner || '-'}</td>
                    )}
                    <td className='!text-left'>{saleOrder.sales}</td>
                    <td className='!text-left'>
                      {currencyFormat(saleOrder.amountTotal)}
                    </td>
                    <td>
                      <div className='flex justify-center'>
                        <TransactionStatusBadge status={saleOrder.status} />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            <Pagination
              pageCount={pageCount}
              currentPage={parseInt(pageNew)}
              // url={router.pathname + (pageQuery ? `?${pageQuery}` : '')}
              url={`/my/transactions?${toQuery(_.omit(query, ['page']))}`}
              className='mt-2 mb-2'
            />
          </div>
        </div>
      </DesktopView>
    </>
  );
};

export default Transactions;