Compare commits

...

168 Commits

Author SHA1 Message Date
rstubryan 3b9bd3c5bd Revert "refactor(FE): Prevent adding recordings for kandangs in transition"
This reverts commit 9dc30c1f58.
2026-03-09 03:50:33 +07:00
rstubryan 9dc30c1f58 refactor(FE): Prevent adding recordings for kandangs in transition 2026-03-09 03:35:03 +07:00
rstubryan 671fd72141 refactor(FE): Make stock fields optional during transition to laying 2026-03-09 03:32:44 +07:00
rstubryan d236138aa7 refactor(FE): Update recording editability logic and extend
BaseRecording type
2026-03-09 03:18:41 +07:00
Adnan Zahir 3042b54577 Merge branch 'fix/product-select-include-all-param' into 'development'
fix: add include all param to adjustment stock products select

See merge request mbugroup/lti-web-client!343
2026-03-09 00:51:43 +07:00
Adnan Zahir e5a686e5ee Merge branch 'hotfix/adjustment-fifo-stock-ttl' into 'development'
[HOTFIX/FE] FIFO Stock Adjustment for TTL, Recording and Project Flock (Chickin)

See merge request mbugroup/lti-web-client!342
2026-03-09 00:50:11 +07:00
Adnan Zahir 37d5a6b675 fix: add include all param to adjustment stock products select 2026-03-09 00:49:39 +07:00
rstubryan 2ff32094ce chore(FE): Fix inconsistent indentation in ChickLogsView and
RecordingForm
2026-03-08 22:13:26 +07:00
rstubryan 7207f1ba75 refactor(FE): Add isRecordingEditable check to detail actions 2026-03-08 22:12:29 +07:00
rstubryan 41d2e8737b feat(FE): Add chickin delete functionality with modal confirmation 2026-03-08 21:54:55 +07:00
rstubryan b2016314f5 refactor(FE): Restrict edit and delete actions based on recording status 2026-03-08 16:40:36 +07:00
rstubryan 7366d6490c refactor(FE): Validate transferToLayingId before fetching data 2026-03-08 16:34:59 +07:00
rstubryan e5e9b517fd refactor(FE): Update button visibility logic in TransferToLayingsTable 2026-03-08 16:17:20 +07:00
rstubryan b6629b0bbb refactor(FE): Set maxSourceQuantity in edit mode using existing data 2026-03-08 16:12:08 +07:00
rstubryan bac6766fa2 refactor(FE): Refactor transfer logic to use maxSourceQuantity state 2026-03-08 16:06:13 +07:00
Rivaldi A N S 9389fa0354 Merge branch 'fix/cleanup-warning-and-adjust-form-field' into 'development'
[FIX/FE] Cleanup Warning and Refactoring All Form Field (No Warning on Linter)

See merge request mbugroup/lti-web-client!341
2026-03-06 04:47:39 +00:00
rstubryan 37bc7a85e5 refactor(FE): Add depletion product handling in inventory adjustment
forms
2026-03-06 10:52:59 +07:00
rstubryan 667eb41eb2 refactor(FE): Refactor toggle logic for clarity in useModal 2026-03-06 10:08:13 +07:00
rstubryan e64b55e527 refactor(FE): Fix conditional call to onBackdropClick in Drawer
component
2026-03-06 10:00:25 +07:00
rstubryan 9710998dc6 refactor(FE): Handle null or undefined values in FinanceDetail component 2026-03-06 09:57:30 +07:00
rstubryan ca0b216ba0 refactor(FE): Handle null transaction_type and fix useEffect dependency 2026-03-06 09:53:57 +07:00
rstubryan 9ff6f3a35d refactor(FE): Refactor form components to improve state handling 2026-03-05 15:59:32 +07:00
rstubryan 333dd01f92 refactor(FE): Fix dependency array in useMemo for SalesClosingTable 2026-03-05 15:33:50 +07:00
rstubryan 75f765ee69 chore(FE): Add setTableState to useEffect dependency array 2026-03-05 15:05:17 +07:00
rstubryan 945bdb8b27 refactor(FE): Refactor formik field value setter in WarehousesTable 2026-03-05 15:02:00 +07:00
rstubryan 77eae32a3d refactor(FE): Refactor Formik field updates to use setFieldValue 2026-03-05 15:00:20 +07:00
rstubryan a5ebc6d1ae refactor(FE): Fix dependency arrays and improve error handling in
purchase components
2026-03-05 14:17:42 +07:00
rstubryan 15c7452d7b chore(FE): Fix missing dependency in useEffect hook 2026-03-05 14:15:41 +07:00
rstubryan 5dac900a1a refactor(FE): Refactor date filter state management in UniformityTable 2026-03-05 14:11:58 +07:00
rstubryan 4b49cd18f5 refactor(FE): Refactor form handlers to use consistent formik utilities 2026-03-05 13:45:01 +07:00
rstubryan a4cb4e202b refactor(FE): Fix dependency arrays and refactor setFieldValue usage 2026-03-05 13:36:43 +07:00
rstubryan 4a69eef294 fix(FE): Add handler to open filter modal and trigger form validation 2026-03-05 12:03:54 +07:00
rstubryan 2de6636bbf refactor(FE): Refactor tab actions to use memoized components 2026-03-05 11:59:27 +07:00
rstubryan a7951b6c28 refactor(FE): Fix missing dependencies in UniformityTable effect hooks 2026-03-05 11:47:16 +07:00
rstubryan 03baba40a6 refactor(FE): Remove unused params argument from
generateReportExpensePDF
2026-03-05 11:41:43 +07:00
rstubryan 96ef6f8496 refactor(FE): Refactor tab actions into a memoized component 2026-03-05 11:40:32 +07:00
rstubryan 94ab48d3f6 refactor(FE): Refactor tab actions to use memoized component 2026-03-05 11:21:56 +07:00
rstubryan ea88c3ce8e refactor(FE): Refactor tab actions to use memoized component 2026-03-05 11:10:36 +07:00
rstubryan 267ef9d812 refactor(FE): Refactor CustomerPaymentTab to use filterParams instead of
formik values
2026-03-05 11:01:52 +07:00
rstubryan b5fc1d4310 refactor(FE): Refactor tab actions to use memoized component 2026-03-05 10:57:13 +07:00
rstubryan c98e7d8cb3 refactor(FE): Fix population check to ensure proper boolean evaluation 2026-03-05 10:24:39 +07:00
rstubryan 1acbc91cfe refactor(FE): Reset dependent fields when location or project flock
changes
2026-03-05 10:19:30 +07:00
rstubryan 807041834b refactor(FE): Refactor formik field updates to use destructured methods 2026-03-05 09:54:50 +07:00
rstubryan 4de21561b3 refactor(FE): Refactor delivery order value initialization logic 2026-03-05 09:41:25 +07:00
rstubryan 1938f6cbda refactor(FE): Refactor DeliveryOrderProductTable to support delivery
order rendering
2026-03-04 17:13:30 +07:00
rstubryan f4a522fc0c refactor(FE): Refactor form field updates to use destructured Formik
methods
2026-03-04 16:48:21 +07:00
rstubryan 7ae04b3f3e refactor(FE): Refactor DashboardProduction callbacks for memoization 2026-03-04 14:12:45 +07:00
rstubryan b786acf71a chore(FE): Add setTableState to useEffect dependency arrays 2026-03-04 14:11:17 +07:00
rstubryan bb28ae8613 Merge branch 'development' of gitlab.com:mbugroup/lti-web-client into dev/restu 2026-03-04 11:59:06 +07:00
rstubryan 080592ff01 chore(FE): Remove unused variables and imports across components 2026-03-04 11:58:35 +07:00
Rivaldi A N S 6d41203a5e Merge branch 'feat/global-search-store' into 'development'
[FEAT/FE] Add Global Search Store and Filter for Each Table Index (All Module)

See merge request mbugroup/lti-web-client!340
2026-03-04 04:44:27 +00:00
rstubryan 89d7d3ef91 refactor(FE): Format imports in PurchaseTable.tsx 2026-03-04 11:07:30 +07:00
rstubryan 18ebf75aa7 feat(FE): Integrate UI store and pathname handling in table components 2026-03-04 11:06:53 +07:00
rstubryan 6e7dfebacc feat(FE): Integrate UI store for table state and search handling 2026-03-04 10:56:35 +07:00
rstubryan 4b93cb4589 feat(FE): Integrate UI store state with InventoryProductTable 2026-03-04 10:51:51 +07:00
rstubryan 58f1ab82c7 refactor(FE): Refactor long lines for readability in MovementTable 2026-03-04 10:45:15 +07:00
rstubryan 1fb9687142 feat(FE): Add filter functionality to inventory tables 2026-03-04 10:44:22 +07:00
rstubryan 4f6d71f1f4 refactor(FE): Refactor payload creation in
PurchaseOrderAcceptApprovalForm
2026-03-04 10:20:50 +07:00
rstubryan d502ec707c refactor(FE): Move error message above form actions in
InventoryAdjustmentForm
2026-03-04 09:36:37 +07:00
rstubryan fa86f488e1 refactor(FE): Standardize search input placeholders to "Search" 2026-03-03 14:19:52 +07:00
rstubryan 5e5400f56b feat(FE): Add advanced filtering capabilities to master data tables 2026-03-03 14:03:29 +07:00
rstubryan 741884ac29 feat(FE): Add filter schemas and types for master data components 2026-03-03 14:02:06 +07:00
rstubryan 4e278c5687 refactor(FE): Integrate UI store and pathname sync in master-data tables 2026-03-03 10:59:26 +07:00
rstubryan 3d2e40518b refactor(FE): Add table state management with path grouping logic 2026-03-03 10:33:03 +07:00
Rivaldi A N S cbab7f52f2 Merge branch 'dev/hotfix/restu' into 'development'
[HOTFIX/FE] Fix Constant Value of Adjustment Stock (Recording Depletion In)

See merge request mbugroup/lti-web-client!339
2026-03-03 02:50:52 +00:00
rstubryan ceb316d3da refactor(FE): Refactor subtype label mapping and fix depletion subtype
value
2026-03-03 09:15:57 +07:00
Rivaldi A N S 9ea152aef9 Merge branch 'hotfix/adjustment-stock-api-usage' into 'development'
[HOTFIX/FE] Fix Inventory AdjustmentForm using Product API Instead of Product Warehouse API

See merge request mbugroup/lti-web-client!338
2026-03-02 08:58:16 +00:00
rstubryan 910ea85b62 refactor(FE): Refactor InventoryAdjustmentForm to simplify product
handling
2026-03-02 15:24:14 +07:00
rstubryan 968243c370 refactor(FE): Refactor tab actions store to use slice pattern 2026-03-02 14:44:20 +07:00
Rivaldi A N S f1ba577a97 Merge branch 'fix/master-data-product-nonstock' into 'development'
[FIX/FE] Adjustment Product and Nonstock Match with FIFO Stock V2

See merge request mbugroup/lti-web-client!337
2026-03-02 07:33:43 +00:00
rstubryan c6b906a28e refactor(FE): Fix loading state for flag and sub-flag dropdowns 2026-03-02 14:12:42 +07:00
rstubryan eafcfd2f28 refactor(FE): Fix null check for product_flag_mapping in ProductForm 2026-03-02 14:06:12 +07:00
rstubryan 0e5d38f75c refactor(FE): Update field name from 'isExpedition' to 'flags' in
handler
2026-03-02 13:57:56 +07:00
rstubryan f2b59ded3c feat(FE): Add skeleton components for master data tables 2026-03-02 13:50:25 +07:00
rstubryan 1341b1ff53 refactor(FE): Add skeleton loaders for inventory tables 2026-03-02 13:31:23 +07:00
rstubryan 9c4c750664 refactor(FE): Refactor table skeleton components for consistency 2026-03-02 12:10:06 +07:00
rstubryan d3501e5f3d refactor(FE): Add skeleton loaders for ProjectFlock and TransferToLaying
tables
2026-03-02 11:56:27 +07:00
rstubryan d96388e5f4 refactor(FE): Rename and update import for UniformityTableFilter module 2026-03-02 11:42:34 +07:00
rstubryan 749b7d6f1a refactor(FE): Refactor UniformityTable to improve loading and empty
states
2026-03-02 11:34:27 +07:00
rstubryan aadf10b8b9 refactor(FE): Refactor master-data pages to simplify component rendering 2026-03-02 11:17:54 +07:00
rstubryan 7db6ae4077 refactor(FE): Refactor NonstocksTable to use Popover for row actions 2026-03-02 10:47:17 +07:00
rstubryan 7eaf6b7a3a refactor(FE): Refactor ProductTable and RowOptionsMenu for improved
clarity
2026-03-02 10:42:34 +07:00
rstubryan 8397d76171 refactor(FE): Add fallback for product flag mapping on constants error 2026-03-02 10:15:53 +07:00
rstubryan 56d4b8a5c9 refactor(FE): Update ProductFlagMapping types and related references 2026-03-02 10:15:06 +07:00
rstubryan ef9d820c0d refactor(FE): Refactor ProductForm to fetch constants via SWR 2026-03-02 10:06:06 +07:00
rstubryan 4e3c6736ab refactor(FE): Rename "Sub Flags" header to "Kategori Flags" 2026-03-02 09:58:01 +07:00
rstubryan aa1ef7a559 feat(FE): Add constants transformation utilities and API service 2026-03-02 09:57:21 +07:00
rstubryan 04b5a7bd4d refactor(FE): Update label in NonstockForm to 'Flags Ekspedisi' 2026-02-27 15:42:24 +07:00
rstubryan 3aec412599 refactor(FE): Update label text in NonstockForm RadioGroup 2026-02-27 15:38:47 +07:00
rstubryan 80a94c48c3 refactor(FE): Format product prices using formatCurrency helper 2026-02-27 15:38:11 +07:00
rstubryan 9bd4a73a90 refactor(FE): Refactor flags field to boolean and update form handling 2026-02-27 15:36:44 +07:00
rstubryan d1c6fe8fb4 refactor(FE): Add conditional validation for sub_flags in
ProductForm.schema
2026-02-27 15:03:09 +07:00
rstubryan a4378ebd04 refactor(FE): Refactor product flags to support single flag and
sub-flags
2026-02-27 14:57:45 +07:00
rstubryan 16f2f2bc06 feat(FE): Add PRODUCT_FLAG_MAPPING with flags, sub-flags, and mappings 2026-02-27 14:08:17 +07:00
rstubryan 64843a36ab refactor(FE): Refactor date input components for consistency and layout 2026-02-27 13:34:51 +07:00
rstubryan 396a5ab5ba refactor(FE): Rename and update FinanceTableFilter schema import path 2026-02-27 13:12:12 +07:00
rstubryan 9f4c041ec8 refactor(FE): Update FinanceTable layout and conditional styling 2026-02-27 11:27:51 +07:00
rstubryan 5e3d2273d1 refactor(FE): Refactor RowOptionsMenu to use PopoverButton and
PopoverContent
2026-02-27 11:25:37 +07:00
rstubryan 0b01eefe20 refactor(FE): Update button labels for clarity in FinanceTable 2026-02-27 11:23:06 +07:00
rstubryan 43045b3f8b Merge branch 'development' of gitlab.com:mbugroup/lti-web-client into dev/restu 2026-02-27 11:21:34 +07:00
rstubryan d3ce60d3ba refactor(FE): Refactor FinanceTable and simplify Finance page structure 2026-02-27 11:14:13 +07:00
Rivaldi A N S 8c7577dcc5 Merge branch 'fix/adjustment-stock-and-ui-related' into 'development'
[FIX/FE] Refactor Adjustment Stock with Latest FIFO Stock and Adjustment UI (Production, Inventory, Pembelian, Penjualan, Biaya, Closing)

See merge request mbugroup/lti-web-client!336
2026-02-27 04:02:05 +00:00
rstubryan da3cadc37d Merge branch 'development' of gitlab.com:mbugroup/lti-web-client into fix/adjustment-stock-and-ui-related 2026-02-27 10:28:35 +07:00
rstubryan 2e6aa1b83a refactor(FE): Filter out excluded product flags in product options 2026-02-27 10:04:54 +07:00
rstubryan 8811976f53 chore(FE): Remove redundant comments in InventoryAdjustmentForm 2026-02-27 09:30:10 +07:00
rstubryan 9fb65bdacd feat(FE): Validate quantity against available stock 2026-02-27 09:29:33 +07:00
rstubryan 6f6f54571f refactor(FE): Reset transaction subtype when product changes for
RECORDING
2026-02-26 16:20:00 +07:00
rstubryan 3099588141 refactor(FE): Filter transaction subtypes based on selected product
flags
2026-02-26 16:10:19 +07:00
rstubryan 47ee911852 feat(FE): Add stock availability badge to product dropdown 2026-02-26 15:56:31 +07:00
rstubryan b4d0ed1537 refactor(FE): Refactor product options handling in
InventoryAdjustmentForm
2026-02-26 15:39:49 +07:00
rstubryan 36f2368e95 refactor(FE): Refactor product selection to use ProductWarehouse API 2026-02-26 15:31:43 +07:00
rstubryan a4d5cbb117 refactor(FE): Simplify conditional formatting in InventoryAdjustmentForm 2026-02-26 15:12:19 +07:00
rstubryan c926a81756 refactor(FE): Update transaction subtype handling and labels 2026-02-26 15:11:39 +07:00
rstubryan 2476b6a4b4 refactor(FE): Format prices and totals as currency in
InventoryAdjustmentTable
2026-02-26 14:52:44 +07:00
rstubryan 01c1843fd5 refactor(FE): Refactor MovementTable to use Popover for row actions 2026-02-26 14:37:34 +07:00
rstubryan f86498e350 refactor(FE): Refactor InventoryProductTable to use Popover for row
options
2026-02-26 14:29:27 +07:00
rstubryan 5cd24f2c46 refactor(FE): Fix form error list visibility and field touch handling 2026-02-26 14:12:11 +07:00
rstubryan da0be9cb52 refactor(FE): Update input components to adjust spacing and text size 2026-02-26 14:11:33 +07:00
rstubryan da1cdfb59e refactor(FE): Refactor transaction type handling with useEffect 2026-02-26 13:58:21 +07:00
rstubryan a991150262 refactor(FE): Refactor InventoryAdjustmentForm layout for better
responsiveness
2026-02-26 13:32:52 +07:00
rstubryan ee49c91fba refactor(FE): Add type annotation for inventory adjustment payload 2026-02-26 12:08:36 +07:00
rstubryan 75463326e3 refactor(FE): Refactor InventoryAdjustmentForm to remove 'edit' type
handling
2026-02-26 12:07:14 +07:00
rstubryan e98c49ac5a refactor(FE): Update columns in InventoryAdjustmentTable 2026-02-26 11:48:27 +07:00
rstubryan aeeb0b721c refactor(FE): Refactor InventoryAdjustmentTable for improved readability 2026-02-26 11:31:17 +07:00
Rivaldi A N S b14bc00af4 Merge branch 'fix/fe/return-to-logout' into 'development'
[FIX/FE] add return fe cors

See merge request mbugroup/lti-web-client!334
2026-02-26 04:27:56 +00:00
ragilap e2a4088e77 [FEAT/BE] add return fe cors 2026-02-26 11:19:47 +07:00
rstubryan ebe80358ee refactor(FE): Remove unused import isResponseSuccess from
InventoryAdjustmentForm
2026-02-26 11:11:51 +07:00
rstubryan 9d4e9f6318 refactor(FE): Refactor InventoryAdjustmentForm to use useSelect for
Kandang
2026-02-26 11:09:13 +07:00
rstubryan e5007a285a refactor(FE): Refactor InventoryAdjustmentForm to improve state
management
2026-02-26 10:38:41 +07:00
rstubryan da82c704d5 refactor(FE): Fix validation message formatting in
InventoryAdjustmentForm
2026-02-26 10:12:48 +07:00
rstubryan 88b9c890e5 refactor(FE): Refactor inventory adjustment form 2026-02-26 10:10:59 +07:00
rstubryan 5a67901722 feat(FE): Add transaction type and subtype options to constants 2026-02-26 09:11:05 +07:00
rstubryan 0031a65f97 refactor(FE): Ensure filter modal closes on reset across components 2026-02-25 16:30:31 +07:00
rstubryan a89e83af29 refactor(FE): Fix multiline formatting for isError conditions 2026-02-25 15:57:25 +07:00
rstubryan a75d84556a refactor(FE): Refactor date validation to use shared state and cleanup 2026-02-25 15:56:12 +07:00
rstubryan 0af7b172a0 refactor(FE): Refactor PurchaseTable to use Popover for row options menu 2026-02-25 12:08:31 +07:00
rstubryan 8be33b230b refactor(FE): Refactor row options menu to use popover components 2026-02-25 11:59:17 +07:00
rstubryan 4fda2f661a refactor(FE): Remove unnecessary padding and margin classes in
components
2026-02-25 11:49:41 +07:00
rstubryan 22b1102454 refactor(FE): Refactor ExpensesTable to use ExpensesFilterModal 2026-02-25 11:40:42 +07:00
rstubryan e2e64f093f refactor(FE): Refactor TransferToLayingFilterModal to use schema
validation
2026-02-25 11:02:26 +07:00
rstubryan 90942b41b9 refactor(FE): Fix formatting of disabled condition in RecordingTable
button
2026-02-25 10:53:32 +07:00
rstubryan 93a2d99b7f refactor(FE): Disable filter button if kandang_id is not selected 2026-02-25 10:52:03 +07:00
rstubryan dae9a24a7c refactor(FE): Refactor array formatting and improve code readability 2026-02-25 10:41:34 +07:00
rstubryan f701ab0d91 refactor(FE): Replace active filter count logic with ButtonFilter
component
2026-02-25 10:39:14 +07:00
rstubryan 47a2439777 feat(FE): Add support for grouped fields in ButtonFilter active count
calculation
2026-02-25 10:07:26 +07:00
rstubryan cce84a3a6f refactor(FE): Refactor ButtonFilter to support excluded fields with
useMemo
2026-02-25 09:46:19 +07:00
Rivaldi A N S f92622cc22 Merge branch 'fix/adjustment-production-module' into 'development'
[FIX/FE] Adjustment Production Module (Recording & Uniformity)

See merge request mbugroup/lti-web-client!333
2026-02-25 02:32:21 +00:00
rstubryan f0041ca938 refactor(FE): Filter inactive kandangs in UniformityForm options 2026-02-24 21:05:22 +07:00
rstubryan 6566b881b2 refactor(FE): Use formatTitleCase for category text in StatusBadge 2026-02-24 21:02:56 +07:00
rstubryan 1a2e38568b refactor(FE): Remove unused page size selector and related logic 2026-02-24 15:46:32 +07:00
rstubryan ced3970aae refactor(FE): Add padding to RecordingTableSkeleton container class 2026-02-24 15:38:19 +07:00
rstubryan 9de31c991d refactor(FE): Refactor approval checks for readability 2026-02-24 15:34:11 +07:00
rstubryan bdca10e0ac refactor(FE): Handle rejected recordings in selection logic 2026-02-24 15:31:22 +07:00
rstubryan 9a5e2987d5 refactor(FE): Conditionally load data based on filter modal state 2026-02-24 15:22:06 +07:00
rstubryan a5b4deaac4 refactor(FE): Refactor RecordingTable layout for improved readability 2026-02-24 15:13:37 +07:00
rstubryan 82953f4c9c Merge branch 'development' of gitlab.com:mbugroup/lti-web-client into dev/restu 2026-02-24 14:48:34 +07:00
rstubryan 509fc5476d refactor(FE): Refactor recording table and add filter modal 2026-02-24 14:48:09 +07:00
Rivaldi A N S 6a10849a84 Merge branch 'fix/adjustment-pf-report-penjualan' into 'development'
[FIX/FE] Adjustment Project Flock Related, Penjualan Calculation (Both SO/DO) and Report Filter Display Issue

See merge request mbugroup/lti-web-client!332
2026-02-24 03:24:42 +00:00
rstubryan 50424a25fc refactor(FE): Remove redundant transformations and validations in
schemas
2026-02-23 16:05:12 +07:00
rstubryan 35b09b514f refactor(FE): Refactor form field change handlers for real-time
calculations
2026-02-23 15:30:54 +07:00
rstubryan 81e4e1fc6a refactor(FE): Update validation rules for SalesOrderProduct schema 2026-02-23 14:12:44 +07:00
rstubryan 62c9ab014d refactor(FE): Add period filter to ProjectFlockTable 2026-02-23 13:51:32 +07:00
rstubryan ba28d64562 refactor(FE): Format type definition for readability 2026-02-23 13:40:00 +07:00
rstubryan 75ee058818 feat(FE): Add filter functionality to ProjectFlockTable 2026-02-23 13:38:47 +07:00
rstubryan 755bddc74c refactor(FE): Fix logic for checking active projects in the same kandang
from the validation logic.
2026-02-23 12:10:44 +07:00
rstubryan 08aa1900a8 feat(FE): Add validation for disabling close button in
ProjectFlockDetail
2026-02-23 11:55:07 +07:00
rstubryan 7e1166b5e8 refactor(FE): Refactor tab actions store to use a unified implementation 2026-02-23 11:05:11 +07:00
rstubryan 75e9b06a83 refactor(FE): Set default value for show_unrecorded to false 2026-02-23 10:27:34 +07:00
158 changed files with 13113 additions and 7209 deletions
+1 -6
View File
@@ -3,12 +3,7 @@
import FinanceTable from '@/components/pages/finance/FinanceTable';
const Finance = () => {
return (
<section className='size-full p-6'>
<div className='flex flex-row gap-4'></div>
<FinanceTable />
</section>
);
return <FinanceTable />;
};
export default Finance;
+1 -1
View File
@@ -2,7 +2,7 @@ import InventoryAdjustmentTable from '@/components/pages/inventory/adjustment/In
const InventoryAdjustment = () => {
return (
<section className='w-full p-4'>
<section className='w-full'>
<InventoryAdjustmentTable />
</section>
);
+1 -5
View File
@@ -1,11 +1,7 @@
import AreasTable from '@/components/pages/master-data/area/AreasTable';
const Nonstock = () => {
return (
<section className='w-full p-4'>
<AreasTable />
</section>
);
return <AreasTable />;
};
export default Nonstock;
+1 -5
View File
@@ -1,11 +1,7 @@
import BanksTable from '@/components/pages/master-data/bank/BanksTable';
const Bank = () => {
return (
<section className='w-full p-4'>
<BanksTable />
</section>
);
return <BanksTable />;
};
export default Bank;
+1 -5
View File
@@ -1,11 +1,7 @@
import CustomersTable from '@/components/pages/master-data/customer/CustomersTable';
const Customer = () => {
return (
<section className='w-full p-4'>
<CustomersTable />
</section>
);
return <CustomersTable />;
};
export default Customer;
+1 -5
View File
@@ -1,11 +1,7 @@
import FlockTable from '@/components/pages/master-data/flock/FlocksTable';
const Flock = () => {
return (
<section className='w-full p-4'>
<FlockTable />
</section>
);
return <FlockTable />;
};
export default Flock;
+1 -5
View File
@@ -1,11 +1,7 @@
import KandangsTable from '@/components/pages/master-data/kandang/KandangsTable';
const Nonstock = () => {
return (
<section className='w-full p-4'>
<KandangsTable />
</section>
);
return <KandangsTable />;
};
export default Nonstock;
+1 -5
View File
@@ -1,11 +1,7 @@
import LocationsTable from '@/components/pages/master-data/location/LocationsTable';
const Nonstock = () => {
return (
<section className='w-full p-4'>
<LocationsTable />
</section>
);
return <LocationsTable />;
};
export default Nonstock;
+1 -5
View File
@@ -1,11 +1,7 @@
import NonstocksTable from '@/components/pages/master-data/nonstock/NonstocksTable';
const Nonstock = () => {
return (
<section className='w-full p-4'>
<NonstocksTable />
</section>
);
return <NonstocksTable />;
};
export default Nonstock;
@@ -1,11 +1,7 @@
import ProductCategoryTable from '@/components/pages/master-data/product-category/ProductCategoryTable';
const ProductCategory = () => {
return (
<section className='w-full p-4'>
<ProductCategoryTable />
</section>
);
return <ProductCategoryTable />;
};
export default ProductCategory;
+1 -5
View File
@@ -1,11 +1,7 @@
import ProductsTable from '@/components/pages/master-data/product/ProductTable';
const Product = () => {
return (
<section className='w-full p-4'>
<ProductsTable />
</section>
);
return <ProductsTable />;
};
export default Product;
@@ -1,11 +1,7 @@
import ProductionStandardTable from '@/components/pages/master-data/production-standard/ProductionStandardTable';
const ProductionStandardPage = () => {
return (
<div className='w-full'>
<ProductionStandardTable />
</div>
);
return <ProductionStandardTable />;
};
export default ProductionStandardPage;
+1 -5
View File
@@ -1,11 +1,7 @@
import SuppliersTable from '@/components/pages/master-data/supplier/SupplierTable';
const Supplier = () => {
return (
<section className='w-full p-4'>
<SuppliersTable />
</section>
);
return <SuppliersTable />;
};
export default Supplier;
+1 -5
View File
@@ -1,11 +1,7 @@
import UomsTable from '@/components/pages/master-data/uom/UomsTable';
const Nonstock = () => {
return (
<section className='w-full p-4'>
<UomsTable />
</section>
);
return <UomsTable />;
};
export default Nonstock;
+1 -5
View File
@@ -1,11 +1,7 @@
import WarehousesTable from '@/components/pages/master-data/warehouse/WarehousesTable';
const Warehouse = () => {
return (
<section className='w-full p-4'>
<WarehousesTable />
</section>
);
return <WarehousesTable />;
};
export default Warehouse;
+1 -1
View File
@@ -2,7 +2,7 @@ import RecordingTable from '@/components/pages/production/recording/RecordingTab
const Recording = () => {
return (
<section className='w-full p-4 sm:p-0'>
<section className='w-full'>
<RecordingTable />
</section>
);
+3 -1
View File
@@ -108,7 +108,9 @@ const Drawer = ({
if (closeOnBackdropClick) {
setOpen(false);
}
onBackdropClick && onBackdropClick();
if (onBackdropClick) {
onBackdropClick();
}
};
return (
+5 -1
View File
@@ -31,7 +31,11 @@ export const useModal = (isNestingModal = false) => {
}, []);
const toggle = useCallback(() => {
open ? closeModal() : openModal();
if (open) {
closeModal();
} else {
openModal();
}
}, [open, closeModal, openModal]);
useEffect(() => {
+5 -1
View File
@@ -26,13 +26,17 @@ const Navbar = ({ toggleSidebar }: NavbarProps) => {
const logoutClickHandler = async () => {
const logoutRes = await AuthApi.logout();
if (isResponseError(logoutRes)) {
toast.error('Gagal logout! Coba lagi!');
return;
}
setUser(undefined);
const redirect = (logoutRes as { redirect?: string })?.redirect;
if (redirect) {
window.location.href = redirect;
return;
}
router.replace(process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string);
};
+41 -7
View File
@@ -3,15 +3,51 @@ import { getFilledFormikValuesCount } from '@/lib/formik-helper';
import { cn } from '@/lib/helper';
import { Icon } from '@iconify/react';
import { FormikValues } from 'formik';
import { useMemo } from 'react';
export type ButtonFilterProps = ButtonProps & {
values: FormikValues;
onClick: () => void;
excludeFields?: string[];
fieldGroups?: string[][];
};
// 'bg-gradient-to-t from-blue-50 to-blue-100 border-blue-500 text-blue-600 hover:from-blue-100 hover:to-blue-200
const ButtonFilter = ({ values, onClick, ...props }: ButtonFilterProps) => {
const ButtonFilter = ({
values,
onClick,
excludeFields = [],
fieldGroups = [],
...props
}: ButtonFilterProps) => {
const activeCount = useMemo(() => {
const filteredValues: FormikValues = {};
Object.keys(values).forEach((key) => {
if (!excludeFields.includes(key)) {
filteredValues[key] = values[key];
}
});
let count = getFilledFormikValuesCount(filteredValues);
fieldGroups.forEach((group) => {
const groupFields = group.filter(
(field) => !excludeFields.includes(field)
);
const filledGroupFields = groupFields.filter(
(field) => filteredValues[field]
);
if (
filledGroupFields.length === groupFields.length &&
groupFields.length > 1
) {
count -= groupFields.length - 1;
}
});
return count;
}, [values, excludeFields, fieldGroups]);
return (
<Button
{...props}
@@ -21,7 +57,7 @@ const ButtonFilter = ({ values, onClick, ...props }: ButtonFilterProps) => {
className={cn(
'rounded-lg max-h-10 font-semibold text-sm gap-1.5',
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft',
getFilledFormikValuesCount(values) > 0
activeCount > 0
? 'border-primary-gradient text-primary rounded-lg!'
: 'rounded-lg',
props.className
@@ -31,14 +67,12 @@ const ButtonFilter = ({ values, onClick, ...props }: ButtonFilterProps) => {
icon='heroicons:funnel'
width={20}
height={20}
className={
getFilledFormikValuesCount(values) > 0 ? 'text-blue-600' : ''
}
className={activeCount > 0 ? 'text-blue-600' : ''}
/>
Filter
{getFilledFormikValuesCount(values) > 0 && (
{activeCount > 0 && (
<span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
{getFilledFormikValuesCount(values)}
{activeCount}
</span>
)}
</Button>
+8 -2
View File
@@ -134,14 +134,20 @@ const DropFileInput: React.FC<DropFileInputProps> = ({
{!isError && bottomLabel && (
<p
className={cn('w-full text-sm opacity-60', className?.bottomLabel)}
className={cn(
'w-full mt-1.5 text-xs opacity-60',
className?.bottomLabel
)}
>
{bottomLabel}
</p>
)}
{isError && (
<p
className={cn('w-full text-sm text-error', className?.errorMessage)}
className={cn(
'w-full mt-1.5 text-xs text-error',
className?.errorMessage
)}
>
{errorMessage}
</p>
+2 -2
View File
@@ -144,12 +144,12 @@ export const RadioGroup = ({
{/* Label bawah */}
{!isError && bottomLabel && (
<p className='text-sm opacity-60'>{bottomLabel}</p>
<p className='mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
)}
{/* Pesan error */}
{isError && errorMessage && (
<p className='text-sm text-error'>{errorMessage}</p>
<p className='mt-1.5 text-xs text-error'>{errorMessage}</p>
)}
</div>
</RadioGroupContext.Provider>
+4 -2
View File
@@ -488,9 +488,11 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
/>
)}
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
{isError && (
<p className='w-full mt-1.5 text-xs text-error'>{errorMessage}</p>
)}
{!isError && bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
)}
</div>
);
+4 -2
View File
@@ -159,9 +159,11 @@ const TagInput: React.FC<TagInputProps> = ({
{/* Bottom label or error message */}
{!isError && bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
)}
{isError && (
<p className='w-full mt-1.5 text-xs text-error'>{errorMessage}</p>
)}
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
</div>
);
};
@@ -18,7 +18,7 @@ import HppExpeditionClosingTab from '@/components/pages/closing/tab/HppExpeditio
import ClosingKandangList from '@/components/pages/closing/ClosingKandangList';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { useClosingTabStore } from '@/stores/closing/closing-tab.store';
import { useTabActionsStore } from '@/stores/tab-actions/tab-actions.store';
interface ClosingDetailProps {
id: number;
initialValue?: ClosingGeneralInformation;
@@ -33,7 +33,7 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
kandangData,
}) => {
const [activeTabId, setActiveTabId] = useState<string>('sapronak');
const tabActions = useClosingTabStore((state) => state.tabActions);
const tabActions = useTabActionsStore((state) => state.tabActions);
const closingDetailTabs = useMemo(() => {
const validTabs = [
+33 -50
View File
@@ -1,6 +1,8 @@
'use client';
import { ChangeEventHandler, useEffect, useState, useMemo } from 'react';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import { useRouter } from 'next/navigation';
@@ -31,6 +33,7 @@ import {
ClosingFilterType,
} from '@/components/pages/closing/filter/ClosingFilter';
import ClosingTableSkeleton from '@/components/pages/closing/skeleton/ClosingTableSkeleton';
import ButtonFilter from '@/components/helper/ButtonFilter';
const RowOptionsMenu = ({
props,
@@ -90,6 +93,9 @@ const RowOptionsMenu = ({
};
const ClosingsTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
// ===== ROUTER =====
const router = useRouter();
@@ -158,6 +164,7 @@ const ClosingsTable = () => {
onReset: () => {
updateFilter('location_id', '');
updateFilter('project_status', '');
filterModal.closeModal();
},
});
@@ -287,25 +294,17 @@ const ClosingsTable = () => {
);
}, [formik.values.project_status, projectStatusOptions]);
// ===== ACTIVE FILTERS COUNT =====
const activeFiltersCount = useMemo(() => {
let count = 0;
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
if (tableFilterState.location_id) {
count += 1;
}
if (tableFilterState.project_status) {
count += 1;
}
return count;
}, [tableFilterState.location_id, tableFilterState.project_status]);
const hasFilters = activeFiltersCount > 0;
useEffect(() => {
setTableState('closing-table', pathname);
}, [pathname, setTableState]);
// ===== SEARCH CHANGE HANDLER =====
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
@@ -352,25 +351,12 @@ const ClosingsTable = () => {
}}
/>
<Button
variant='outline'
color='none'
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={handleFilterModalOpen}
className={cn(
'px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft transition-all',
{
'border-primary-gradient text-primary': hasFilters,
}
)}
>
<Icon icon='heroicons:funnel' width={20} height={20} />
Filter
{hasFilters && (
<span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
{activeFiltersCount}
</span>
)}
</Button>
className='px-3 py-2.5'
/>
</div>
</div>
@@ -379,19 +365,19 @@ const ClosingsTable = () => {
<span className='loading loading-spinner loading-xl' />
</div>
) : data.length === 0 ? (
<ClosingTableSkeleton
columns={closingsColumns}
icon={
<Icon
icon='heroicons:chart-bar'
className='text-white'
width={20}
height={20}
/>
}
title='Data Closing Belum Tersedia'
subtitle='Tidak ada data closing untuk saat ini.'
/>
<div className='mt-3'>
<ClosingTableSkeleton
columns={closingsColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Closing>
data={isResponseSuccess(closings) ? closings?.data : []}
@@ -410,10 +396,7 @@ const ClosingsTable = () => {
rowSelection={rowSelection}
setRowSelection={setRowSelection}
className={{
containerClassName: cn('mt-3', {
'w-full mb-0':
isResponseSuccess(closings) && closings?.data?.length === 0,
}),
containerClassName: cn('mt-3 mb-0'),
headerColumnClassName: 'text-nowrap',
}}
/>
@@ -6,13 +6,13 @@ import { ColumnDef } from '@tanstack/react-table';
const ClosingTableSkeleton = ({
columns,
icon,
title,
subtitle,
title = 'No Data Available',
subtitle = 'There is no closing data displayed. Enter closing data to get started.',
}: {
columns: ColumnDef<Closing>[];
icon: React.ReactNode;
title: string;
subtitle: string;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
@@ -308,7 +308,16 @@ const SalesClosingTable = ({ projectFlockId }: SalesClosingTableProps) => {
// },
// },
],
[]
[
summary,
totals.avgActualPrice,
totals.avgSalesPrice,
totals.avgWeight,
totals.totalActualPrice,
totals.totalQuantity,
totals.totalSalesPrice,
totals.totalWeight,
]
);
return (
@@ -150,33 +150,39 @@ const DashboardProduction = () => {
},
});
const { resetForm } = formik;
const handleResetFilter = useCallback(() => {
formik.resetForm();
resetForm();
resetFilterValues(); // Clear stored filter values
setAnalysisMode('OVERVIEW');
setEndpointUrl('/dashboards');
setSelectedLocationIds([]);
}, [resetFilterValues, filterValues, selectedLocationIds]);
}, [resetForm, resetFilterValues]);
const handleApplyFilter = (values: DashboardFilter) => {
// Build query params object, only include non-empty values
const params: Record<string, string> = {};
const handleApplyFilter = useCallback(
(values: DashboardFilter) => {
// Build query params object, only include non-empty values
const params: Record<string, string> = {};
if (values.start_date) params.start_date = values.start_date;
if (values.end_date) params.end_date = values.end_date;
if (values.analysis_mode) params.analysis_mode = values.analysis_mode;
if (values.location_ids.length > 0)
params.location_ids = values.location_ids.toString();
if (values.flock_ids.length > 0)
params.flock_ids = values.flock_ids.toString();
if (values.kandang_ids.length > 0)
params.kandang_ids = values.kandang_ids.toString();
if (values.comparison_type) params.comparison_type = values.comparison_type;
if (values.start_date) params.start_date = values.start_date;
if (values.end_date) params.end_date = values.end_date;
if (values.analysis_mode) params.analysis_mode = values.analysis_mode;
if (values.location_ids.length > 0)
params.location_ids = values.location_ids.toString();
if (values.flock_ids.length > 0)
params.flock_ids = values.flock_ids.toString();
if (values.kandang_ids.length > 0)
params.kandang_ids = values.kandang_ids.toString();
if (values.comparison_type)
params.comparison_type = values.comparison_type;
setEndpointUrl(`/dashboards?${new URLSearchParams(params).toString()}`);
filterModal.closeModal();
refreshDashboardProductionData();
};
setEndpointUrl(`/dashboards?${new URLSearchParams(params).toString()}`);
filterModal.closeModal();
refreshDashboardProductionData();
},
[filterModal, refreshDashboardProductionData]
);
// ===== Load filter from store on mount =====
useEffect(() => {
@@ -190,20 +196,20 @@ const DashboardProduction = () => {
kandang_ids: normalizeToArray(filterValues.kandang),
comparison_type: filterValues.comparisonType,
});
}, [filterValues]);
}, [filterValues, handleApplyFilter]);
// ===== Formik Error List =====
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
// ===== Export PDF =====
const handleExportPDF = async () => {
const handleExportPDF = useCallback(async () => {
await generateDashboardPDF({
filterValues: formik.values,
allStatsRef,
allChartsRef,
setExporting,
});
};
}, [formik.values]);
// ===== Register Navbar Actions =====
const openFilterModalRef = useRef(filterModal.openModal);
@@ -253,7 +259,7 @@ const DashboardProduction = () => {
</Dropdown>
</div>
);
}, [formik.values, exporting, setNavbarActions]);
}, [formik.values, exporting, setNavbarActions, handleExportPDF]);
// Cleanup only on unmount
useEffect(() => {
@@ -409,14 +409,14 @@ const DashboardLineChart = ({
axisLine={{ stroke: '#C1C1C180', opacity: 0.5 }}
domain={(() => {
// Calculate dynamic domain based on visible data
let seriesData: DashboardChartsSeries[] = [];
// let seriesData: DashboardChartsSeries[] = [];
let dataset: DashboardChartsDataset[] = [];
if (
analysisMode === 'OVERVIEW' &&
isOverviewCharts(data.charts)
) {
seriesData = data.charts[chartData]?.series || [];
// seriesData = data.charts[chartData]?.series || [];
dataset = data.charts[chartData]?.dataset || [];
} else if (
analysisMode === 'COMPARISON' &&
@@ -426,7 +426,7 @@ const DashboardLineChart = ({
data.charts.farm ||
data.charts.flock ||
data.charts.kandang;
seriesData = comparisonChart?.series || [];
// seriesData = comparisonChart?.series || [];
dataset = comparisonChart?.dataset || [];
}
+307 -329
View File
@@ -1,6 +1,8 @@
'use client';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
import useSWR from 'swr';
import {
CellContext,
@@ -16,41 +18,40 @@ import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import RealizationStatusBadge from '@/components/pages/expense/RealizationStatusBadge';
import ExpenseStatusBadge from '@/components/pages/expense/ExpenseStatusBadge';
import CheckboxInput from '@/components/input/CheckboxInput';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import DateInput from '@/components/input/DateInput';
import RequirePermission from '@/components/helper/RequirePermission';
import ButtonFilter from '@/components/helper/ButtonFilter';
import ExpensesFilterModal from '@/components/pages/expense/filter/ExpensesFilterModal';
import ExpenseTableSkeleton from '@/components/pages/expense/skeleton/ExpenseTableSkeleton';
import { Expense } from '@/types/api/expense';
import { ExpenseApi } from '@/services/api/expense';
import { cn, formatCurrency, formatDate } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { LocationApi, SupplierApi } from '@/services/api/master-data';
import { Location } from '@/types/api/master-data/location';
import { Supplier } from '@/types/api/master-data/supplier';
import { BaseApiResponse } from '@/types/api/api-general';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Expense, unknown>;
approveClickHandler: () => void;
rejectClickHandler: () => void;
deleteClickHandler: () => void;
}) => {
const popoverId = `expense#${props.row.original.id}`;
const popoverAnchorName = `--anchor-expense#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
const showEditButton = props.row.original.latest_approval
? props.row.original.latest_approval.step_number !== 6 &&
(props.row.original.latest_approval.step_number === 1 ||
@@ -59,85 +60,102 @@ const RowOptionsMenu = ({
props.row.original.latest_approval.step_number === 4)
: false;
// TODO: apply RBAC
const showRealizationButton = props.row.original.latest_approval
? props.row.original.latest_approval.action !== 'REJECTED' &&
props.row.original.latest_approval.step_number === 4
: false;
return (
<RowOptionsMenuWrapper type={type}>
<div className='w-full max-h-40 overflow-auto flex flex-col gap-1'>
<RequirePermission permissions='lti.expense.detail'>
<Button
href={`/expense/detail/?expenseId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
{showEditButton && (
<RequirePermission permissions='lti.expense.update'>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.expense.detail'>
<Button
href={`/expense/detail/edit/?expenseId=${props.row.original.id}`}
href={`/expense/detail/?expenseId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon
icon='material-symbols:edit-outline'
width={16}
height={16}
/>
Edit
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
)}
{showRealizationButton && (
<RequirePermission permissions='lti.expense.create.realization'>
{showEditButton && (
<RequirePermission permissions='lti.expense.update'>
<Button
href={`/expense/detail/edit/?expenseId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='mdi:pencil-outline' width={20} height={20} />
Edit
</Button>
</RequirePermission>
)}
{showRealizationButton && (
<RequirePermission permissions='lti.expense.create.realization'>
<Button
href={`/expense/realization/?expenseId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon
icon='material-symbols:money-bag-rounded'
width={20}
height={20}
className='text-info'
/>
Realisasi
</Button>
</RequirePermission>
)}
<RequirePermission permissions='lti.expense.delete'>
<Button
href={`/expense/realization/?expenseId=${props.row.original.id}`}
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='info'
className='justify-start text-sm text-info focus-visible:text-info-content hover:text-info-content'
color='error'
className='p-3 justify-start text-sm font-semibold w-full focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:money-bag-rounded'
width={16}
height={16}
/>
Realisasi
<Icon icon='mdi:delete-outline' width={20} height={20} />
Delete
</Button>
</RequirePermission>
)}
<RequirePermission permissions='lti.expense.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</div>
</RowOptionsMenuWrapper>
</div>
</PopoverContent>
</div>
);
};
const ExpensesTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -179,6 +197,9 @@ const ExpensesTable = () => {
const approveModal = useModal();
const rejectModal = useModal();
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
const [selectedExpense, setSelectedExpense] = useState<Expense | undefined>(
undefined
);
@@ -340,31 +361,7 @@ const ExpensesTable = () => {
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 3;
const approveClickHandler = () => {
setSelectedExpense(props.row.original);
// Set row selection
setRowSelection({
[String(props.row.original.id)]: true,
});
setApprovalNotes('');
approveModal.openModal();
};
const rejectClickHandler = () => {
setSelectedExpense(props.row.original);
// Set row selection
setRowSelection({
[String(props.row.original.id)]: true,
});
setApprovalNotes('');
rejectModal.openModal();
};
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedExpense(props.row.original);
@@ -372,31 +369,11 @@ const ExpensesTable = () => {
};
return (
<>
{currentPageSize > 3 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
approveClickHandler={approveClickHandler}
rejectClickHandler={rejectClickHandler}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 3 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
approveClickHandler={approveClickHandler}
rejectClickHandler={rejectClickHandler}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
<RowOptionsMenu
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
props={props}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
@@ -535,51 +512,41 @@ const ExpensesTable = () => {
setIsRejectLoading(false);
};
const {
setInputValue: setLocationInputValue,
options: locationOptions,
isLoadingOptions: isLoadingLocationOptions,
} = useSelect<Location>(LocationApi.basePath, 'id', 'name');
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
null
);
const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
setSelectedLocation(val as OptionType);
updateFilter(
'locationId',
val ? ((val as OptionType).value as string) : ''
);
};
const {
setInputValue: setVendorInputValue,
options: vendorOptions,
isLoadingOptions: isLoadingVendorOptions,
} = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name');
const [selectedVendor, setSelectedVendor] = useState<OptionType | null>(null);
const vendorChangeHandler = (val: OptionType | OptionType[] | null) => {
setSelectedVendor(val as OptionType);
updateFilter('vendorId', val ? ((val as OptionType).value as string) : '');
};
useEffect(() => {
setTableState('expense-table', pathname);
}, [pathname, setTableState]);
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const transactionDateChangeHandler: ChangeEventHandler<HTMLInputElement> = (
e
) => {
updateFilter('transactionDate', e.target.value);
// ===== FILTER MODAL HANDLERS =====
const handleFilterModalOpen = () => {
filterModal.openModal();
};
const realizationDateChangeHandler: ChangeEventHandler<HTMLInputElement> = (
e
) => {
updateFilter('realizationDate', e.target.value);
const handleFilterSubmit = (values: {
transaction_date?: string | null;
realization_date?: string | null;
location_id?: string | null;
vendor_id?: string | null;
}) => {
updateFilter('transactionDate', values.transaction_date || '');
updateFilter('realizationDate', values.realization_date || '');
updateFilter('locationId', values.location_id || '');
updateFilter('vendorId', values.vendor_id || '');
};
const handleFilterReset = () => {
updateFilter('transactionDate', '');
updateFilter('realizationDate', '');
updateFilter('locationId', '');
updateFilter('vendorId', '');
};
// track sorting
@@ -595,188 +562,193 @@ const ExpensesTable = () => {
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-4'>
<div className='w-full sm:w-fit flex flex-col sm:flex-row self-start gap-2'>
<RequirePermission permissions='lti.expense.create'>
<div className='w-full'>
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.expense.create'>
<Button
href='/expense/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-xl shadow-button-soft'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Expense
</Button>
</RequirePermission>
{selectedRowIds.length > 0 && (
<>
<hr className='w-px h-full border-none bg-base-content/10 sm:block hidden' />
<RequirePermission permissions='lti.expense.approve.head_area'>
<Button
href='/expense/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
variant='outline'
color='none'
onClick={bulkApproveClickHandler}
disabled={!isAllSelectedRowLatestApprovalOnHeadArea}
className='px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Expense
<Icon
icon='lucide-lab:farm'
width={20}
height={20}
className='text-success'
/>
Approve Head Area
</Button>
</RequirePermission>
{selectedRowIds.length > 0 && (
<>
<RequirePermission permissions='lti.expense.approve.head_area'>
<Button
variant='outline'
color='info'
onClick={bulkApproveClickHandler}
disabled={!isAllSelectedRowLatestApprovalOnHeadArea}
className='w-full sm:w-fit'
>
<Icon icon='lucide-lab:farm' width={24} height={24} />
Approve Head Area
</Button>
</RequirePermission>
<RequirePermission permissions='lti.expense.approve.unit_vice_president'>
<Button
variant='outline'
color='none'
onClick={bulkApproveClickHandler}
disabled={
!isAllSelectedRowLatestApprovalOnUnitVicePresident
}
className='px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
>
<Icon
icon='tdesign:money'
width={20}
height={20}
className='text-success'
/>
Approve Unit Vice President
</Button>
</RequirePermission>
<RequirePermission permissions='lti.expense.approve.unit_vice_president'>
<Button
variant='outline'
color='success'
onClick={bulkApproveClickHandler}
disabled={
!isAllSelectedRowLatestApprovalOnUnitVicePresident
}
className='w-full sm:w-fit'
>
<Icon icon='tdesign:money' width={24} height={24} />
Approve Unit Vice President
</Button>
</RequirePermission>
<RequirePermission permissions='lti.expense.approve.finance'>
<Button
variant='outline'
color='none'
onClick={bulkApproveClickHandler}
disabled={!isAllSelectedRowLatestApprovalOnFinance}
className='px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
>
<Icon
icon='tdesign:money'
width={20}
height={20}
className='text-success'
/>
Approve Finance
</Button>
</RequirePermission>
<RequirePermission permissions='lti.expense.approve.finance'>
<Button
variant='outline'
color='success'
onClick={bulkApproveClickHandler}
disabled={!isAllSelectedRowLatestApprovalOnFinance}
className='w-full sm:w-fit'
>
<Icon icon='tdesign:money' width={24} height={24} />
Approve Finance
</Button>
</RequirePermission>
<RequirePermission
permissions={[
'lti.expense.approve.head_area',
'lti.expense.approve.unit_vice_president',
'lti.expense.approve.finance',
]}
>
<Button
variant='outline'
color='none'
onClick={bulkRejectClickHandler}
disabled={
!isAllSelectedRowLatestApprovalOnHeadArea &&
!isAllSelectedRowLatestApprovalOnUnitVicePresident &&
!isAllSelectedRowLatestApprovalOnFinance
}
className='px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
>
<Icon
icon='material-symbols:close'
width={20}
height={20}
className='text-error'
/>
Reject
</Button>
</RequirePermission>
</>
)}
</div>
<RequirePermission
permissions={[
'lti.expense.approve.head_area',
'lti.expense.approve.unit_vice_president',
'lti.expense.approve.finance',
]}
>
<Button
variant='outline'
color='error'
onClick={bulkRejectClickHandler}
disabled={
!isAllSelectedRowLatestApprovalOnHeadArea &&
!isAllSelectedRowLatestApprovalOnUnitVicePresident &&
!isAllSelectedRowLatestApprovalOnFinance
}
className='w-full sm:w-fit'
>
<Icon
icon='material-symbols:close'
width={24}
height={24}
/>
Reject
</Button>
</RequirePermission>
</>
)}
</div>
</div>
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
/>
<div className='grid grid-cols-12 justify-end gap-2'>
<DateInput
required
label='Tanggal Transaksi'
name='transaction_date'
placeholder='Masukkan tanggal transaksi'
value={tableFilterState.transactionDate}
onChange={transactionDateChangeHandler}
className={{
wrapper: 'col-span-12 sm:col-span-3',
}}
/>
<DateInput
required
label='Tanggal Realisasi'
name='realization_date'
placeholder='Masukkan tanggal realisasi'
value={tableFilterState.realizationDate}
onChange={realizationDateChangeHandler}
className={{
wrapper: 'col-span-12 sm:col-span-3',
}}
/>
<SelectInput
label='Lokasi'
options={locationOptions}
isLoading={isLoadingLocationOptions}
value={selectedLocation}
onChange={locationChangeHandler}
onInputChange={setLocationInputValue}
isClearable
className={{
wrapper: 'col-span-12 sm:col-span-3',
}}
/>
<SelectInput
label='Vendor'
options={vendorOptions}
isLoading={isLoadingVendorOptions}
value={selectedVendor}
onChange={vendorChangeHandler}
onInputChange={setVendorInputValue}
isClearable
className={{
wrapper: 'col-span-12 sm:col-span-3',
}}
/>
<DebouncedTextInput
name='search'
placeholder='Cari Biaya Operasional'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'col-span-12 max-w-52 justify-self-end' }}
/>
</div>
<ButtonFilter
values={tableFilterState}
excludeFields={[
'page',
'pageSize',
'search',
'nameSort',
'userId',
]}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
<Table<Expense>
data={isResponseSuccess(expenses) ? expenses?.data : []}
columns={expensesColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(expenses) ? expenses?.meta?.page : 0}
totalItems={
isResponseSuccess(expenses) ? expenses?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
rowSelection={rowSelection}
setRowSelection={setRowSelection}
enableRowSelection={tableEnableRowSelectionHandler}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(expenses) && expenses?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(expenses) || expenses.data?.length === 0 ? (
<div className='p-3'>
<ExpenseTableSkeleton
columns={expensesColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Expense>
data={isResponseSuccess(expenses) ? expenses?.data : []}
columns={expensesColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(expenses) ? expenses?.meta?.page : 0}
totalItems={
isResponseSuccess(expenses) ? expenses?.meta?.total_results : 0
}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
rowSelection={rowSelection}
setRowSelection={setRowSelection}
enableRowSelection={tableEnableRowSelectionHandler}
className={{
containerClassName: cn('p-3 mb-0'),
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -831,6 +803,12 @@ const ExpensesTable = () => {
onClick: confirmationModalRejectClickHandler,
}}
/>
<ExpensesFilterModal
ref={filterModal.ref}
onSubmit={handleFilterSubmit}
onReset={handleFilterReset}
/>
</>
);
};
@@ -0,0 +1,28 @@
import * as yup from 'yup';
export type ExpensesFilterType = {
transaction_date: string | null;
realization_date: string | null;
location_id: string | null;
vendor_id: string | null;
};
export const ExpensesFilterSchema = yup.object({
transaction_date: yup.string().nullable(),
realization_date: yup
.string()
.nullable()
.test(
'is-greater-or-equal-transaction',
'Tanggal realisasi tidak boleh sebelum tanggal transaksi',
function (value) {
const { transaction_date } = this.parent;
if (!transaction_date || !value) return true;
return new Date(value) >= new Date(transaction_date);
}
),
location_id: yup.string().nullable(),
vendor_id: yup.string().nullable(),
});
export type ExpensesFilterValues = yup.InferType<typeof ExpensesFilterSchema>;
@@ -0,0 +1,209 @@
'use client';
import { RefObject } from 'react';
import { useFormik } from 'formik';
import { Icon } from '@iconify/react';
import Modal from '@/components/Modal';
import Button from '@/components/Button';
import DateInput from '@/components/input/DateInput';
import SelectInput from '@/components/input/SelectInput';
import { OptionType, useSelect } from '@/components/input/SelectInput';
import { LocationApi, SupplierApi } from '@/services/api/master-data';
import { Location } from '@/types/api/master-data/location';
import { Supplier } from '@/types/api/master-data/supplier';
import {
ExpensesFilterSchema,
ExpensesFilterValues,
} from '@/components/pages/expense/filter/ExpensesFilter';
interface ExpensesFilterModalProps {
ref: RefObject<HTMLDialogElement | null>;
initialValues?: ExpensesFilterValues;
onSubmit?: (values: Partial<ExpensesFilterValues>) => void;
onReset?: () => void;
}
const ExpensesFilterModal = ({
ref,
initialValues,
onSubmit,
onReset,
}: ExpensesFilterModalProps) => {
const closeModalHandler = () => {
ref.current?.close();
};
const {
setInputValue: setLocationInputValue,
options: locationOptions,
isLoadingOptions: isLoadingLocationOptions,
} = useSelect<Location>(LocationApi.basePath, 'id', 'name');
const {
setInputValue: setVendorInputValue,
options: vendorOptions,
isLoadingOptions: isLoadingVendorOptions,
} = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name');
const formik = useFormik<ExpensesFilterValues>({
initialValues: initialValues || {
transaction_date: null,
realization_date: null,
location_id: null,
vendor_id: null,
},
validationSchema: ExpensesFilterSchema,
onSubmit: async (values) => {
onSubmit?.(values);
closeModalHandler();
},
onReset: () => {
onReset?.();
closeModalHandler();
},
});
const locationValue = formik.values.location_id
? locationOptions.find(
(opt) => String(opt.value) === formik.values.location_id
) || null
: null;
const vendorValue = formik.values.vendor_id
? vendorOptions.find(
(opt) => String(opt.value) === formik.values.vendor_id
) || null
: null;
const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
const locationId =
val && !Array.isArray(val) ? (String(val.value) as string) : null;
formik.setFieldValue('location_id', locationId);
};
const vendorChangeHandler = (val: OptionType | OptionType[] | null) => {
const vendorId =
val && !Array.isArray(val) ? (String(val.value) as string) : null;
formik.setFieldValue('vendor_id', vendorId);
};
return (
<Modal
ref={ref}
className={{
modalBox: 'p-0 rounded-xl xl:max-w-4/12 max-w-sm',
}}
>
<form
onSubmit={formik.handleSubmit}
onReset={formik.handleReset}
className='w-full flex flex-col'
>
{/* Modal Header */}
<div className='p-4 flex items-center justify-between gap-2 border-b border-base-content/10'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='text-sm font-medium'>Filter Data</h3>
</div>
<Button
type='button'
variant='ghost'
color='none'
onClick={closeModalHandler}
className='p-0 text-base-content/50 hover:text-base-content'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
{/* Modal Body */}
<div className='p-4 flex flex-col gap-1.5'>
<div className='flex flex-col'>
<span className='py-2 text-xs font-semibold'>Tanggal</span>
<div className='flex flex-row items-center gap-1.5'>
<DateInput
name='transaction_date'
placeholder='Tanggal Transaksi'
value={formik.values.transaction_date || ''}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={
formik.touched.transaction_date &&
!!formik.errors.transaction_date
}
/>
<hr className='w-full max-w-3 h-px border-base-content/10' />
<DateInput
name='realization_date'
placeholder='Tanggal Realisasi'
value={formik.values.realization_date || ''}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
isError={
formik.touched.realization_date &&
!!formik.errors.realization_date
}
/>
</div>
{formik.touched.realization_date &&
formik.errors.realization_date && (
<span className='text-xs text-error'>
{formik.errors.realization_date}
</span>
)}
</div>
<SelectInput
label='Lokasi'
placeholder='Pilih Lokasi'
options={locationOptions}
value={locationValue}
onChange={locationChangeHandler}
onInputChange={setLocationInputValue}
isLoading={isLoadingLocationOptions}
isClearable
isSearchable={true}
className={{ wrapper: 'w-full' }}
/>
<SelectInput
label='Vendor'
placeholder='Pilih Vendor'
options={vendorOptions}
value={vendorValue}
onChange={vendorChangeHandler}
onInputChange={setVendorInputValue}
isLoading={isLoadingVendorOptions}
isClearable
isSearchable={true}
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='p-4 flex justify-between gap-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='reset'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
);
};
export default ExpensesFilterModal;
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
@@ -75,6 +75,12 @@ const ExpenseKandangsTable = ({
.filter((id): id is number => id !== undefined)
)
);
const rowSelectionRef = useRef(rowSelection);
const prevRowSelectionRef = useRef<Record<string, boolean>>({});
useEffect(() => {
rowSelectionRef.current = rowSelection;
}, [rowSelection]);
const kandangsColumns: ColumnDef<Kandang>[] = [
{
@@ -133,33 +139,43 @@ const ExpenseKandangsTable = ({
useEffect(() => {
setOpen(isResponseSuccess(kandangs) ? kandangs.data.length > 0 : false);
}, [kandangs, isResponseSuccess]);
}, [kandangs]);
useEffect(() => {
if (Object.keys(rowSelection).length !== 0 && isResponseSuccess(kandangs)) {
const formattedSelectedKandangs = Object.keys(rowSelection).map(
(item) => {
const selectedKandang = kandangs.data.find(
(kandang) => kandang.id === parseInt(item)
);
const currentKeys = Object.keys(rowSelection).sort().join(',');
const prevKeys = Object.keys(prevRowSelectionRef.current).sort().join(',');
return {
id: parseInt(item),
name: selectedKandang?.name ?? 'Kandang tidak ditemukan!',
};
}
);
if (currentKeys !== prevKeys) {
prevRowSelectionRef.current = { ...rowSelection };
onChange(formattedSelectedKandangs);
} else {
onChange([]);
if (
Object.keys(rowSelection).length !== 0 &&
isResponseSuccess(kandangs)
) {
const formattedSelectedKandangs = Object.keys(rowSelection).map(
(item) => {
const selectedKandang = kandangs.data.find(
(kandang) => kandang.id === parseInt(item)
);
return {
id: parseInt(item),
name: selectedKandang?.name ?? 'Kandang tidak ditemukan!',
};
}
);
onChange(formattedSelectedKandangs);
} else if (Object.keys(rowSelection).length === 0) {
onChange([]);
}
}
}, [rowSelection]);
}, [rowSelection, kandangs, onChange]);
useEffect(() => {
if (
selectedKandangs.length === 0 &&
Object.keys(rowSelection).length !== 0
Object.keys(rowSelectionRef.current).length !== 0
) {
setRowSelection({});
}
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useFormik } from 'formik';
import toast from 'react-hot-toast';
@@ -90,6 +90,7 @@ const ExpenseRealizationForm = ({
const formik = useFormik<ExpenseRealizationFormValues>({
initialValues: getExpenseRealizationFormInitialValues(initialValues),
enableReinitialize: true,
validationSchema:
type === 'edit'
? UpdateExpenseRealizationFormSchema
@@ -143,7 +144,6 @@ const ExpenseRealizationForm = ({
},
});
const { setValues: formikSetValues } = formik;
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
const {
@@ -254,10 +254,6 @@ const ExpenseRealizationForm = ({
formik.setFieldValue('documents', newRequestDocuments);
};
useEffect(() => {
formikSetValues(getExpenseRealizationFormInitialValues(initialValues));
}, [formikSetValues, getExpenseRealizationFormInitialValues, initialValues]);
return (
<section className='w-full'>
<header className='flex flex-col gap-4'>
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useFormik } from 'formik';
import { toast } from 'react-hot-toast';
@@ -102,6 +102,7 @@ const ExpenseRequestForm = ({
const formik = useFormik<ExpenseRequestFormValues>({
initialValues: getExpenseFormInitialValues(initialValues),
enableReinitialize: true,
validationSchema:
type === 'edit'
? UpdateExpenseRequestFormSchema
@@ -171,7 +172,7 @@ const ExpenseRequestForm = ({
},
});
const { setValues: formikSetValues } = formik;
const { setFieldValue, setFieldTouched } = formik;
const {
setInputValue: setLocationInputValue,
@@ -186,8 +187,8 @@ const ExpenseRequestForm = ({
} = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name');
const categoryChangeHandler = (val: OptionType | OptionType[] | null) => {
formik.setFieldTouched('category', true);
formik.setFieldValue('category', val);
setFieldTouched('category', true);
setFieldValue('category', val);
};
const locationChangeHandler = useCallback(
@@ -195,12 +196,12 @@ const ExpenseRequestForm = ({
const location = val as OptionType | null;
const locationId = location ? Number(location.value) : 0;
formik.setFieldTouched('location', true);
formik.setFieldValue('location', location);
formik.setFieldTouched('location_id', true);
formik.setFieldValue('location_id', locationId);
setFieldTouched('location', true);
setFieldValue('location', location);
setFieldTouched('location_id', true);
setFieldValue('location_id', locationId);
},
[]
[setFieldTouched, setFieldValue]
);
const kandangsChangeHandler = (
@@ -343,10 +344,6 @@ const ExpenseRequestForm = ({
formik.handleSubmit(e);
};
useEffect(() => {
formikSetValues(getExpenseFormInitialValues(initialValues));
}, [formikSetValues, getExpenseFormInitialValues, initialValues]);
return (
<>
<section className='w-full'>
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Expense } from '@/types/api/expense';
import { ColumnDef } from '@tanstack/react-table';
const ExpenseTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no expense data displayed. Enter expense data to get started.',
}: {
columns: ColumnDef<Expense>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default ExpenseTableSkeleton;
+20 -15
View File
@@ -2,7 +2,6 @@ import Button from '@/components/Button';
import Card from '@/components/Card';
import { FormHeader } from '@/components/helper/form/FormHeader';
import RequirePermission from '@/components/helper/RequirePermission';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import Table from '@/components/Table';
@@ -26,11 +25,13 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
const informasiUmum = [
{
label: 'ID',
value: finance.payment_code,
value: finance.payment_code || '-',
},
{
label: 'Jenis Transaksi',
value: formatTitleCase(finance.transaction_type.split('_').join(' ')),
value: formatTitleCase(
(finance.transaction_type || '').split('_').join(' ')
),
},
{
label: 'Pihak',
@@ -38,11 +39,13 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
},
{
label: 'Tanggal',
value: formatDate(finance.payment_date, 'DD MMM yyyy'),
value: finance.payment_date
? formatDate(finance.payment_date, 'DD MMM yyyy')
: '-',
},
{
label: 'Metode Pembayaran',
value: finance.payment_method,
value: finance.payment_method || '-',
},
{
label: 'Catatan',
@@ -61,22 +64,22 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
: '-',
},
{
label: `Rekening ${formatTitleCase(finance.party?.type)}`,
value: finance.party?.account_number,
label: `Rekening ${formatTitleCase(finance.party?.type || '')}`,
value: finance.party?.account_number || '-',
},
{
label: 'Nominal',
value: formatCurrency(
finance.transaction_type === 'INJECTION'
? finance.nominal
: Math.abs(finance.nominal)
? finance.nominal || 0
: Math.abs(finance.nominal || 0)
),
},
].filter((item) => {
// Hide party account number row if transaction type is INJECTION
if (
FINANCE_INJECTION_STATUS.includes(finance.transaction_type) &&
item.label === `Rekening ${formatTitleCase(finance.party?.type)}`
FINANCE_INJECTION_STATUS.includes(finance.transaction_type || '') &&
item.label === `Rekening ${formatTitleCase(finance.party?.type || '')}`
) {
return false;
}
@@ -150,7 +153,7 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
</Card>
<div className='flex flex-row gap-2 justify-end'>
{FINANCE_TRANSACTION_STATUS.includes(finance.transaction_type) &&
{FINANCE_TRANSACTION_STATUS.includes(finance.transaction_type || '') &&
finance.party?.type !== 'SUPPLIER' && (
<RequirePermission permissions='lti.finance.payments.update'>
<Button
@@ -163,7 +166,9 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
</Button>
</RequirePermission>
)}
{FINANCE_INITIAL_BALANCE_STATUS.includes(finance.transaction_type) && (
{FINANCE_INITIAL_BALANCE_STATUS.includes(
finance.transaction_type || ''
) && (
<RequirePermission permissions='lti.finance.initial_balances.update'>
<Button
color='warning'
@@ -175,7 +180,7 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
</Button>
</RequirePermission>
)}
{FINANCE_INJECTION_STATUS.includes(finance.transaction_type) && (
{FINANCE_INJECTION_STATUS.includes(finance.transaction_type || '') && (
<RequirePermission permissions='lti.finance.injections.update'>
<Button
color='warning'
@@ -201,7 +206,7 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Finance ini (${finance?.payment_code})?`}
text={`Apakah anda yakin ingin menghapus data Finance ini (${finance?.payment_code || ''})?`}
secondaryButton={{
text: 'Tidak',
}}
+471 -270
View File
@@ -1,10 +1,19 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { CellContext } from '@tanstack/react-table';
'use client';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { CellContext, ColumnDef } from '@tanstack/react-table';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
import { useFormik } from 'formik';
import { cn, formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
import Button from '@/components/Button';
import Card from '@/components/Card';
import DateInput from '@/components/input/DateInput';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, {
@@ -12,7 +21,6 @@ import SelectInput, {
useSelect,
} from '@/components/input/SelectInput';
import Table from '@/components/Table';
import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { Finance } from '@/types/api/finance/finance';
import {
@@ -25,115 +33,145 @@ import { FinanceApi } from '@/services/api/finance';
import { isResponseSuccess } from '@/lib/api-helper';
import { BankApi, CustomerApi, SupplierApi } from '@/services/api/master-data';
import { Bank } from '@/types/api/master-data/bank';
import { useModal } from '@/components/Modal';
import Modal, { useModal } from '@/components/Modal';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import toast from 'react-hot-toast';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import { Icon } from '@iconify/react';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import { useUiStore } from '@/stores/ui/ui.store';
import {
FinanceTableFilterSchema,
FinanceTableFilterValues,
} from './FinanceTableFilter.schema';
} from '@/components/pages/finance/filter/FinanceFilter';
import FinanceTableSkeleton from '@/components/pages/finance/skeleton/FinanceTableSkeleton';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Finance, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `finance#${props.row.original.id}`;
const popoverAnchorName = `--anchor-finance#${props.row.original.id}`;
const closePopover = () => {
const popover = document.getElementById(popoverId) as
| HTMLDivElement
| undefined;
popover?.hidePopover?.();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission
permissions={[
'lti.finance.transactions.detail',
'lti.finance.initial_balances.detail',
'lti.finance.injections.detail',
'lti.finance.payments.detail',
]}
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Button
href={`/finance/detail?financeId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
{FINANCE_TRANSACTION_STATUS.includes(
props.row.original.transaction_type
) && (
<RequirePermission permissions='lti.finance.payments.update'>
<Button
href={`/finance/detail/edit?financeId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission
permissions={[
'lti.finance.transactions.detail',
'lti.finance.initial_balances.detail',
'lti.finance.injections.detail',
'lti.finance.payments.detail',
]}
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
)}
<Button
href={`/finance/detail?financeId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
{FINANCE_INITIAL_BALANCE_STATUS.includes(
props.row.original.transaction_type
) && (
<RequirePermission permissions='lti.finance.initial_balances.update'>
<Button
href={`/finance/detail/edit/initial-balance?financeId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
)}
{FINANCE_TRANSACTION_STATUS.includes(
props.row.original.transaction_type
) && (
<RequirePermission permissions='lti.finance.payments.update'>
<Button
href={`/finance/detail/edit?financeId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='mdi:pencil-outline' width={20} height={20} />
Edit
</Button>
</RequirePermission>
)}
{FINANCE_INJECTION_STATUS.includes(
props.row.original.transaction_type
) && (
<RequirePermission permissions='lti.finance.injections.update'>
<Button
href={`/finance/detail/edit/injection?financeId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
)}
{FINANCE_INITIAL_BALANCE_STATUS.includes(
props.row.original.transaction_type
) && (
<RequirePermission permissions='lti.finance.initial_balances.update'>
<Button
href={`/finance/detail/edit/initial-balance?financeId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='mdi:pencil-outline' width={20} height={20} />
Edit
</Button>
</RequirePermission>
)}
<RequirePermission permissions='lti.finance.transactions.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='text-error hover:text-inherit'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
{FINANCE_INJECTION_STATUS.includes(
props.row.original.transaction_type
) && (
<RequirePermission permissions='lti.finance.injections.update'>
<Button
href={`/finance/detail/edit/injection?financeId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='mdi:pencil-outline' width={20} height={20} />
Edit
</Button>
</RequirePermission>
)}
<RequirePermission permissions='lti.finance.transactions.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='error'
className='p-3 justify-start text-sm font-semibold w-full focus-visible:text-error-content hover:text-error-content'
>
<Icon icon='mdi:delete-outline' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
@@ -171,6 +209,9 @@ const FinanceTable = () => {
},
});
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== State =====
const deleteModal = useModal();
const [selectedTransactionType, setSelectedTransactionType] = useState<
@@ -189,6 +230,7 @@ const FinanceTable = () => {
const [selectedFinance, setSelectedFinance] = useState<Finance | null>(null);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [dateErrorShown, setDateErrorShown] = useState(false);
const [hasDateError, setHasDateError] = useState(false);
// ===== Formik for Filter =====
const filterFormik = useFormik<FinanceTableFilterValues>({
@@ -214,6 +256,18 @@ const FinanceTable = () => {
updateFilter('sortBy', values.sort_by);
updateFilter('startDate', values.start_date);
updateFilter('endDate', values.end_date);
filterModal.closeModal();
},
onReset: () => {
updateFilter('search', '');
resetSearchValue();
updateFilter('transactionTypes', '');
updateFilter('bankIds', '');
updateFilter('customerIds', '');
updateFilter('supplierIds', '');
updateFilter('sortBy', '');
updateFilter('startDate', '');
updateFilter('endDate', '');
},
});
@@ -266,10 +320,41 @@ const FinanceTable = () => {
});
}, [bankOptions, bankRawData]);
// ===== ACTIVE FILTERS COUNT =====
const activeFiltersCount = useMemo(() => {
let count = 0;
if (tableFilterState.transactionTypes) count += 1;
if (tableFilterState.bankIds) count += 1;
if (tableFilterState.customerIds) count += 1;
if (tableFilterState.supplierIds) count += 1;
if (tableFilterState.sortBy) count += 1;
if (tableFilterState.startDate) count += 1;
if (tableFilterState.endDate) count += 1;
return count;
}, [
tableFilterState.transactionTypes,
tableFilterState.bankIds,
tableFilterState.customerIds,
tableFilterState.supplierIds,
tableFilterState.sortBy,
tableFilterState.startDate,
tableFilterState.endDate,
]);
const hasFilters = activeFiltersCount > 0;
// ===== Handler =====
const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
filterFormik.setFieldValue('search', e.target.value);
};
const searchChangeHandler = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
updateFilter('search', e.target.value);
setSearchValue(e.target.value);
setPage(1);
},
[updateFilter, setSearchValue, setPage]
);
const transactionTypeChangeHandler = (
val: OptionType | OptionType[] | null
) => {
@@ -335,10 +420,7 @@ const FinanceTable = () => {
const endDateObj = new Date(endDate);
if (endDateObj < startDate) {
filterFormik.setFieldError(
'end_date',
'Tanggal akhir tidak boleh masa lampau'
);
setHasDateError(true);
if (!dateErrorShown) {
toast.error('Tanggal akhir tidak boleh masa lampau', {
duration: Infinity,
@@ -346,12 +428,14 @@ const FinanceTable = () => {
setDateErrorShown(true);
}
} else {
filterFormik.setFieldError('end_date', undefined);
setHasDateError(false);
if (dateErrorShown) {
toast.dismiss();
setDateErrorShown(false);
}
}
} else {
setHasDateError(false);
}
};
@@ -366,10 +450,7 @@ const FinanceTable = () => {
const endDate = new Date(value);
if (endDate < startDateObj) {
filterFormik.setFieldError(
'end_date',
'Tanggal akhir tidak boleh masa lampau'
);
setHasDateError(true);
if (!dateErrorShown) {
toast.error('Tanggal akhir tidak boleh masa lampau', {
duration: Infinity,
@@ -380,13 +461,18 @@ const FinanceTable = () => {
}
}
filterFormik.setFieldError('end_date', undefined);
setHasDateError(false);
if (dateErrorShown) {
toast.dismiss();
setDateErrorShown(false);
}
};
const handleFilterModalOpen = () => {
filterModal.openModal();
filterFormik.validateForm();
};
const resetFilterHandler = () => {
setSelectedTransactionType(null);
setSelectedBank(null);
@@ -406,6 +492,7 @@ const FinanceTable = () => {
updateFilter('startDate', '');
updateFilter('endDate', '');
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -417,8 +504,8 @@ const FinanceTable = () => {
setIsDeleteLoading(false);
};
const columns = useMemo(() => {
return [
const columns: ColumnDef<Finance>[] = useMemo(
() => [
{
header: 'ID',
accessorKey: 'payment_code',
@@ -498,32 +585,17 @@ const FinanceTable = () => {
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
<RowOptionsMenu
props={props}
deleteClickHandler={deleteClickHandler}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
/>
);
},
},
];
}, []);
],
[deleteModal]
);
useEffect(() => {
return () => {
@@ -555,151 +627,280 @@ const FinanceTable = () => {
}, [resetSearchValue, dateErrorShown]);
return (
<section className='size-full flex flex-col gap-6'>
<div className='flex justify-end gap-2'>
<RequirePermission permissions='lti.finance.injections.create'>
<Button
color='warning'
className='min-w-24'
href='/finance/add/injection'
>
Injection Saldo Bank
</Button>
</RequirePermission>
<RequirePermission permissions='lti.finance.initial_balances.create'>
<Button
color='info'
className='text-white min-w-24'
href='/finance/add/initial-balance'
>
Saldo Awal
</Button>
</RequirePermission>
<RequirePermission permissions='lti.finance.payments.create'>
<Button color='primary' className='min-w-24' href='/finance/add'>
Tambah
</Button>
</RequirePermission>
</div>
<Card
variant='bordered'
className={{
wrapper: 'w-full',
}}
footer={
<div className='flex justify-end gap-2'>
<>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.finance.injections.create'>
<Button
href='/finance/add/injection'
color='warning'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='mdi:bank-transfer-in' width={20} height={20} />
Add Injection (Saldo Bank)
</Button>
</RequirePermission>
<RequirePermission permissions='lti.finance.initial_balances.create'>
<Button
href='/finance/add/initial-balance'
color='info'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='mdi:cash-register' width={20} height={20} />
Add Initial Balance
</Button>
</RequirePermission>
<RequirePermission permissions='lti.finance.payments.create'>
<Button
href='/finance/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Finance
</Button>
</RequirePermission>
</div>
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
/>
<Button
color='warning'
className='min-w-24'
onClick={resetFilterHandler}
variant='outline'
color='none'
onClick={handleFilterModalOpen}
className={cn(
'px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft transition-all',
{
'border-primary-gradient text-primary': hasFilters,
}
)}
>
Reset
</Button>
<Button
color='primary'
className='min-w-24'
onClick={() => filterFormik.handleSubmit()}
>
Cari
<Icon icon='heroicons:funnel' width={20} height={20} />
Filter
{hasFilters && (
<span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
{activeFiltersCount}
</span>
)}
</Button>
</div>
}
>
<div className='grid grid-cols-4 gap-6'>
<SelectInput
options={FINANCE_TRANSACTION_TYPE_OPTIONS}
label='Jenis Transaksi'
value={selectedTransactionType}
onChange={transactionTypeChangeHandler}
closeMenuOnSelect={false}
isClearable
isMulti
/>
<SelectInput
options={customerOptions}
label={'Customer'}
value={selectedCustomerId}
onChange={customerIdChangeHandler}
onInputChange={customerInputValue}
onMenuScrollToBottom={customerLoadMore}
isLoading={customerIsLoadingOptions}
closeMenuOnSelect={false}
isClearable
isMulti
/>
<SelectInput
options={supplierOptions}
label={'Supplier'}
value={selectedSupplierId}
onChange={supplierIdChangeHandler}
onInputChange={supplierInputValue}
onMenuScrollToBottom={supplierLoadMore}
isLoading={supplierIsLoadingOptions}
closeMenuOnSelect={false}
isClearable
isMulti
/>
<SelectInput
options={bankSelectOptions}
label='Bank'
value={selectedBank}
onChange={bankChangeHandler}
onInputChange={bankInputValue}
onMenuScrollToBottom={bankLoadMore}
closeMenuOnSelect={false}
isClearable
isMulti
/>
<SelectInput
options={sortByOptions}
label='Urutkan Berdasarkan'
value={selectedSortBy}
onChange={sortByChangeHandler}
isClearable
/>
<DateInput
name='start_date'
label='Periode Tanggal (Mulai)'
value={filterFormik.values.start_date}
onChange={startDateChangeHandler}
errorMessage={
filterFormik.errors.end_date
? filterFormik.errors.end_date
: undefined
}
/>
<DateInput
name='end_date'
label='Periode Tanggal (Akhir)'
value={filterFormik.values.end_date}
onChange={endDateChangeHandler}
errorMessage={
filterFormik.errors.end_date
? filterFormik.errors.end_date
: undefined
}
/>
<DebouncedTextInput
name='search'
label='Cari'
placeholder='Cari'
value={filterFormik.values.search}
onChange={searchChangeHandler}
/>
</div>
</Card>
<Table<Finance>
data={isResponseSuccess(finances) ? finances.data : []}
columns={columns}
pageSize={tableFilterState.pageSize}
page={tableFilterState.page}
onPageChange={setPage}
onPageSizeChange={setPageSize}
totalItems={
isResponseSuccess(finances) ? finances.meta?.total_results : 0
}
isLoading={isLoading}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(finances) || finances.data?.length === 0 ? (
<div className='p-3'>
<FinanceTableSkeleton
columns={columns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Finance>
data={isResponseSuccess(finances) ? finances.data : []}
columns={columns}
pageSize={tableFilterState.pageSize}
page={tableFilterState.page}
totalItems={
isResponseSuccess(finances) ? finances.meta?.total_results : 0
}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={isLoading}
className={{
containerClassName: cn('p-3 mb-0'),
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form
onSubmit={filterFormik.handleSubmit}
onReset={filterFormik.handleReset}
>
<div className='p-4 flex flex-col gap-1.5'>
<div className='flex flex-col'>
<span className='py-2 text-xs font-semibold'>Tanggal</span>
<div className='flex flex-row items-center gap-1.5'>
<DateInput
name='start_date'
placeholder='Periode Tanggal Awal'
value={filterFormik.values.start_date}
errorMessage={filterFormik.errors.start_date}
onChange={startDateChangeHandler}
isError={
filterFormik.touched.start_date &&
Boolean(filterFormik.errors.start_date)
}
/>
<hr className='w-full max-w-3 h-px border-base-content/10' />
<DateInput
name='end_date'
placeholder='Periode Tanggal Akhir'
value={filterFormik.values.end_date}
errorMessage={filterFormik.errors.end_date}
onChange={endDateChangeHandler}
isError={
(filterFormik.touched.end_date &&
Boolean(filterFormik.errors.end_date)) ||
hasDateError
}
/>
</div>
</div>
<SelectInput
options={FINANCE_TRANSACTION_TYPE_OPTIONS}
label='Jenis Transaksi'
placeholder='Pilih Jenis Transaksi'
value={selectedTransactionType}
onChange={transactionTypeChangeHandler}
onInputChange={() => {}}
closeMenuOnSelect={false}
isClearable
isMulti
className={{ wrapper: 'w-full' }}
/>
<SelectInput
options={customerOptions}
label='Customer'
placeholder='Pilih Customer'
value={selectedCustomerId}
onChange={customerIdChangeHandler}
onInputChange={customerInputValue}
onMenuScrollToBottom={customerLoadMore}
isLoading={customerIsLoadingOptions}
closeMenuOnSelect={false}
isClearable
isMulti
className={{ wrapper: 'w-full' }}
/>
<SelectInput
options={supplierOptions}
label='Supplier'
placeholder='Pilih Supplier'
value={selectedSupplierId}
onChange={supplierIdChangeHandler}
onInputChange={supplierInputValue}
onMenuScrollToBottom={supplierLoadMore}
isLoading={supplierIsLoadingOptions}
closeMenuOnSelect={false}
isClearable
isMulti
className={{ wrapper: 'w-full' }}
/>
<SelectInput
options={bankSelectOptions}
label='Bank'
placeholder='Pilih Bank'
value={selectedBank}
onChange={bankChangeHandler}
onInputChange={bankInputValue}
onMenuScrollToBottom={bankLoadMore}
closeMenuOnSelect={false}
isClearable
isMulti
className={{ wrapper: 'w-full' }}
/>
<SelectInput
options={sortByOptions}
label='Urutkan Berdasarkan'
placeholder='Pilih Urutan'
value={selectedSortBy}
onChange={sortByChangeHandler}
isClearable
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
filterFormik.resetForm();
setSelectedTransactionType(null);
setSelectedBank(null);
setSelectedCustomerId(null);
setSelectedSupplierId(null);
setSelectedSortBy(null);
resetFilterHandler();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!filterFormik.isValid || filterFormik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
@@ -714,7 +915,7 @@ const FinanceTable = () => {
onClick: confirmationModalDeleteClickHandler,
}}
/>
</section>
</>
);
};
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Finance } from '@/types/api/finance/finance';
import { ColumnDef } from '@tanstack/react-table';
const FinanceTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no finance data displayed. Enter finance data to get started.',
}: {
columns: ColumnDef<Finance>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default FinanceTableSkeleton;
@@ -1,22 +1,48 @@
'use client';
import Badge from '@/components/Badge';
import Button from '@/components/Button';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import Table from '@/components/Table';
import RequirePermission from '@/components/helper/RequirePermission';
import { ROWS_OPTIONS } from '@/config/constant';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn } from '@/lib/helper';
import { InventoryAdjustmentApi } from '@/services/api/inventory';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { InventoryAdjustment } from '@/types/api/inventory/adjustment';
import {
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
import { ColumnDef, ColumnSort, SortingState } from '@tanstack/react-table';
import { useCallback, useEffect, useState } from 'react';
import useSWR from 'swr';
import { useFormik } from 'formik';
import Button from '@/components/Button';
import Table from '@/components/Table';
import RequirePermission from '@/components/helper/RequirePermission';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';
import Modal, { useModal } from '@/components/Modal';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn, formatNumber, formatDate, formatCurrency } from '@/lib/helper';
import { InventoryAdjustmentApi } from '@/services/api/inventory';
import { WarehouseApi, ProductApi } from '@/services/api/master-data';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { useUiStore } from '@/stores/ui/ui.store';
import { InventoryAdjustment } from '@/types/api/inventory/adjustment';
import { Warehouse } from '@/types/api/master-data/warehouse';
import { TRANSACTION_SUBTYPE_OPTIONS } from '@/config/constant';
import { Product } from '@/types/api/master-data/product';
import StatusBadge from '@/components/helper/StatusBadge';
import InventoryAdjustmentTableSkeleton from '@/components/pages/inventory/adjustment/skeleton/InventoryAdjustmentTableSkeleton';
import {
AdjustmentFilterSchema,
AdjustmentFilterType,
} from '@/components/pages/inventory/adjustment/filter/AdjustmentFilter';
import SelectInputRadio from '@/components/input/SelectInputRadio';
const InventoryAdjustmentTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -30,6 +56,9 @@ const InventoryAdjustmentTable = () => {
productSort: '',
warehouseSort: '',
stockSort: '',
productFilter: '',
warehouseFilter: '',
transactionTypeFilter: '',
},
paramMap: {
page: 'page',
@@ -38,84 +67,257 @@ const InventoryAdjustmentTable = () => {
productSort: 'sort_product',
warehouseSort: 'sort_warehouse',
stockSort: 'sort_stock',
productFilter: 'product_id',
warehouseFilter: 'warehouse_id',
transactionTypeFilter: 'transaction_type',
},
});
// Fetch Data
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FORMIK SETUP =====
const formik = useFormik<AdjustmentFilterType>({
initialValues: {
product_id: null,
warehouse_id: null,
transaction_type: null,
},
validationSchema: AdjustmentFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('productFilter', values.product_id || '');
updateFilter('warehouseFilter', values.warehouse_id || '');
updateFilter('transactionTypeFilter', values.transaction_type || '');
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('productFilter', '');
updateFilter('warehouseFilter', '');
updateFilter('transactionTypeFilter', '');
},
});
// ===== PRODUCT OPTIONS =====
const {
setInputValue: setProductInputValue,
options: productOptions,
isLoadingOptions: isLoadingProductOptions,
loadMore: loadMoreProducts,
} = useSelect<Product>(
filterModal.open ? ProductApi.basePath : null,
'id',
'name',
'search'
);
// ===== WAREHOUSE OPTIONS =====
const {
setInputValue: setWarehouseInputValue,
options: warehouseOptions,
isLoadingOptions: isLoadingWarehouseOptions,
loadMore: loadMoreWarehouses,
} = useSelect<Warehouse>(
filterModal.open ? WarehouseApi.basePath : null,
'id',
'name',
'search'
);
// ===== TRANSACTION TYPE OPTIONS =====
const transactionTypeOptions = useMemo(() => {
return [
{ value: 'increase', label: 'Increase' },
{ value: 'decrease', label: 'Decrease' },
];
}, []);
// ===== FILTER HANDLERS =====
const handleFilterProductChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const product = val as OptionType | null;
const productId = product?.value ? String(product.value) : null;
formik.setFieldValue('product_id', productId);
},
[formik]
);
const handleFilterWarehouseChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const warehouse = val as OptionType | null;
const warehouseId = warehouse?.value ? String(warehouse.value) : null;
formik.setFieldValue('warehouse_id', warehouseId);
},
[formik]
);
const handleFilterTransactionTypeChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const type = val as OptionType | null;
const typeValue = type?.value ? String(type.value) : null;
formik.setFieldValue('transaction_type', typeValue);
},
[formik]
);
// ===== FILTER HELPERS =====
const productIdValue = useMemo(() => {
if (!formik.values.product_id) return null;
return (
productOptions.find(
(opt) => String(opt.value) === formik.values.product_id
) || null
);
}, [formik.values.product_id, productOptions]);
const warehouseIdValue = useMemo(() => {
if (!formik.values.warehouse_id) return null;
return (
warehouseOptions.find(
(opt) => String(opt.value) === formik.values.warehouse_id
) || null
);
}, [formik.values.warehouse_id, warehouseOptions]);
const transactionTypeValue = useMemo(() => {
if (!formik.values.transaction_type) return null;
return (
transactionTypeOptions.find(
(opt) => String(opt.value) === formik.values.transaction_type
) || null
);
}, [formik.values.transaction_type, transactionTypeOptions]);
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
filterModal.openModal();
formik.validateForm();
};
const { data: inventoryAdjustments, isLoading } = useSWR(
`${InventoryAdjustmentApi.basePath}${getTableFilterQueryString()}`,
InventoryAdjustmentApi.getAllFetcher
);
// State
const [sorting, setSorting] = useState<SortingState>([]);
// Columns
const inventoryAdjustmentsColumns: ColumnDef<InventoryAdjustment>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
id: 'product_name',
header: 'Nama Produk',
accessorFn: (row) => row.product_warehouse?.product?.name ?? '-',
},
{
id: 'warehouse_name',
header: 'Gudang',
accessorFn: (row) => row.product_warehouse?.warehouse?.name ?? '-',
},
{
id: 'created_at',
header: 'Tanggal',
accessorFn: (row) =>
new Date(row.created_at).toLocaleDateString('id-ID', {
day: '2-digit',
month: 'short',
year: 'numeric',
}),
},
{
id: 'quantity',
header: 'Kuantitas',
accessorFn: (row) => formatNumber(String(row.increase + row.decrease)),
},
{
id: 'transaction_type',
header: 'Tipe Transaksi',
accessorFn: (row) => {
if (row.increase > 0) return 'Peningkatan';
if (row.decrease > 0) return 'Penurunan';
return '-';
},
cell: (props) => {
const type = props.row.original.increase;
const label = type > 0 ? 'Peningkatan' : type <= 0 ? 'Penurunan' : '-';
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
return (
<Badge variant='soft' color={type > 0 ? 'success' : 'error'}>
{label}
</Badge>
);
},
},
{
id: 'created_by',
header: 'Oleh',
accessorFn: (row) => row.created_user?.name ?? '-',
},
];
useEffect(() => {
setTableState('inventory-adjustment-table', pathname);
}, [pathname, setTableState]);
// Handler
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const inventoryAdjustmentsColumns: ColumnDef<InventoryAdjustment>[] = useMemo(
() => [
{
id: 'adj_number',
header: 'No. Referensi',
accessorFn: (row) => row.adj_number ?? '-',
},
{
id: 'location',
header: 'Lokasi',
accessorFn: (row) => row.location?.name ?? '-',
},
{
id: 'project_flock',
header: 'Flock',
accessorFn: (row) => row.project_flock?.flock_name ?? '-',
},
{
id: 'warehouse_name',
header: 'Gudang',
accessorFn: (row) => row.product_warehouse?.warehouse?.name ?? '-',
},
{
id: 'product_name',
header: 'Nama Produk',
accessorFn: (row) => row.product_warehouse?.product?.name ?? '-',
},
{
id: 'quantity',
header: 'Kuantitas',
accessorFn: (row) => row.qty ?? '-',
cell: (row) => {
const value = row.row.original.increase + row.row.original.decrease;
return <div className='text-center'>{formatNumber(value)}</div>;
},
},
{
id: 'price',
header: 'Harga',
accessorFn: (row) => (row.price ? formatCurrency(row.price) : '-'),
},
{
id: 'grand_total',
header: 'Grand Total',
accessorFn: (row) =>
row.grand_total ? formatCurrency(row.grand_total) : '-',
},
{
id: 'transaction_type',
header: 'Tipe Transaksi',
accessorFn: (row) => row.transaction_subtype ?? '-',
cell: (row) => {
const subtype = row.row.original.transaction_subtype;
const increase = row.row.original.increase;
const getSubtypeLabel = (subtypeValue: string): string => {
if (subtypeValue === TRANSACTION_SUBTYPE_OPTIONS.PEMBELIAN.value) {
return TRANSACTION_SUBTYPE_OPTIONS.PEMBELIAN.label;
}
if (subtypeValue === TRANSACTION_SUBTYPE_OPTIONS.PENJUALAN.value) {
return TRANSACTION_SUBTYPE_OPTIONS.PENJUALAN.label;
}
const recordingOption = TRANSACTION_SUBTYPE_OPTIONS.RECORDING.find(
(opt) => opt.value === subtypeValue
);
if (recordingOption) {
return recordingOption.label;
}
if (subtypeValue === 'RECORDING_DEPLETION_OUT') {
return 'Recording Depletion';
}
return subtypeValue || '-';
};
const label = getSubtypeLabel(subtype);
return (
<StatusBadge
color={
increase > 0 ? 'success' : increase <= 0 ? 'error' : 'neutral'
}
text={label}
className={{
badge: 'whitespace-nowrap',
}}
/>
);
},
},
{
id: 'created_at',
header: 'Tanggal',
accessorFn: (row) =>
row.created_at ? formatDate(row.created_at, 'DD MMM YYYY') : '-',
},
{
id: 'created_by',
header: 'Oleh',
accessorFn: (row) => row.created_user?.name ?? '-',
},
],
[tableFilterState.pageSize, tableFilterState.page]
);
const updateSortingFilter = useCallback(
(
sortName: Exclude<keyof typeof tableFilterState, 'page' | 'pageSize'>,
@@ -130,7 +332,6 @@ const InventoryAdjustmentTable = () => {
[updateFilter]
);
// Effect
useEffect(() => {
const productCategorySortFilter = sorting.find(
(sortItem) => sortItem.id === 'productCategory'
@@ -149,88 +350,200 @@ const InventoryAdjustmentTable = () => {
updateSortingFilter('stockSort', stockSortFilter);
}, [sorting, updateSortingFilter]);
// Utils Function
const formatNumber = (value: string) => {
const numericValue = value.replace(/[^0-9.]/g, '');
const [integer, decimal] = numericValue.split('.');
const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return decimal ? `${formattedInteger}.${decimal}` : formattedInteger;
};
// Render
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.inventory.create'>
<Button
href='/inventory/adjustment/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'min-w-28' }}
/>
</div>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.inventory.create'>
<Button
href='/inventory/adjustment/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Adjustment
</Button>
</RequirePermission>
</div>
<Table<InventoryAdjustment>
data={
isResponseSuccess(inventoryAdjustments)
? inventoryAdjustments?.data
: []
}
columns={inventoryAdjustmentsColumns}
pageSize={tableFilterState.pageSize}
page={
isResponseSuccess(inventoryAdjustments)
? inventoryAdjustments?.meta?.page
: 0
}
totalItems={
isResponseSuccess(inventoryAdjustments)
? inventoryAdjustments?.meta?.total_results
: 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(inventoryAdjustments) &&
inventoryAdjustments?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
/>
<ButtonFilter
values={tableFilterState}
excludeFields={[
'page',
'pageSize',
'search',
'productCategorySort',
'productSort',
'warehouseSort',
'stockSort',
]}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(inventoryAdjustments) ||
inventoryAdjustments.data?.length === 0 ? (
<div className='p-3'>
<InventoryAdjustmentTableSkeleton
columns={inventoryAdjustmentsColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<InventoryAdjustment>
data={
isResponseSuccess(inventoryAdjustments)
? inventoryAdjustments?.data
: []
}
columns={inventoryAdjustmentsColumns}
pageSize={tableFilterState.pageSize}
page={
isResponseSuccess(inventoryAdjustments)
? inventoryAdjustments?.meta?.page
: 0
}
totalItems={
isResponseSuccess(inventoryAdjustments)
? inventoryAdjustments?.meta?.total_results
: 0
}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn('p-3 mb-0'),
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInput
label='Produk'
placeholder='Pilih Produk'
options={productOptions}
value={productIdValue}
onChange={handleFilterProductChange}
onInputChange={setProductInputValue}
isLoading={isLoadingProductOptions}
isClearable
onMenuScrollToBottom={loadMoreProducts}
className={{ wrapper: 'w-full' }}
/>
<SelectInput
label='Gudang'
placeholder='Pilih Gudang'
options={warehouseOptions}
value={warehouseIdValue}
onChange={handleFilterWarehouseChange}
onInputChange={setWarehouseInputValue}
isLoading={isLoadingWarehouseOptions}
isClearable
onMenuScrollToBottom={loadMoreWarehouses}
className={{ wrapper: 'w-full' }}
/>
<SelectInputRadio
label='Tipe Transaksi'
placeholder='Pilih Tipe Transaksi'
options={transactionTypeOptions}
value={transactionTypeValue}
onChange={handleFilterTransactionTypeChange}
isClearable
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
formik.resetForm();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
</>
);
};
@@ -0,0 +1,13 @@
import { string, object } from 'yup';
export const AdjustmentFilterSchema = object().shape({
product_id: string().nullable(),
warehouse_id: string().nullable(),
transaction_type: string().nullable(),
});
export type AdjustmentFilterType = {
product_id: string | null;
warehouse_id: string | null;
transaction_type: string | null;
};
@@ -1,55 +1,118 @@
import * as Yup from 'yup';
import { OptionType } from '@/components/input/SelectInput';
export const InventoryAdjustmentFormSchema = Yup.object({
product_category: Yup.mixed<OptionType>()
.nullable()
.test(
'is-valid-option',
'Kategori Produk wajib diisi!',
(value) => value !== null && value !== undefined
export type InventoryAdjustmentFormSchemaType = {
location: {
value: number;
label: string;
} | null;
location_id: number;
project_flock: {
value: number;
label: string;
} | null;
project_flock_id: number;
kandang: {
value: number;
label: string;
} | null;
kandang_id: number;
project_flock_kandang: {
value: number;
label: string;
} | null;
project_flock_kandang_id: number;
product: {
value: number;
label: string;
} | null;
product_id: number;
depletion_product: {
value: number;
label: string;
} | null;
depletion_product_id: number;
transaction_type: string;
transaction_subtype: string;
qty: number | string;
price: number | string;
notes: string;
};
export const InventoryAdjustmentFormSchema: Yup.ObjectSchema<InventoryAdjustmentFormSchemaType> =
Yup.object({
location: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).nullable(),
location_id: Yup.number()
.min(1, 'Lokasi wajib diisi!')
.required('Lokasi wajib diisi!')
.typeError('Lokasi wajib diisi!'),
project_flock: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).nullable(),
project_flock_id: Yup.number()
.min(1, 'Project flock wajib diisi!')
.required('Project flock wajib diisi!')
.typeError('Project flock wajib diisi!'),
kandang: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).nullable(),
kandang_id: Yup.number()
.min(1, 'Kandang wajib diisi!')
.required('Kandang wajib diisi!')
.typeError('Kandang wajib diisi!'),
project_flock_kandang: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).nullable(),
project_flock_kandang_id: Yup.number()
.default(0)
.typeError('Project Flock Kandang wajib diisi!')
.test(
'is-valid-project-flock-kandang',
'Project Flock Kandang wajib diisi!',
(value) => value !== undefined && value !== null && value > 0
)
.required('Project Flock Kandang wajib diisi!'),
product: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).nullable(),
product_id: Yup.number()
.min(1, 'Produk wajib diisi!')
.required('Produk wajib diisi!')
.typeError('Produk wajib diisi!'),
depletion_product: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
}).nullable(),
depletion_product_id: Yup.number()
.default(0)
.typeError('Jenis deplesi harus berupa angka'),
transaction_type: Yup.string()
.min(1, 'Tipe transaksi wajib diisi!')
.oneOf(
['PEMBELIAN', 'PENJUALAN', 'RECORDING'],
'Tipe transaksi tidak valid'
)
.required('Tipe transaksi wajib diisi')
.typeError('Tipe transaksi wajib diisi!'),
transaction_subtype: Yup.string().required(
'Sub tipe transaksi wajib diisi'
),
product_category_id: Yup.number().nullable(),
product: Yup.mixed<OptionType>()
.nullable()
.test(
'is-valid-option',
'Produk wajib diisi!',
(value) => value !== null && value !== undefined
),
product_id: Yup.number()
.nullable()
.required('Produk wajib diisi!')
.min(1, 'Produk wajib diisi!'),
warehouse: Yup.mixed<OptionType>()
.nullable()
.test(
'is-valid-option',
'Warehouse wajib diisi!',
(value) => value !== null && value !== undefined
),
warehouse_id: Yup.number()
.nullable()
.required('Warehouse wajib diisi!')
.min(1, 'Warehouse wajib diisi!'),
transaction_type: Yup.string()
.oneOf(['increase', 'decrease'], 'Tipe transaksi tidak valid')
.nullable()
.required('Tipe transaksi wajib diisi'),
quantity: Yup.number()
.typeError('Kuantitas harus berupa angka')
.min(1, 'Minimal kuantitas adalah 1')
.required('Kuantitas wajib diisi'),
note: Yup.string().required('Catatan wajib diisi!'),
});
qty: Yup.number()
.typeError('Kuantitas harus berupa angka')
.min(1, 'Minimal kuantitas adalah 1')
.required('Kuantitas wajib diisi'),
price: Yup.number()
.typeError('Harga harus berupa angka')
.min(0, 'Minimal harga adalah 0')
.required('Harga wajib diisi'),
notes: Yup.string().required('Catatan wajib diisi!'),
});
export type InventoryAdjustmentFormValues = Yup.InferType<
typeof InventoryAdjustmentFormSchema
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { InventoryAdjustment } from '@/types/api/inventory/adjustment';
import { ColumnDef } from '@tanstack/react-table';
const InventoryAdjustmentTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no inventory adjustment data displayed. Enter inventory adjustment data to get started.',
}: {
columns: ColumnDef<InventoryAdjustment>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default InventoryAdjustmentTableSkeleton;
@@ -1,49 +1,98 @@
'use client';
import { ChangeEventHandler, useState } from 'react';
import {
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { SortingState, CellContext, ColumnDef } from '@tanstack/react-table';
import { useFormik } from 'formik';
import Table from '@/components/Table';
import { Icon } from '@iconify/react';
import { Movement } from '@/types/api/inventory/movement';
import { MovementApi } from '@/services/api/inventory';
import { WarehouseApi, ProductApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { OptionType } from '@/components/input/SelectInput';
import { useUiStore } from '@/stores/ui/ui.store';
import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';
import Modal, { useModal } from '@/components/Modal';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import MovementTableSkeleton from '@/components/pages/inventory/movement/skeleton/MovementTableSkeleton';
import { Warehouse } from '@/types/api/master-data/warehouse';
import { Product } from '@/types/api/master-data/product';
import {
MovementFilterSchema,
MovementFilterType,
} from '@/components/pages/inventory/movement/filter/MovementFilter';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Movement, unknown>;
}) => (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.inventory.transfer.detail'>
<Button
href={`/inventory/movement/detail/?movementId=${props.row.original.id}`}
}) => {
const popoverId = `movement#${props.row.original.id}`;
const popoverAnchorName = `--anchor-movement#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='primary'
className='justify-start text-sm'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
);
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.inventory.transfer.detail'>
<Button
href={`/inventory/movement/detail/?movementId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const MovementTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -53,13 +102,109 @@ const MovementTable = () => {
} = useTableFilter({
initial: {
search: '',
productFilter: '',
warehouseFilter: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
productFilter: 'product_id',
warehouseFilter: 'warehouse_id',
},
});
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FORMIK SETUP =====
const formik = useFormik<MovementFilterType>({
initialValues: {
product_id: null,
warehouse_id: null,
},
validationSchema: MovementFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('productFilter', values.product_id || '');
updateFilter('warehouseFilter', values.warehouse_id || '');
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('productFilter', '');
updateFilter('warehouseFilter', '');
},
});
// ===== PRODUCT OPTIONS =====
const {
setInputValue: setProductInputValue,
options: productOptions,
isLoadingOptions: isLoadingProductOptions,
loadMore: loadMoreProducts,
} = useSelect<Product>(
filterModal.open ? ProductApi.basePath : null,
'id',
'name',
'search'
);
// ===== WAREHOUSE OPTIONS =====
const {
setInputValue: setWarehouseInputValue,
options: warehouseOptions,
isLoadingOptions: isLoadingWarehouseOptions,
loadMore: loadMoreWarehouses,
} = useSelect<Warehouse>(
filterModal.open ? WarehouseApi.basePath : null,
'id',
'name',
'search'
);
// ===== FILTER HANDLERS =====
const handleFilterProductChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const product = val as OptionType | null;
const productId = product?.value ? String(product.value) : null;
formik.setFieldValue('product_id', productId);
},
[formik]
);
const handleFilterWarehouseChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const warehouse = val as OptionType | null;
const warehouseId = warehouse?.value ? String(warehouse.value) : null;
formik.setFieldValue('warehouse_id', warehouseId);
},
[formik]
);
// ===== FILTER HELPERS =====
const productIdValue = useMemo(() => {
if (!formik.values.product_id) return null;
return (
productOptions.find(
(opt) => String(opt.value) === formik.values.product_id
) || null
);
}, [formik.values.product_id, productOptions]);
const warehouseIdValue = useMemo(() => {
if (!formik.values.warehouse_id) return null;
return (
warehouseOptions.find(
(opt) => String(opt.value) === formik.values.warehouse_id
) || null
);
}, [formik.values.warehouse_id, warehouseOptions]);
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
filterModal.openModal();
formik.validateForm();
};
const [sorting, setSorting] = useState<SortingState>([]);
const { data: movements, isLoading } = useSWR(
@@ -67,153 +212,249 @@ const MovementTable = () => {
MovementApi.getAllFetcher
);
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
useEffect(() => {
setTableState('movement-table', pathname);
}, [pathname, setTableState]);
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
setPage(1);
};
const movementColumns: ColumnDef<Movement>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorFn: (row) => row.source_warehouse?.name,
header: 'Gudang Asal',
},
{
accessorFn: (row) => row.destination_warehouse?.name,
header: 'Gudang Tujuan',
},
{
accessorKey: 'transfer_reason',
header: 'Catatan',
},
{
accessorKey: 'transfer_date',
header: 'Tanggal',
cell: (props) =>
new Date(props.row.original.transfer_date).toLocaleDateString('id-ID'),
},
{
accessorFn: (row) => {
const totalCost = row.deliveries?.reduce(
(sum, d) => sum + (d.shipping_cost_total || 0),
0
);
return totalCost?.toLocaleString('id-ID');
const movementColumns: ColumnDef<Movement>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
header: 'Biaya Pengiriman',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu type='dropdown' props={props} />
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu type='collapse' props={props} />
</RowCollapseOptions>
)}
</>
);
{
accessorFn: (row) => row.source_warehouse?.name,
header: 'Gudang Asal',
},
},
];
{
accessorFn: (row) => row.destination_warehouse?.name,
header: 'Gudang Tujuan',
},
{
accessorKey: 'transfer_reason',
header: 'Catatan',
},
{
accessorKey: 'transfer_date',
header: 'Tanggal',
cell: (props) =>
new Date(props.row.original.transfer_date).toLocaleDateString(
'id-ID'
),
},
{
accessorFn: (row) => {
const totalCost = row.deliveries?.reduce(
(sum, d) => sum + (d.shipping_cost_total || 0),
0
);
return totalCost?.toLocaleString('id-ID');
},
header: 'Biaya Pengiriman',
},
{
header: 'Aksi',
cell: (props: CellContext<Movement, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page]
);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row gap-2'>
<RequirePermission permissions='lti.inventory.transfer.create'>
<Button
href='/inventory/movement/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Movement
</Button>
</RequirePermission>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Movement'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.inventory.transfer.create'>
<Button
href='/inventory/movement/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Movement
</Button>
</RequirePermission>
</div>
<div className='flex justify-end gap-4'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
}}
onChange={pageSizeChangeHandler}
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper:
'col-span-6 sm:col-span-4 max-w-28 sm:justify-self-end',
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
/>
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
<Table<Movement>
data={isResponseSuccess(movements) ? movements?.data : []}
columns={movementColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(movements) ? movements?.meta?.page : 0}
totalItems={
isResponseSuccess(movements) ? movements?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(movements) && movements?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(movements) || movements.data?.length === 0 ? (
<div className='p-3'>
<MovementTableSkeleton
columns={movementColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Movement>
data={isResponseSuccess(movements) ? movements?.data : []}
columns={movementColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(movements) ? movements?.meta?.page : 0}
totalItems={
isResponseSuccess(movements)
? movements?.meta?.total_results
: 0
}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn('p-3 mb-0'),
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInput
label='Produk'
placeholder='Pilih Produk'
options={productOptions}
value={productIdValue}
onChange={handleFilterProductChange}
onInputChange={setProductInputValue}
isLoading={isLoadingProductOptions}
isClearable
onMenuScrollToBottom={loadMoreProducts}
className={{ wrapper: 'w-full' }}
/>
<SelectInput
label='Gudang'
placeholder='Pilih Gudang'
options={warehouseOptions}
value={warehouseIdValue}
onChange={handleFilterWarehouseChange}
onInputChange={setWarehouseInputValue}
isLoading={isLoadingWarehouseOptions}
isClearable
onMenuScrollToBottom={loadMoreWarehouses}
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
formik.resetForm();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
</>
);
};
@@ -0,0 +1,11 @@
import { string, object } from 'yup';
export const MovementFilterSchema = object().shape({
product_id: string().nullable(),
warehouse_id: string().nullable(),
});
export type MovementFilterType = {
product_id: string | null;
warehouse_id: string | null;
};
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Movement } from '@/types/api/inventory/movement';
import { ColumnDef } from '@tanstack/react-table';
const MovementTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no movement data displayed. Enter movement data to get started.',
}: {
columns: ColumnDef<Movement>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default MovementTableSkeleton;
@@ -2,46 +2,78 @@
import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import Table from '@/components/Table';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import { ROWS_OPTIONS } from '@/config/constant';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn, formatCurrency, formatNumber } from '@/lib/helper';
import { InventoryProductApi } from '@/services/api/inventory';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { useUiStore } from '@/stores/ui/ui.store';
import { InventoryProduct } from '@/types/api/inventory/product';
import { Icon } from '@iconify/react';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import { ChangeEventHandler, useMemo, useState } from 'react';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import InventoryProductTableSkeleton from '@/components/pages/inventory/product/skeleton/InventoryProductTableSkeleton';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<InventoryProduct, unknown>;
}) => (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.inventory.product_stock.detail'>
<Button
href={`/inventory/product/detail?inventoryProductId=${props.row.original.id}`}
}) => {
const popoverId = `product#${props.row.original.id}`;
const popoverAnchorName = `--anchor-product#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='primary'
className='justify-start text-sm'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
);
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.inventory.product_stock.detail'>
<Button
href={`/inventory/product/detail?inventoryProductId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const InventoryProductTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -65,20 +97,23 @@ const InventoryProductTable = () => {
InventoryProductApi.getAllFetcher
);
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
setPage(1);
useEffect(() => {
setTableState('inventory-product-table', pathname);
}, [pathname, setTableState]);
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const columns: ColumnDef<InventoryProduct>[] = useMemo(
() => [
{
header: '#',
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
@@ -125,7 +160,7 @@ const InventoryProductTable = () => {
},
{
header: 'Aksi',
cell: (props) => {
cell: (props: CellContext<InventoryProduct, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
@@ -135,96 +170,108 @@ const InventoryProductTable = () => {
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu type='dropdown' props={props} />
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu type='collapse' props={props} />
</RowCollapseOptions>
)}
</>
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
/>
);
},
},
],
[]
[tableFilterState.pageSize, tableFilterState.page]
);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row gap-2'></div>
</div>
<div className='flex justify-between items-end gap-4'>
<DebouncedTextInput
name='search'
placeholder='Cari Produk'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
}}
onChange={pageSizeChangeHandler}
className={{
wrapper:
'col-span-6 sm:col-span-4 max-w-28 sm:justify-self-end',
}}
/>
</div>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.inventory.product_stock.create'>
<Button
href='/inventory/product/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Product
</Button>
</RequirePermission>
</div>
<Table<InventoryProduct>
data={
isResponseSuccess(inventoryProducts) ? inventoryProducts?.data : []
}
columns={columns}
pageSize={tableFilterState.pageSize}
page={
isResponseSuccess(inventoryProducts)
? inventoryProducts?.meta?.page
: 0
}
totalItems={
isResponseSuccess(inventoryProducts)
? inventoryProducts?.meta?.total_results
: 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(inventoryProducts) &&
inventoryProducts?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon icon='heroicons:magnifying-glass' width={20} height={20} />
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
/>
</div>
</div>
</>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(inventoryProducts) ||
inventoryProducts.data?.length === 0 ? (
<div className='p-3'>
<InventoryProductTableSkeleton
columns={columns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<InventoryProduct>
data={
isResponseSuccess(inventoryProducts)
? inventoryProducts?.data
: []
}
columns={columns}
pageSize={tableFilterState.pageSize}
page={
isResponseSuccess(inventoryProducts)
? inventoryProducts?.meta?.page
: 0
}
totalItems={
isResponseSuccess(inventoryProducts)
? inventoryProducts?.meta?.total_results
: 0
}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn('p-3 mb-0'),
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
);
};
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { InventoryProduct } from '@/types/api/inventory/product';
import { ColumnDef } from '@tanstack/react-table';
const InventoryProductTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no inventory product data displayed. Enter inventory product data to get started.',
}: {
columns: ColumnDef<InventoryProduct>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default InventoryProductTableSkeleton;
@@ -1,7 +1,6 @@
'use client';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { OptionType } from '@/components/input/SelectInput';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
@@ -112,16 +111,34 @@ const DeliveryOrderFormModal = ({}: { initialValues?: Marketing }) => {
useState<DeliveryOrderProductFormValues | null>(null);
const [deliveryOrderValues, setDeliveryOrderValues] = useState<
DeliveryOrderProductFormValues[]
>(
isResponseSuccess(marketing)
? mergeSOwithDO(
marketing?.data.sales_order?.map(SalesProductToFieldValues) ?? [],
marketing?.data.delivery_order?.flatMap((delivery) =>
DeliveryProductToFieldValues(marketing.data.sales_order, delivery)
) ?? [],
true
)
: []
>([]);
const getDeliveryOrderValues = useCallback(
(marketingData: Marketing): DeliveryOrderProductFormValues[] => {
const hasDeliveryOrder =
marketingData.delivery_order &&
marketingData.delivery_order.length > 0 &&
marketingData.delivery_order.some(
(doItem) => doItem.deliveries && doItem.deliveries.length > 0
);
if (hasDeliveryOrder) {
return (
marketingData.delivery_order?.flatMap((delivery) =>
DeliveryProductToFieldValues(marketingData.sales_order, delivery)
) ?? []
);
}
return mergeSOwithDO(
marketingData.sales_order?.map(SalesProductToFieldValues) ?? [],
marketingData.delivery_order?.flatMap((delivery) =>
DeliveryProductToFieldValues(marketingData.sales_order, delivery)
) ?? [],
true
);
},
[]
);
// ================== SETUP FORMIK ==================
@@ -130,14 +147,8 @@ const DeliveryOrderFormModal = ({}: { initialValues?: Marketing }) => {
>(() => {
if (!isResponseSuccess(marketing))
return {} as SalesOrderFormValues & DeliveryOrderFormValues;
const deliveryValues = mergeSOwithDO(
marketing?.data.sales_order?.map(SalesProductToFieldValues) ?? [],
marketing?.data.delivery_order?.flatMap((delivery) =>
DeliveryProductToFieldValues(marketing.data.sales_order, delivery)
) ?? [],
true
);
const deliveryValues = getDeliveryOrderValues(marketing.data);
setDeliveryOrderValues(deliveryValues);
return {
@@ -163,7 +174,7 @@ const DeliveryOrderFormModal = ({}: { initialValues?: Marketing }) => {
) ?? [],
delivery_order: deliveryValues,
};
}, [marketing]);
}, [marketing, getDeliveryOrderValues]);
const formik = useFormik<SalesOrderFormValues & DeliveryOrderFormValues>({
enableReinitialize: true,
@@ -648,9 +659,8 @@ const DeliveryOrderFormModal = ({}: { initialValues?: Marketing }) => {
<tr>
<td className='text-sm px-4 py-3'>No. Order</td>
<td className='text-sm px-4 py-3'>
{marketing.data.do_number
? marketing.data.do_number
: marketing.data.so_number}
{marketing.data.do_number ||
marketing.data.so_number}
</td>
</tr>
<tr>
@@ -765,6 +775,7 @@ const DeliveryOrderFormModal = ({}: { initialValues?: Marketing }) => {
<MemoizedDeliveryOrderProductForm
formState={'edit'}
salesOrders={marketing?.data?.sales_order ?? []}
deliveryOrders={marketing?.data?.delivery_order ?? []}
exisitingValues={deliveryOrderValues}
onSubmitForm={handleAddSubmitDO}
initialValues={selectedDeliveryProduct ?? undefined}
@@ -30,6 +30,8 @@ import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import StatusBadge from '@/components/helper/StatusBadge';
import MarketingFilterModal from '@/components/pages/marketing/MarketingFilter';
import ButtonFilter from '@/components/helper/ButtonFilter';
import MarketingTableSkeleton from '@/components/pages/marketing/skeleton/MarketingTableSkeleton';
const RowsOptionsMenu = ({
props,
@@ -214,32 +216,6 @@ const MarketingTable = () => {
updateFilter('customer_id', '');
};
// ===== ACTIVE FILTERS COUNT =====
const activeFiltersCount = useMemo(() => {
let count = 0;
// Product filter
if (tableFilterState.product_ids) {
count += 1;
}
// Status filter
if (tableFilterState.status) {
count += 1;
}
// Customer filter
if (tableFilterState.customer_id) {
count += 1;
}
return count;
}, [
tableFilterState.product_ids,
tableFilterState.status,
tableFilterState.customer_id,
]);
const approveClickHandler = () => {
setApproveAction('APPROVED');
confirmationModal.openModal();
@@ -588,28 +564,14 @@ const MarketingTable = () => {
)}
</div>
<div className='flex flex-row gap-3'>
<Button
variant='outline'
color='none'
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={() => {
filterModal.openModal();
}}
className={cn(
'px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft transition-all',
{
'border-primary-gradient text-primary':
activeFiltersCount > 0,
}
)}
>
<Icon icon='heroicons:funnel' width={20} height={20} />
Filter
{activeFiltersCount > 0 && (
<span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
{activeFiltersCount}
</span>
)}
</Button>
className='px-3 py-2.5'
/>
<Dropdown
align='end'
direction='bottom'
@@ -655,28 +617,49 @@ const MarketingTable = () => {
</Dropdown>
</div>
</div>
<Table
rowSelection={rowSelection}
setRowSelection={setRowSelection}
onPageChange={setPage}
onPageSizeChange={setPageSize}
data={allData}
columns={columns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(marketing) ? marketing?.meta?.page : 1}
totalItems={
isResponseSuccess(marketing) ? marketing?.meta?.total_results : 0
}
isLoading={isLoadingMarketing}
className={{
containerClassName: cn('p-3', {
'w-full mb-20':
isResponseSuccess(marketing) && marketing?.data?.length === 0,
}),
bodyColumnClassName:
'last:text-end last:w-17 first:text-start first:w-5',
}}
/>
<div className='flex flex-col mb-4'>
{isLoadingMarketing ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(marketing) || marketing.data?.length === 0 ? (
<div className='p-3'>
<MarketingTableSkeleton
columns={columns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table
rowSelection={rowSelection}
setRowSelection={setRowSelection}
onPageChange={setPage}
onPageSizeChange={setPageSize}
data={allData}
columns={columns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(marketing) ? marketing?.meta?.page : 1}
totalItems={
isResponseSuccess(marketing)
? marketing?.meta?.total_results
: 0
}
isLoading={isLoadingMarketing}
className={{
containerClassName: cn('p-3 mb-0'),
bodyColumnClassName:
'last:text-end last:w-17 first:text-start first:w-5',
}}
/>
)}
</div>
</div>
<ConfirmationModal
ref={deleteModal.ref}
@@ -10,7 +10,10 @@ import NumberInput from '@/components/input/NumberInput';
import PatternInput from '@/components/input/PatternInput';
import { formatTitleCase, formatVechicleNumber } from '@/lib/helper';
import DateInput from '@/components/input/DateInput';
import { BaseSalesOrder } from '@/types/api/marketing/marketing';
import {
BaseSalesOrder,
BaseDeliveryOrder,
} from '@/types/api/marketing/marketing';
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm.schema';
import * as Yup from 'yup';
import { isResponseSuccess } from '@/lib/api-helper';
@@ -32,6 +35,7 @@ import { handleMarketingCalculation } from '@/lib/marketing-calculation';
const DeliveryOrderProductForm = ({
formState,
salesOrders,
deliveryOrders,
initialValues,
exisitingValues,
onUpdateForm,
@@ -39,6 +43,7 @@ const DeliveryOrderProductForm = ({
}: {
formState: 'add' | 'edit';
salesOrders: BaseSalesOrder[];
deliveryOrders?: BaseDeliveryOrder[];
initialValues?: DeliveryOrderProductFormValues;
exisitingValues?: DeliveryOrderProductFormValues[];
onSubmitForm?: (value: DeliveryOrderProductFormValues) => Promise<void>;
@@ -115,6 +120,36 @@ const DeliveryOrderProductForm = ({
})
?.filter((item) => item != null) as OptionType[];
const hasDeliveryOrder = useMemo(() => {
return (
deliveryOrders &&
deliveryOrders.length > 0 &&
deliveryOrders.some(
(doItem) => doItem.deliveries && doItem.deliveries.length > 0
)
);
}, [deliveryOrders]);
const deliveryOrder = useMemo(() => {
if (!hasDeliveryOrder || !deliveryOrders) return null;
for (const doItem of deliveryOrders) {
const found = doItem.deliveries.find(
(d) =>
d.product_warehouse.id ===
initialValues?.marketing_product?.product_warehouse_id
);
if (found) {
return {
...found,
delivery_date: doItem.delivery_date,
do_number: doItem.do_number,
};
}
}
return null;
}, [deliveryOrders, hasDeliveryOrder, initialValues]);
const salesOrder = salesOrders.find(
(item) => item.id === initialValues?.marketing_product_id
);
@@ -122,15 +157,25 @@ const DeliveryOrderProductForm = ({
const formik = useFormik<DeliveryOrderProductFormValues>({
enableReinitialize: true,
initialValues: {
delivery_date: initialValues?.delivery_date || undefined,
vehicle_number: initialValues?.vehicle_number || undefined,
delivery_date:
deliveryOrder?.delivery_date ||
initialValues?.delivery_date ||
undefined,
vehicle_number:
deliveryOrder?.vehicle_number ||
initialValues?.vehicle_number ||
undefined,
marketing_product_id:
salesOrder?.id || initialValues?.marketing_product_id || undefined,
unit_price: initialValues?.unit_price || undefined,
total_weight: initialValues?.total_weight || undefined,
qty: initialValues?.qty || undefined,
avg_weight: initialValues?.avg_weight || undefined,
total_price: initialValues?.total_price || undefined,
unit_price:
deliveryOrder?.unit_price ?? initialValues?.unit_price ?? undefined,
total_weight:
deliveryOrder?.total_weight ?? initialValues?.total_weight ?? undefined,
qty: deliveryOrder?.qty ?? initialValues?.qty ?? undefined,
avg_weight:
deliveryOrder?.avg_weight ?? initialValues?.avg_weight ?? undefined,
total_price:
deliveryOrder?.total_price ?? initialValues?.total_price ?? undefined,
marketing_product: initialValues?.marketing_product || undefined,
uom: initialValues?.uom || '',
weight_per_convertion:
@@ -236,6 +281,25 @@ const DeliveryOrderProductForm = ({
});
};
// Handler untuk onChange - auto calculation real-time untuk field yang mempengaruhi total_price (total_peti, weight_per_convertion, price_per_convertion, sisa_berat, price_sisa_berat, price_per_qty, qty)
const handleFieldChange = (
field: string,
value: number | string,
callback?: () => void
) => {
formik.setFieldValue(field, value);
setTimeout(() => {
handleMarketingCalculation(field, {
values: { ...formik.values, [field]: value },
setFieldValue: formik.setFieldValue,
hasSisaBerat,
});
}, 0);
if (callback) callback();
};
// Handler khusus untuk toggle sisa berat - langsung pakai nilai baru
const handleSisaBeratToggle = (newHasSisaBerat: boolean) => {
setHasSisaBerat(newHasSisaBerat);
@@ -520,13 +584,11 @@ const DeliveryOrderProductForm = ({
} per ${formik.values.convertion_unit?.value}`}
value={formik.values.weight_per_convertion ?? ''}
onChange={(e) => {
formik.setFieldValue(
'weight_per_convertion',
Number(e.target.value)
const value = Number(e.target.value);
handleFieldChange('weight_per_convertion', value, () =>
setCurrentInput(e.target.name)
);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('weight_per_convertion')}
/>
</div>
</div>
@@ -564,10 +626,11 @@ const DeliveryOrderProductForm = ({
name='total_peti'
value={formik.values.total_peti ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('total_peti', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('total_peti')}
isError={
formik.touched.total_peti && Boolean(formik.errors.total_peti)
}
@@ -592,10 +655,11 @@ const DeliveryOrderProductForm = ({
name='avg_weight'
value={formik.values.avg_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('avg_weight', value, () =>
setCurrentInput('avg_weight')
);
}}
onBlur={() => handleBlurField('avg_weight')}
isError={
formik.touched.avg_weight &&
Boolean(formik.errors.avg_weight)
@@ -613,10 +677,11 @@ const DeliveryOrderProductForm = ({
name='total_weight'
value={formik.values.total_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('total_weight', value, () =>
setCurrentInput('total_weight')
);
}}
onBlur={() => handleBlurField('total_weight')}
isError={
formik.touched.total_weight &&
Boolean(formik.errors.total_weight)
@@ -638,10 +703,11 @@ const DeliveryOrderProductForm = ({
name='qty'
value={formik.values.qty}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('qty', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('qty')}
isError={Boolean(formik.errors.qty)}
errorMessage={formik.errors.qty}
placeholder='Masukan Kuantitas'
@@ -677,10 +743,11 @@ const DeliveryOrderProductForm = ({
name='price_per_convertion'
value={formik.values.price_per_convertion ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('price_per_convertion', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('price_per_convertion')}
isError={
formik.touched.price_per_convertion &&
Boolean(formik.errors.price_per_convertion)
@@ -699,10 +766,11 @@ const DeliveryOrderProductForm = ({
name='price_per_qty'
value={formik.values.price_per_qty ?? undefined}
onChange={(e) => {
formik.setFieldValue('price_per_qty', Number(e.target.value));
setCurrentInput('price_per_qty');
const value = Number(e.target.value);
handleFieldChange('price_per_qty', value, () =>
setCurrentInput('price_per_qty')
);
}}
onBlur={() => handleBlurField('price_per_qty')}
isError={
formik.touched.price_per_qty &&
Boolean(formik.errors.price_per_qty)
@@ -721,10 +789,11 @@ const DeliveryOrderProductForm = ({
name='unit_price'
value={formik.values.unit_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('unit_price', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('unit_price')}
isError={Boolean(formik.errors.unit_price)}
errorMessage={formik.errors.unit_price}
placeholder='Masukan Harga Satuan'
@@ -760,10 +829,11 @@ const DeliveryOrderProductForm = ({
name='sisa_berat'
value={formik.values.sisa_berat ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('sisa_berat', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('sisa_berat')}
isError={
formik.touched.sisa_berat && Boolean(formik.errors.sisa_berat)
}
@@ -776,10 +846,11 @@ const DeliveryOrderProductForm = ({
name='price_sisa_berat'
value={formik.values.price_sisa_berat ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('price_sisa_berat', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('price_sisa_berat')}
isError={
formik.touched.price_sisa_berat &&
Boolean(formik.errors.price_sisa_berat)
@@ -797,10 +868,11 @@ const DeliveryOrderProductForm = ({
name='total_price'
value={formik.values.total_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('total_price', value, () =>
setCurrentInput('total_price')
);
}}
onBlur={() => handleBlurField('total_price')}
isError={
formik.touched.total_price && Boolean(formik.errors.total_price)
}
@@ -250,6 +250,25 @@ const SalesOrderProductForm = ({
});
};
// Handler untuk onChange - auto calculation real-time untuk field yang mempengaruhi total_price (total_peti, weight_per_convertion, price_per_convertion, sisa_berat, price_sisa_berat, price_per_qty, qty)
const handleFieldChange = (
field: string,
value: number | string,
callback?: () => void
) => {
formik.setFieldValue(field, value);
setTimeout(() => {
handleMarketingCalculation(field, {
values: { ...formik.values, [field]: value },
setFieldValue: formik.setFieldValue,
hasSisaBerat,
});
}, 0);
if (callback) callback();
};
// Handler khusus untuk toggle sisa berat - langsung pakai nilai baru
const handleSisaBeratToggle = (newHasSisaBerat: boolean) => {
setHasSisaBerat(newHasSisaBerat);
@@ -475,13 +494,11 @@ const SalesOrderProductForm = ({
} per ${formik.values.convertion_unit?.value}`}
value={formik.values.weight_per_convertion ?? ''}
onChange={(e) => {
formik.setFieldValue(
'weight_per_convertion',
Number(e.target.value)
const value = Number(e.target.value);
handleFieldChange('weight_per_convertion', value, () =>
setCurrentInput(e.target.name)
);
setCurrentInput(e.target.name);
}}
onBlur={() => handleBlurField('weight_per_convertion')}
/>
</div>
</div>
@@ -519,10 +536,11 @@ const SalesOrderProductForm = ({
name='total_peti'
value={formik.values.total_peti ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('total_peti', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('total_peti')}
isError={
formik.touched.total_peti && Boolean(formik.errors.total_peti)
}
@@ -547,10 +565,11 @@ const SalesOrderProductForm = ({
name='avg_weight'
value={formik.values.avg_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('avg_weight', value, () =>
setCurrentInput('avg_weight')
);
}}
onBlur={() => handleBlurField('avg_weight')}
isError={
formik.touched.avg_weight &&
Boolean(formik.errors.avg_weight)
@@ -568,10 +587,11 @@ const SalesOrderProductForm = ({
name='total_weight'
value={formik.values.total_weight}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('total_weight', value, () =>
setCurrentInput('total_weight')
);
}}
onBlur={() => handleBlurField('total_weight')}
isError={
formik.touched.total_weight &&
Boolean(formik.errors.total_weight)
@@ -593,10 +613,11 @@ const SalesOrderProductForm = ({
name='qty'
value={formik.values.qty}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('qty', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('qty')}
isError={formik.touched.qty && Boolean(formik.errors.qty)}
errorMessage={formik.errors.qty}
placeholder='Masukan Kuantitas'
@@ -630,10 +651,11 @@ const SalesOrderProductForm = ({
name='price_per_convertion'
value={formik.values.price_per_convertion ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('price_per_convertion', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('price_per_convertion')}
isError={
formik.touched.price_per_convertion &&
Boolean(formik.errors.price_per_convertion)
@@ -652,10 +674,11 @@ const SalesOrderProductForm = ({
name='price_per_qty'
value={formik.values.price_per_qty ?? undefined}
onChange={(e) => {
formik.setFieldValue('price_per_qty', Number(e.target.value));
setCurrentInput('price_per_qty');
const value = Number(e.target.value);
handleFieldChange('price_per_qty', value, () =>
setCurrentInput('price_per_qty')
);
}}
onBlur={() => handleBlurField('price_per_qty')}
isError={
formik.touched.price_per_qty &&
Boolean(formik.errors.price_per_qty)
@@ -674,10 +697,11 @@ const SalesOrderProductForm = ({
name='unit_price'
value={formik.values.unit_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('unit_price', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('unit_price')}
isError={
formik.touched.unit_price && Boolean(formik.errors.unit_price)
}
@@ -715,10 +739,11 @@ const SalesOrderProductForm = ({
name='sisa_berat'
value={formik.values.sisa_berat ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('sisa_berat', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('sisa_berat')}
isError={
formik.touched.sisa_berat && Boolean(formik.errors.sisa_berat)
}
@@ -731,10 +756,11 @@ const SalesOrderProductForm = ({
name='price_sisa_berat'
value={formik.values.price_sisa_berat ?? undefined}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('price_sisa_berat', value, () =>
setCurrentInput(e.target.name)
);
}}
onBlur={() => handleBlurField('price_sisa_berat')}
isError={
formik.touched.price_sisa_berat &&
Boolean(formik.errors.price_sisa_berat)
@@ -752,10 +778,11 @@ const SalesOrderProductForm = ({
name='total_price'
value={formik.values.total_price}
onChange={(e) => {
formik.handleChange(e);
setCurrentInput(e.target.name);
const value = Number(e.target.value);
handleFieldChange('total_price', value, () =>
setCurrentInput('total_price')
);
}}
onBlur={() => handleBlurField('total_price')}
isError={
formik.touched.total_price && Boolean(formik.errors.total_price)
}
@@ -2,10 +2,11 @@ import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/for
import Button from '@/components/Button';
import Card from '@/components/Card';
import { Icon } from '@iconify/react';
import { useRef } from 'react';
import { useRef, useMemo } from 'react';
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
import DeliveryOrderExport from '@/components/pages/marketing/pdf/DeliveryOrderExport';
import { Marketing } from '@/types/api/marketing/marketing';
import { Marketing, BaseDelivery } from '@/types/api/marketing/marketing';
import { Warehouse } from '@/types/api/master-data/warehouse';
type DeliveryOrderProductTableProps = {
data: DeliveryOrderProductFormValues[];
@@ -42,7 +43,31 @@ const DeliveryOrderProductTable = ({
const approvalStepNumber = marketing?.latest_approval?.step_number;
const renderTableContent = (item: DeliveryOrderProductFormValues) => {
const hasDeliveryOrder = useMemo(() => {
return (
marketing?.delivery_order &&
marketing.delivery_order.length > 0 &&
marketing.delivery_order.some(
(doItem) => doItem.deliveries && doItem.deliveries.length > 0
)
);
}, [marketing?.delivery_order]);
const deliveryItems = useMemo(() => {
if (!hasDeliveryOrder) return [];
return (
marketing?.delivery_order?.flatMap((doItem) =>
doItem.deliveries.map((delivery) => ({
...delivery,
do_number: doItem.do_number,
delivery_date: doItem.delivery_date,
warehouse: doItem.warehouse,
}))
) ?? []
);
}, [marketing?.delivery_order, hasDeliveryOrder]);
const renderSalesOrderContent = (item: DeliveryOrderProductFormValues) => {
const doItem = marketing?.delivery_order?.find(
(doItem) => doItem.do_number === item.do_number
);
@@ -185,50 +210,217 @@ const DeliveryOrderProductTable = ({
);
};
const renderDeliveryOrderContent = (
item: BaseDelivery & {
do_number: string;
delivery_date: string;
warehouse: Warehouse;
}
) => {
const parentDoItem = marketing?.delivery_order?.find(
(doItem) => doItem.do_number === item.do_number
);
return (
<>
<tr className='border-b border-tools-table-outline border-base-content/5'>
<th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
Label
</th>
<th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
<div className='flex w-full flex-row gap-1 items-center justify-between h-full'>
<div>Value</div>
</div>
</th>
</tr>
<>
<tr>
<td className='text-sm px-4 py-3'>Gudang</td>
<td className='text-sm px-4 py-3'>{item.warehouse?.name}</td>
</tr>
<tr>
<td className='text-sm px-4 py-3'>Produk</td>
<td className='text-sm px-4 py-3'>
{item.product_warehouse?.product?.name}
</td>
</tr>
<tr>
<td className='text-sm px-4 py-3'>Qty</td>
<td className='text-sm px-4 py-3'>
{item.qty
? `${formatNumber(item.qty)} ${item.product_warehouse?.product?.uom?.name ?? ''}`
: '-'}
</td>
</tr>
{Number(item.avg_weight ?? 0) > 0 && (
<tr>
<td className='text-sm px-4 py-3'>Avg Bobot</td>
<td className='text-sm px-4 py-3'>
{formatNumber(Number(item.avg_weight))} Kg
</td>
</tr>
)}
{Number(item.total_weight ?? 0) > 0 && (
<tr>
<td className='text-sm px-4 py-3'>Total Bobot</td>
<td className='text-sm px-4 py-3'>
{formatNumber(Number(item.total_weight))}
</td>
</tr>
)}
<tr>
<td className='text-sm px-4 py-3'>Total Harga Satuan</td>
<td className='text-sm px-4 py-3'>
{formatCurrency(item.unit_price)}
</td>
</tr>
<tr>
<td className='text-sm px-4 py-3'>Total Penjualan</td>
<td className='text-sm px-4 py-3'>
{formatCurrency(item.total_price)}
</td>
</tr>
</>
<tr className='border-b border-t border-tools-table-outline border-base-content/5'>
<th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
Label
</th>
<th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
<div className='flex w-full flex-row gap-1 items-center justify-between h-full'>
<div>Value</div>
</div>
</th>
</tr>
<>
{approvalStepNumber !== 1 && (
<tr>
<td className='text-sm px-4 py-3'>Tanggal Pengiriman</td>
<td className='text-sm px-4 py-3'>
{item.delivery_date
? formatDate(item.delivery_date, 'DD MMM YYYY')
: '-'}
</td>
</tr>
)}
{item.do_number && (
<tr>
<td className='text-sm px-4 py-3'>No. Pengiriman</td>
<td className='text-sm px-4 py-3'>{item.do_number}</td>
</tr>
)}
<tr>
<td className='text-sm px-4 py-3'>No. Polisi</td>
<td className='text-sm px-4 py-3'>{item.vehicle_number}</td>
</tr>
{parentDoItem && (
<tr>
<td className='text-sm px-4 py-3'>Dokumen Pengiriman</td>
<td className='text-sm px-4 py-3'>
<DeliveryOrderExport
data={marketing}
deliveryOrder={parentDoItem}
/>
</td>
</tr>
)}
</>
</>
);
};
return (
<>
<div className='size-full flex flex-col relative overflow-x-hidden gap-3'>
{data.map((item) => (
<div key={`table-${item.id}`}>
{formType === 'success' ? (
<div className='rounded-lg border border-tools-table-outline border-base-content/5'>
<table
style={{
borderRadius: '0.5rem',
}}
className='border-none w-full'
>
<tbody className='w-full'>{renderTableContent(item)}</tbody>
</table>
{hasDeliveryOrder
? deliveryItems.map((item, index) => (
<div key={`do-table-${item.product_warehouse?.id}-${index}`}>
{formType === 'success' ? (
<div className='rounded-lg border border-tools-table-outline border-base-content/5'>
<table
style={{
borderRadius: '0.5rem',
}}
className='border-none w-full'
>
<tbody className='w-full'>
{renderDeliveryOrderContent(item)}
</tbody>
</table>
</div>
) : (
<Card
key={`do-table-${item.product_warehouse?.id}-${index}`}
title={item.product_warehouse?.product?.name || 'Produk'}
collapsible={true}
defaultCollapsed={false}
variant='bordered'
className={{
wrapper: 'w-full rounded-lg',
body: 'p-0',
title: 'px-2 py-1.5 font-normal text-sm',
collapsible: 'rounded-lg',
}}
>
<table
style={{
borderRadius: '0.5rem',
}}
className='border-none w-full'
>
<tbody className='w-full'>
{renderDeliveryOrderContent(item)}
</tbody>
</table>
</Card>
)}
</div>
) : (
<Card
key={`table-${item.id}`}
title={
item.marketing_product?.product_warehouse?.label || 'Produk'
}
collapsible={true}
defaultCollapsed={false}
variant='bordered'
className={{
wrapper: 'w-full rounded-lg',
body: 'p-0',
title: 'px-2 py-1.5 font-normal text-sm',
collapsible: 'rounded-lg',
}}
>
<table
style={{
borderRadius: '0.5rem',
}}
className='border-none w-full'
>
<tbody className='w-full'>{renderTableContent(item)}</tbody>
</table>
</Card>
)}
</div>
))}
))
: data.map((item) => (
<div key={`table-${item.id}`}>
{formType === 'success' ? (
<div className='rounded-lg border border-tools-table-outline border-base-content/5'>
<table
style={{
borderRadius: '0.5rem',
}}
className='border-none w-full'
>
<tbody className='w-full'>
{renderSalesOrderContent(item)}
</tbody>
</table>
</div>
) : (
<Card
key={`table-${item.id}`}
title={
item.marketing_product?.product_warehouse?.label ||
'Produk'
}
collapsible={true}
defaultCollapsed={false}
variant='bordered'
className={{
wrapper: 'w-full rounded-lg',
body: 'p-0',
title: 'px-2 py-1.5 font-normal text-sm',
collapsible: 'rounded-lg',
}}
>
<table
style={{
borderRadius: '0.5rem',
}}
className='border-none w-full'
>
<tbody className='w-full'>
{renderSalesOrderContent(item)}
</tbody>
</table>
</Card>
)}
</div>
))}
</div>
</>
);
@@ -1,7 +1,7 @@
import Button from '@/components/Button';
import { BaseDeliveryOrder, Marketing } from '@/types/api/marketing/marketing';
import { Icon } from '@iconify/react';
import { Document, Image, Page, pdf, Text, View } from '@react-pdf/renderer';
import { Document, Page, pdf, Text, View } from '@react-pdf/renderer';
import { useMemo, useState } from 'react';
import { formatDate, formatNumber, formatVechicleNumber } from '@/lib/helper';
import pdfStyles from '@/components/pages/marketing/pdf/styles/MarketingPDFStyles';
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Marketing } from '@/types/api/marketing/marketing';
import { ColumnDef } from '@tanstack/react-table';
const MarketingTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no marketing data displayed. Enter marketing data to get started.',
}: {
columns: ColumnDef<Marketing>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default MarketingTableSkeleton;
@@ -1,6 +1,6 @@
'use client';
import { ChangeEventHandler, useEffect, useState } from 'react';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
@@ -11,75 +11,101 @@ import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import RequirePermission from '@/components/helper/RequirePermission';
import AreaTableSkeleton from '@/components/pages/master-data/area/skeleton/AreaTableSkeleton';
import { Area } from '@/types/api/master-data/area';
import { AreaApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Area, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `area#${props.row.original.id}`;
const popoverAnchorName = `--anchor-area#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.area.detail'>
<Button
href={`/master-data/area/detail/?areaId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.area.update'>
<Button
href={`/master-data/area/detail/edit/?areaId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.area.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='text-error hover:text-inherit'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.area.detail'>
<Button
href={`/master-data/area/detail/?areaId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.area.update'>
<Button
href={`/master-data/area/detail/edit/?areaId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.area.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const AreasTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -87,10 +113,17 @@ const AreasTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '' },
paramMap: { page: 'page', pageSize: 'limit', nameSort: 'sort_name' },
initial: {
search: searchValue,
},
paramMap: {
page: 'page',
pageSize: 'limit',
},
});
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: areas,
isLoading,
@@ -101,65 +134,21 @@ const AreasTable = () => {
);
const deleteModal = useModal();
const [selectedArea, setSelectedArea] = useState<Area | undefined>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const areasColumns: ColumnDef<Area>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
useEffect(() => {
setTableState('areas-table', pathname);
}, [pathname, setTableState]);
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedArea(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -179,95 +168,132 @@ const AreasTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const areasColumns: ColumnDef<Area>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
header: 'Aksi',
cell: (props: CellContext<Area, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
setPageSize(newVal.value as number);
};
const deleteClickHandler = () => {
setSelectedArea(props.row.original);
deleteModal.openModal();
};
// track sorting
useEffect(() => {
const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
if (!isNameSorted) {
updateFilter('nameSort', '');
} else {
updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
}
}, [sorting, updateFilter]);
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.area.create'>
<Button
href='/master-data/area/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Area'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.area.create'>
<Button
href='/master-data/area/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Area
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
</div>
</div>
<Table<Area>
data={isResponseSuccess(areas) ? areas?.data : []}
columns={areasColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(areas) ? areas?.meta?.page : 0}
totalItems={isResponseSuccess(areas) ? areas?.meta?.total_results : 0}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20': isResponseSuccess(areas) && areas?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(areas) || areas.data?.length === 0 ? (
<div className='p-3'>
<AreaTableSkeleton
columns={areasColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Area>
data={isResponseSuccess(areas) ? areas?.data : []}
columns={areasColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(areas) ? areas?.meta?.page : 0}
totalItems={
isResponseSuccess(areas) ? areas?.meta?.total_results : 0
}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Area } from '@/types/api/master-data/area';
import { ColumnDef } from '@tanstack/react-table';
const AreaTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no area data displayed. Enter area data to get started.',
}: {
columns: ColumnDef<Area>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default AreaTableSkeleton;
@@ -1,6 +1,6 @@
'use client';
import { ChangeEventHandler, useEffect, useState } from 'react';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
@@ -11,75 +11,101 @@ import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import BankTableSkeleton from '@/components/pages/master-data/bank/skeleton/BankTableSkeleton';
import { Bank } from '@/types/api/master-data/bank';
import { BankApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Bank, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `bank#${props.row.original.id}`;
const popoverAnchorName = `--anchor-bank#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.banks.detail'>
<Button
href={`/master-data/bank/detail/?bankId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.banks.update'>
<Button
href={`/master-data/bank/detail/edit/?bankId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.banks.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.banks.detail'>
<Button
href={`/master-data/bank/detail/?bankId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.banks.update'>
<Button
href={`/master-data/bank/detail/edit/?bankId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.banks.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const BanksTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -87,10 +113,17 @@ const BanksTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '' },
paramMap: { page: 'page', pageSize: 'limit', nameSort: 'sort_name' },
initial: {
search: searchValue,
},
paramMap: {
page: 'page',
pageSize: 'limit',
},
});
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: banks,
isLoading,
@@ -101,78 +134,21 @@ const BanksTable = () => {
);
const deleteModal = useModal();
const [selectedBank, setSelectedBank] = useState<Bank | undefined>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const banksColumns: ColumnDef<Bank>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'alias',
header: 'Alias',
},
{
accessorKey: 'account_number',
header: 'No. Rekening',
},
{
accessorKey: 'owner',
header: 'Pemilik',
cell: (props) => (props.getValue() ? props.getValue() : '-'),
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
useEffect(() => {
setTableState('banks-table', pathname);
}, [pathname, setTableState]);
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedBank(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -192,93 +168,145 @@ const BanksTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const banksColumns: ColumnDef<Bank>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'alias',
header: 'Alias',
},
{
accessorKey: 'account_number',
header: 'No. Rekening',
},
{
accessorKey: 'owner',
header: 'Pemilik',
cell: (props) => props.getValue() || '-',
},
{
header: 'Aksi',
cell: (props: CellContext<Bank, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
setPageSize(newVal.value as number);
};
const deleteClickHandler = () => {
setSelectedBank(props.row.original);
deleteModal.openModal();
};
// track sorting
useEffect(() => {
const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
if (!isNameSorted) {
updateFilter('nameSort', '');
} else {
updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
}
}, [sorting]);
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.banks.create'>
<Button
href='/master-data/bank/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Bank'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.banks.create'>
<Button
href='/master-data/bank/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Bank
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
</div>
</div>
<Table<Bank>
data={isResponseSuccess(banks) ? banks?.data : []}
columns={banksColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(banks) ? banks?.meta?.page : 0}
totalItems={isResponseSuccess(banks) ? banks?.meta?.total_results : 0}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20': isResponseSuccess(banks) && banks?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(banks) || banks.data?.length === 0 ? (
<div className='p-3'>
<BankTableSkeleton
columns={banksColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Bank>
data={isResponseSuccess(banks) ? banks?.data : []}
columns={banksColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(banks) ? banks?.meta?.page : 0}
totalItems={
isResponseSuccess(banks) ? banks?.meta?.total_results : 0
}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Bank } from '@/types/api/master-data/bank';
import { ColumnDef } from '@tanstack/react-table';
const BankTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no bank data displayed. Enter bank data to get started.',
}: {
columns: ColumnDef<Bank>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default BankTableSkeleton;
@@ -1,81 +1,111 @@
'use client';
import Button from '@/components/Button';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import Table from '@/components/Table';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import { ROWS_OPTIONS } from '@/config/constant';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { cn } from '@/lib/helper';
import { CustomerApi } from '@/services/api/master-data';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import CustomerTableSkeleton from '@/components/pages/master-data/customer/skeleton/CustomerTableSkeleton';
import { Customer } from '@/types/api/master-data/customer';
import { Icon } from '@iconify/react';
import { CellContext, ColumnDef } from '@tanstack/react-table';
import { useState } from 'react';
import toast from 'react-hot-toast';
import useSWR from 'swr';
import { CustomerApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Customer, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `customer#${props.row.original.id}`;
const popoverAnchorName = `--anchor-customer#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.customer.detail'>
<Button
href={`/master-data/customer/detail/?customerId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.customer.update'>
<Button
href={`/master-data/customer/detail/edit/?customerId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.customer.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.customer.detail'>
<Button
href={`/master-data/customer/detail/?customerId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.customer.update'>
<Button
href={`/master-data/customer/detail/edit/?customerId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.customer.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const CustomersTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -83,16 +113,17 @@ const CustomersTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '', picSort: '' },
initial: {
search: searchValue,
},
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
picSort: 'sort_pic',
},
});
// Fetch Data
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: customers,
isLoading,
@@ -102,87 +133,25 @@ const CustomersTable = () => {
CustomerApi.getAllFetcher
);
// State
const deleteModal = useModal();
const [selectedCustomer, setSelectedCustomer] = useState<
Customer | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
// Columns Definition
const customersColumns: ColumnDef<Customer>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'pic',
header: 'PIC',
cell: (props) => props.row.original.pic.name,
},
{
accessorKey: 'type',
header: 'Type',
cell: (props) => props.row.original.type,
},
{
accessorKey: 'phone',
header: 'Phone',
},
{
accessorKey: 'email',
header: 'Email',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
useEffect(() => {
setTableState('customers-table', pathname);
}, [pathname, setTableState]);
const deleteClickHandler = () => {
setSelectedCustomer(props.row.original);
deleteModal.openModal();
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
// Handler
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -202,81 +171,147 @@ const CustomersTable = () => {
toast.success('Successfully delete Customer!');
setIsDeleteLoading(false);
};
const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
updateFilter('search', e.target.value);
};
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
};
const customersColumns: ColumnDef<Customer>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorFn: (row) => row.pic?.name ?? '-',
header: 'PIC',
},
{
accessorKey: 'type',
header: 'Type',
},
{
accessorKey: 'phone',
header: 'Phone',
},
{
accessorKey: 'email',
header: 'Email',
},
{
header: 'Aksi',
cell: (props: CellContext<Customer, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedCustomer(props.row.original);
deleteModal.openModal();
};
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.customer.create'>
<Button
href='/master-data/customer/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Kandang'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.customer.create'>
<Button
href='/master-data/customer/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Customer
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
</div>
</div>
<Table<Customer>
data={isResponseSuccess(customers) ? customers?.data : []}
columns={customersColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(customers) ? customers?.meta?.page : 0}
totalItems={
isResponseSuccess(customers) ? customers?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(customers) && customers?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(customers) || customers.data?.length === 0 ? (
<div className='p-3'>
<CustomerTableSkeleton
columns={customersColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Customer>
data={customers?.data}
columns={customersColumns}
pageSize={tableFilterState.pageSize}
page={customers?.meta?.page ?? 0}
totalItems={customers?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Customer } from '@/types/api/master-data/customer';
import { ColumnDef } from '@tanstack/react-table';
const CustomerTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no customer data displayed. Enter customer data to get started.',
}: {
columns: ColumnDef<Customer>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default CustomerTableSkeleton;
@@ -1,91 +1,111 @@
'use client';
import { CellContext, ColumnDef } from '@tanstack/react-table';
import { Flock } from '@/types/api/master-data/flock';
import { cn } from '@/lib/helper';
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { useState } from 'react';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import { FlockApi } from '@/services/api/master-data';
import { useModal } from '@/components/Modal';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import { ROWS_OPTIONS } from '@/config/constant';
import Table from '@/components/Table';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
const RowsOptions = ({
type = 'dropdown',
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import FlockTableSkeleton from '@/components/pages/master-data/flock/skeleton/FlockTableSkeleton';
import { Flock } from '@/types/api/master-data/flock';
import { FlockApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
const RowOptionsMenu = ({
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Flock, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `flock#${props.row.original.id}`;
const popoverAnchorName = `--anchor-flock#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.flocks.detail'>
<Button
href={`/master-data/flock/detail/?flockId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon
icon='mdi:eye-outline'
width={16}
height={16}
className='justify-start text-sm'
/>
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.flocks.update'>
<Button
href={`/master-data/flock/detail/edit/?flockId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon
icon='material-symbols:edit-outline'
width={16}
height={16}
className='justify-start text-sm'
/>
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.flocks.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.flocks.detail'>
<Button
href={`/master-data/flock/detail/?flockId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.flocks.update'>
<Button
href={`/master-data/flock/detail/edit/?flockId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.flocks.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const FlockTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -93,15 +113,17 @@ const FlockTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '' },
initial: {
search: searchValue,
},
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
},
});
// Fetch Data
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: flocks,
isLoading,
@@ -111,74 +133,25 @@ const FlockTable = () => {
FlockApi.getAllFetcher
);
// State
const deleteModal = useModal();
const [selectedFlock, setSelectedFlock] = useState<Flock | undefined>(
undefined
);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
// Columns Definition
const flocksColumns: ColumnDef<Flock>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'created_at',
header: 'Dibuat pada',
cell: (props) =>
new Date(props.row.original.created_at).toLocaleDateString(),
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
useEffect(() => {
setTableState('flocks-table', pathname);
}, [pathname, setTableState]);
const deleteClickHandler = () => {
setSelectedFlock(props.row.original);
deleteModal.openModal();
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowsOptions
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowsOptions
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
// Handler
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -196,85 +169,143 @@ const FlockTable = () => {
toast.success('Successfully delete Flock!');
setIsDeleteLoading(false);
};
const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
updateFilter('search', e.target.value);
};
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
};
const flocksColumns: ColumnDef<Flock>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'created_at',
header: 'Dibuat pada',
cell: (props) =>
new Date(props.row.original.created_at).toLocaleDateString('id-ID'),
},
{
header: 'Aksi',
cell: (props: CellContext<Flock, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedFlock(props.row.original);
deleteModal.openModal();
};
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.flocks.create'>
<Button
href='/master-data/flock/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Flock'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.flocks.create'>
<Button
href='/master-data/flock/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Flock
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
</div>
</div>
<Table<Flock>
data={isResponseSuccess(flocks) ? flocks?.data : []}
columns={flocksColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(flocks) ? flocks?.meta?.page : 0}
totalItems={
isResponseSuccess(flocks) ? flocks?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
className={{
containerClassName: cn({
'mb-20': isResponseSuccess(flocks) && flocks?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(flocks) || flocks.data?.length === 0 ? (
<div className='p-3'>
<FlockTableSkeleton
columns={flocksColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Flock>
data={flocks?.data}
columns={flocksColumns}
pageSize={tableFilterState.pageSize}
page={flocks?.meta?.page ?? 0}
totalItems={flocks?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Supplier ini (${selectedFlock?.name})?`}
text={`Apakah anda yakin ingin menghapus data Flock ini (${selectedFlock?.name})?`}
secondaryButton={{
text: 'Tidak',
}}
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Flock } from '@/types/api/master-data/flock';
import { ColumnDef } from '@tanstack/react-table';
const FlockTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no flock data displayed. Enter flock data to get started.',
}: {
columns: ColumnDef<Flock>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default FlockTableSkeleton;
@@ -1,90 +1,130 @@
'use client';
import { ChangeEventHandler, useCallback, useEffect, useState } from 'react';
import useSWR from 'swr';
import {
CellContext,
ColumnDef,
ColumnSort,
SortingState,
} from '@tanstack/react-table';
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import { useFormik } from 'formik';
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import KandangTableSkeleton from '@/components/pages/master-data/kandang/skeleton/KandangTableSkeleton';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';
import { Kandang } from '@/types/api/master-data/kandang';
import { KandangApi } from '@/services/api/master-data';
import { cn, formatNumber } from '@/lib/helper';
import { Location } from '@/types/api/master-data/location';
import { KandangApi, LocationApi } from '@/services/api/master-data';
import { UserApi } from '@/services/api/user';
import { User } from '@/types/api/api-general';
import { formatNumber } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { useUiStore } from '@/stores/ui/ui.store';
import {
KandangFilterSchema,
KandangFilterType,
} from '@/components/pages/master-data/kandang/filter/KandangFilter';
import SelectInputRadio from '@/components/input/SelectInputRadio';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Kandang, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `kandang#${props.row.original.id}`;
const popoverAnchorName = `--anchor-kandang#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.kandangs.detail'>
<Button
href={`/master-data/kandang/detail/?kandangId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.kandangs.update'>
<Button
href={`/master-data/kandang/detail/edit/?kandangId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.kandangs.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.kandangs.detail'>
<Button
href={`/master-data/kandang/detail/?kandangId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.kandangs.update'>
<Button
href={`/master-data/kandang/detail/edit/?kandangId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.kandangs.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const KandangsTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -94,21 +134,112 @@ const KandangsTable = () => {
} = useTableFilter({
initial: {
search: '',
nameSort: '',
locationSort: '',
capacitySort: '',
picSort: '',
locationFilter: '',
picFilter: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
locationSort: 'sort_location',
capacitySort: 'sort_capacity',
picSort: ' sort_pic',
locationFilter: 'location_id',
picFilter: 'pic_id',
},
});
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FORMIK SETUP =====
const formik = useFormik<KandangFilterType>({
initialValues: {
location_id: null,
pic_id: null,
},
validationSchema: KandangFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('locationFilter', values.location_id || '');
updateFilter('picFilter', values.pic_id || '');
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('locationFilter', '');
updateFilter('picFilter', '');
},
});
// ===== LOCATION OPTIONS =====
const {
setInputValue: setLocationInputValue,
options: locationOptions,
isLoadingOptions: isLoadingLocationOptions,
loadMore: loadMoreLocations,
} = useSelect<Location>(
filterModal.open ? LocationApi.basePath : null,
'id',
'name',
'search'
);
// ===== PIC OPTIONS =====
const {
setInputValue: setPicInputValue,
options: picOptions,
isLoadingOptions: isLoadingPicOptions,
loadMore: loadMorePics,
} = useSelect<User>(
filterModal.open ? UserApi.basePath : null,
'id',
'name',
'search'
);
// ===== FILTER HANDLERS =====
const handleFilterLocationChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const location = val as OptionType | null;
const locationId = location?.value ? String(location.value) : null;
formik.setFieldValue('location_id', locationId);
},
[formik]
);
const handleFilterPicChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const pic = val as OptionType | null;
const picId = pic?.value ? String(pic.value) : null;
formik.setFieldValue('pic_id', picId);
},
[formik]
);
// ===== FILTER HELPERS =====
const locationIdValue = useMemo(() => {
if (!formik.values.location_id) return null;
return (
locationOptions.find(
(opt) => String(opt.value) === formik.values.location_id
) || null
);
}, [formik.values.location_id, locationOptions]);
const picIdValue = useMemo(() => {
if (!formik.values.pic_id) return null;
return (
picOptions.find((opt) => String(opt.value) === formik.values.pic_id) ||
null
);
}, [formik.values.pic_id, picOptions]);
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
filterModal.openModal();
formik.validateForm();
};
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: kandangs,
isLoading,
@@ -119,82 +250,23 @@ const KandangsTable = () => {
);
const deleteModal = useModal();
const [selectedKandang, setSelectedKandang] = useState<Kandang | undefined>(
undefined
);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const kandangsColumns: ColumnDef<Kandang>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'location',
header: 'Lokasi',
cell: (props) => props.row.original.location.name,
},
{
accessorKey: 'capacity',
header: 'Kapasitas',
cell: (props) => formatNumber(props.row.original.capacity ?? 0),
},
{
accessorKey: 'pic',
header: 'PIC',
cell: (props) => props.row.original.pic.name,
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
useEffect(() => {
setTableState('kandangs-table', pathname);
}, [pathname, setTableState]);
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedKandang(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -216,114 +288,150 @@ const KandangsTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const kandangsColumns: ColumnDef<Kandang>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorFn: (row) => row.location?.name ?? '-',
header: 'Lokasi',
},
{
accessorKey: 'capacity',
header: 'Kapasitas',
cell: (props) => formatNumber(props.row.original.capacity ?? 0),
},
{
accessorFn: (row) => row.pic?.name ?? '-',
header: 'PIC',
},
{
header: 'Aksi',
cell: (props: CellContext<Kandang, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
setPageSize(newVal.value as number);
};
const deleteClickHandler = () => {
setSelectedKandang(props.row.original);
deleteModal.openModal();
};
const updateSortingFilter = useCallback(
(
sortName: Exclude<keyof typeof tableFilterState, 'page' | 'pageSize'>,
sortFilter: ColumnSort | undefined
) => {
if (!sortFilter) {
updateFilter(sortName, '');
} else {
updateFilter(sortName, sortFilter.desc ? 'desc' : 'asc');
}
},
[updateFilter]
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
// track sorting
useEffect(() => {
const nameSortFilter = sorting.find((sortItem) => sortItem.id === 'name');
const locationSortFilter = sorting.find(
(sortItem) => sortItem.id === 'location'
);
const picSortFilter = sorting.find((sortItem) => sortItem.id === 'pic');
updateSortingFilter('nameSort', nameSortFilter);
updateSortingFilter('locationSort', locationSortFilter);
updateSortingFilter('picSort', picSortFilter);
}, [sorting, updateSortingFilter]);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.kandangs.create'>
<Button
href='/master-data/kandang/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Kandang'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.kandangs.create'>
<Button
href='/master-data/kandang/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Kandang
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
<Table<Kandang>
data={isResponseSuccess(kandangs) ? kandangs?.data : []}
columns={kandangsColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(kandangs) ? kandangs?.meta?.page : 0}
totalItems={
isResponseSuccess(kandangs) ? kandangs?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(kandangs) && kandangs?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(kandangs) || kandangs.data?.length === 0 ? (
<div className='p-3'>
<KandangTableSkeleton
columns={kandangsColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Kandang>
data={kandangs?.data}
columns={kandangsColumns}
pageSize={tableFilterState.pageSize}
page={kandangs?.meta?.page ?? 0}
totalItems={kandangs?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -340,6 +448,81 @@ const KandangsTable = () => {
onClick: confirmationModalDeleteClickHandler,
}}
/>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInput
label='Lokasi'
placeholder='Pilih Lokasi'
options={locationOptions}
value={locationIdValue}
onChange={handleFilterLocationChange}
onInputChange={setLocationInputValue}
isLoading={isLoadingLocationOptions}
isClearable
onMenuScrollToBottom={loadMoreLocations}
className={{ wrapper: 'w-full' }}
/>
<SelectInputRadio
label='PIC'
placeholder='Pilih PIC'
options={picOptions}
value={picIdValue}
onChange={handleFilterPicChange}
onInputChange={setPicInputValue}
isLoading={isLoadingPicOptions}
isClearable
onMenuScrollToBottom={loadMorePics}
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
formik.resetForm();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
</>
);
};
@@ -0,0 +1,11 @@
import { string, object } from 'yup';
export const KandangFilterSchema = object().shape({
location_id: string().nullable(),
pic_id: string().nullable(),
});
export type KandangFilterType = {
location_id: string | null;
pic_id: string | null;
};
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Kandang } from '@/types/api/master-data/kandang';
import { ColumnDef } from '@tanstack/react-table';
const KandangTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no kandang data displayed. Enter kandang data to get started.',
}: {
columns: ColumnDef<Kandang>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default KandangTableSkeleton;
@@ -1,90 +1,126 @@
'use client';
import { ChangeEventHandler, useCallback, useEffect, useState } from 'react';
import useSWR from 'swr';
import {
CellContext,
ColumnDef,
ColumnSort,
SortingState,
} from '@tanstack/react-table';
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import { useFormik } from 'formik';
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import LocationTableSkeleton from '@/components/pages/master-data/location/skeleton/LocationTableSkeleton';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';
import { Location } from '@/types/api/master-data/location';
import { LocationApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { Area } from '@/types/api/master-data/area';
import { LocationApi, AreaApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { useUiStore } from '@/stores/ui/ui.store';
import {
LocationFilterSchema,
LocationFilterType,
} from '@/components/pages/master-data/location/filter/LocationFilter';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Location, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `location#${props.row.original.id}`;
const popoverAnchorName = `--anchor-location#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.locations.detail'>
<Button
href={`/master-data/location/detail/?locationId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.locations.update'>
<Button
href={`/master-data/location/detail/edit/?locationId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.locations.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.locations.detail'>
<Button
href={`/master-data/location/detail/?locationId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.locations.update'>
<Button
href={`/master-data/location/detail/edit/?locationId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.locations.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const LocationsTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -92,16 +128,75 @@ const LocationsTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '', addressSort: '', areaSort: '' },
initial: {
search: '',
areaFilter: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
addressSort: 'sort_address',
areaSort: ' sort_area',
areaFilter: 'area_id',
},
});
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FORMIK SETUP =====
const formik = useFormik<LocationFilterType>({
initialValues: {
area_id: null,
},
validationSchema: LocationFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('areaFilter', values.area_id || '');
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('areaFilter', '');
},
});
// ===== AREA OPTIONS =====
const {
setInputValue: setAreaInputValue,
options: areaOptions,
isLoadingOptions: isLoadingAreaOptions,
loadMore: loadMoreAreas,
} = useSelect<Area>(
filterModal.open ? AreaApi.basePath : null,
'id',
'name',
'search'
);
// ===== FILTER HANDLERS =====
const handleFilterAreaChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const area = val as OptionType | null;
const areaId = area?.value ? String(area.value) : null;
formik.setFieldValue('area_id', areaId);
},
[formik]
);
// ===== FILTER HELPERS =====
const areaIdValue = useMemo(() => {
if (!formik.values.area_id) return null;
return (
areaOptions.find((opt) => String(opt.value) === formik.values.area_id) ||
null
);
}, [formik.values.area_id, areaOptions]);
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
filterModal.openModal();
formik.validateForm();
};
const {
data: locations,
isLoading,
@@ -112,76 +207,25 @@ const LocationsTable = () => {
);
const deleteModal = useModal();
const [selectedLocation, setSelectedLocation] = useState<
Location | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
useEffect(() => {
setTableState('locations-table', pathname);
}, [pathname, setTableState]);
const [sorting, setSorting] = useState<SortingState>([]);
const locationsColumns: ColumnDef<Location>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'address',
header: 'Alamat',
},
{
accessorKey: 'area',
header: 'Area',
cell: (props) => props.row.original.area.name,
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedLocation(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -203,114 +247,145 @@ const LocationsTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const locationsColumns: ColumnDef<Location>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'address',
header: 'Alamat',
},
{
accessorFn: (row) => row.area?.name ?? '-',
header: 'Area',
},
{
header: 'Aksi',
cell: (props: CellContext<Location, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
setPageSize(newVal.value as number);
};
const deleteClickHandler = () => {
setSelectedLocation(props.row.original);
deleteModal.openModal();
};
const updateSortingFilter = useCallback(
(
sortName: Exclude<keyof typeof tableFilterState, 'page' | 'pageSize'>,
sortFilter: ColumnSort | undefined
) => {
if (!sortFilter) {
updateFilter(sortName, '');
} else {
updateFilter(sortName, sortFilter.desc ? 'desc' : 'asc');
}
},
[updateFilter]
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
// track sorting
useEffect(() => {
const nameSortFilter = sorting.find((sortItem) => sortItem.id === 'name');
const addressSortFilter = sorting.find(
(sortItem) => sortItem.id === 'address'
);
const areaSortFilter = sorting.find((sortItem) => sortItem.id === 'area');
updateSortingFilter('nameSort', nameSortFilter);
updateSortingFilter('addressSort', addressSortFilter);
updateSortingFilter('areaSort', areaSortFilter);
}, [sorting, updateSortingFilter]);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.locations.create'>
<Button
href='/master-data/location/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Location'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.locations.create'>
<Button
href='/master-data/location/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Location
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
<Table<Location>
data={isResponseSuccess(locations) ? locations?.data : []}
columns={locationsColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(locations) ? locations?.meta?.page : 0}
totalItems={
isResponseSuccess(locations) ? locations?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(locations) && locations?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(locations) || locations.data?.length === 0 ? (
<div className='p-3'>
<LocationTableSkeleton
columns={locationsColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Location>
data={locations?.data}
columns={locationsColumns}
pageSize={tableFilterState.pageSize}
page={locations?.meta?.page ?? 0}
totalItems={locations?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -327,6 +402,68 @@ const LocationsTable = () => {
onClick: confirmationModalDeleteClickHandler,
}}
/>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInput
label='Area'
placeholder='Pilih Area'
options={areaOptions}
value={areaIdValue}
onChange={handleFilterAreaChange}
onInputChange={setAreaInputValue}
isLoading={isLoadingAreaOptions}
isClearable
onMenuScrollToBottom={loadMoreAreas}
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
formik.resetForm();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
</>
);
};
@@ -0,0 +1,9 @@
import { string, object } from 'yup';
export const LocationFilterSchema = object().shape({
area_id: string().nullable(),
});
export type LocationFilterType = {
area_id: string | null;
};
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Location } from '@/types/api/master-data/location';
import { ColumnDef } from '@tanstack/react-table';
const LocationTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no location data displayed. Enter location data to get started.',
}: {
columns: ColumnDef<Location>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default LocationTableSkeleton;
@@ -1,13 +1,8 @@
'use client';
import { ChangeEventHandler, useCallback, useEffect, useState } from 'react';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import {
CellContext,
ColumnDef,
ColumnSort,
SortingState,
} from '@tanstack/react-table';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import { Icon } from '@iconify/react';
@@ -16,75 +11,101 @@ import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import NonstockTableSkeleton from '@/components/pages/master-data/nonstock/skeleton/NonstockTableSkeleton';
import { Nonstock } from '@/types/api/master-data/nonstock';
import { NonstockApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Nonstock, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `nonstock#${props.row.original.id}`;
const popoverAnchorName = `--anchor-nonstock#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.nonstocks.detail'>
<Button
href={`/master-data/nonstock/detail/?nonstockId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.nonstocks.update'>
<Button
href={`/master-data/nonstock/detail/edit/?nonstockId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.nonstocks.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.nonstocks.detail'>
<Button
href={`/master-data/nonstock/detail/?nonstockId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.nonstocks.update'>
<Button
href={`/master-data/nonstock/detail/edit/?nonstockId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.nonstocks.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const NonstocksTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -92,16 +113,25 @@ const NonstocksTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '', locationSort: '', picSort: '' },
initial: {
search: searchValue,
},
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
locationSort: 'sort_location',
picSort: ' sort_pic',
},
});
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
useEffect(() => {
setTableState('nonstocks-table', pathname);
}, [pathname, setTableState]);
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: nonstocks,
isLoading,
@@ -112,88 +142,15 @@ const NonstocksTable = () => {
);
const deleteModal = useModal();
const [selectedNonstock, setSelectedNonstock] = useState<
Nonstock | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
const nonstocksColumns: ColumnDef<Nonstock>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'uom',
header: 'UOM',
cell: (props) => props.row.original.uom.name,
},
{
accessorKey: 'suppliers',
header: 'Supplier',
cell: (props) => {
const supplierNames = props.row.original.suppliers.map(
(supplier) => supplier.name
);
return supplierNames.join(', ') || '-';
},
},
{
accessorKey: 'flags',
header: 'Flag',
cell: (props) => props.row.original.flags?.join(', ') || '-',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedNonstock(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -215,112 +172,143 @@ const NonstocksTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const nonstocksColumns: ColumnDef<Nonstock>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorFn: (row) => row.uom?.name ?? '-',
header: 'UOM',
},
{
accessorFn: (row) =>
row.suppliers?.map((supplier) => supplier.name).join(', ') || '-',
header: 'Supplier',
},
{
accessorFn: (row) => row.flags?.join(', ') || '-',
header: 'Flag',
},
{
header: 'Aksi',
cell: (props: CellContext<Nonstock, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
setPageSize(newVal.value as number);
};
const deleteClickHandler = () => {
setSelectedNonstock(props.row.original);
deleteModal.openModal();
};
const updateSortingFilter = useCallback(
(
sortName: Exclude<keyof typeof tableFilterState, 'page' | 'pageSize'>,
sortFilter: ColumnSort | undefined
) => {
if (!sortFilter) {
updateFilter(sortName, '');
} else {
updateFilter(sortName, sortFilter.desc ? 'desc' : 'asc');
}
},
[updateFilter]
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
// track sorting
useEffect(() => {
const nameSortFilter = sorting.find((sortItem) => sortItem.id === 'name');
const locationSortFilter = sorting.find(
(sortItem) => sortItem.id === 'location'
);
const picSortFilter = sorting.find((sortItem) => sortItem.id === 'pic');
updateSortingFilter('nameSort', nameSortFilter);
updateSortingFilter('locationSort', locationSortFilter);
updateSortingFilter('picSort', picSortFilter);
}, [sorting]);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.nonstocks.create'>
<Button
href='/master-data/nonstock/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Nonstock'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.nonstocks.create'>
<Button
href='/master-data/nonstock/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Nonstock
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
</div>
</div>
<Table<Nonstock>
data={isResponseSuccess(nonstocks) ? nonstocks?.data : []}
columns={nonstocksColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(nonstocks) ? nonstocks?.meta?.page : 0}
totalItems={
isResponseSuccess(nonstocks) ? nonstocks?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(nonstocks) && nonstocks?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(nonstocks) || nonstocks.data?.length === 0 ? (
<div className='p-3'>
<NonstockTableSkeleton
columns={nonstocksColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Nonstock>
data={nonstocks?.data}
columns={nonstocksColumns}
pageSize={tableFilterState.pageSize}
page={nonstocks?.meta?.page ?? 0}
totalItems={nonstocks?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -17,7 +17,7 @@ export const NonstockFormSchema = Yup.object({
})
),
flags: Yup.array().of(Yup.string()).notRequired(),
flags: Yup.boolean().default(false),
});
export const UpdateNonstockFormSchema = NonstockFormSchema;
@@ -12,6 +12,7 @@ import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import { RadioGroup } from '@/components/input/RadioInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
@@ -29,8 +30,7 @@ import {
} from '@/types/api/master-data/nonstock';
import { NonstockApi, SupplierApi, UomApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { flags } from '@/types/api/api-general';
import { SUPPLIER_FLAG_OPTIONS } from '@/config/constant';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { Supplier } from '@/types/api/master-data/supplier';
@@ -97,7 +97,7 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
label: supplier.name,
})) ?? [],
flags: initialValues?.flags ?? [],
flags: initialValues?.flags?.includes('EKSPEDISI') ?? false,
};
}, [initialValues]);
@@ -112,7 +112,7 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
name: values.name,
uom_id: values.uomId,
supplier_ids: values.supplierIds as number[],
flags: values.flags as flags[],
flags: values.flags ? ['EKSPEDISI'] : [],
};
switch (type) {
@@ -183,12 +183,8 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
router.push('/master-data/nonstock');
};
const flagsChangeHandler = (val: OptionType | OptionType[] | null) => {
const formattedFlags = (val as OptionType[]).map(
(flag) => flag.value as string
);
formik.setFieldValue('flags', formattedFlags);
const expeditionChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
formik.setFieldValue('flags', e.target.value === 'true');
};
useEffect(() => {
@@ -268,18 +264,19 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
isDisabled={type === 'detail'}
/>
<SelectInput
label='Flags'
isMulti
value={SUPPLIER_FLAG_OPTIONS.filter((opt) =>
formik.values.flags?.includes(opt.value)
)}
onChange={flagsChangeHandler}
options={SUPPLIER_FLAG_OPTIONS}
<RadioGroup
label='Flags Ekspedisi'
name='flags'
value={String(formik.values.flags)}
onChange={expeditionChangeHandler}
onBlur={formik.handleBlur}
options={[
{ label: 'Ya', value: 'true' },
{ label: 'Tidak', value: 'false' },
]}
isError={formik.touched.flags && Boolean(formik.errors.flags)}
errorMessage={formik.errors.flags as string}
isDisabled={type === 'detail'}
isClearable
disabled={type === 'detail'}
/>
</div>
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Nonstock } from '@/types/api/master-data/nonstock';
import { ColumnDef } from '@tanstack/react-table';
const NonstockTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no nonstock data displayed. Enter nonstock data to get started.',
}: {
columns: ColumnDef<Nonstock>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default NonstockTableSkeleton;
@@ -1,6 +1,7 @@
'use client';
import { ChangeEventHandler, useEffect, useRef, useState } from 'react';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
@@ -11,78 +12,99 @@ import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import ProductCategoryTableSkeleton from '@/components/pages/master-data/product-category/skeleton/ProductCategoryTableSkeleton';
import { ProductCategory } from '@/types/api/master-data/product-category';
import { ProductCategoryApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { useUiStore } from '@/stores/ui/ui.store';
import { ROWS_OPTIONS } from '@/config/constant';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<ProductCategory, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `product-category#${props.row.original.id}`;
const popoverAnchorName = `--anchor-product-category#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.product_categories.detail'>
<Button
href={`/master-data/product-category/detail/?productCategoryId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.product_categories.update'>
<Button
href={`/master-data/product-category/detail/edit/?productCategoryId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='mdi:pencil-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.product_categories.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='mdi:delete-outline'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.product_categories.detail'>
<Button
href={`/master-data/product-category/detail/?productCategoryId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.product_categories.update'>
<Button
href={`/master-data/product-category/detail/edit/?productCategoryId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.product_categories.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const ProductCategoryTable = () => {
const { searchValue, setSearchValue, resetSearchValue } = useUiStore();
const previousPathRef = useRef<string | null>(null);
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
@@ -91,10 +113,21 @@ const ProductCategoryTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: searchValue, nameSort: '' },
paramMap: { page: 'page', pageSize: 'limit', nameSort: 'sort_name' },
initial: {
search: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
},
});
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: productCategories,
isLoading,
@@ -105,71 +138,15 @@ const ProductCategoryTable = () => {
);
const deleteModal = useModal();
const [selectedProductCategory, setSelectedProductCategory] = useState<
ProductCategory | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
const productCategoryColumns: ColumnDef<ProductCategory>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'code',
header: 'Code',
},
{
accessorKey: 'name',
header: 'Nama',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedProductCategory(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -191,123 +168,141 @@ const ProductCategoryTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const productCategoryColumns: ColumnDef<ProductCategory>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'code',
header: 'Code',
},
{
accessorKey: 'name',
header: 'Nama',
},
{
header: 'Aksi',
cell: (props: CellContext<ProductCategory, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
};
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedProductCategory(props.row.original);
deleteModal.openModal();
};
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
useEffect(() => {
// Store current path on mount
previousPathRef.current = window.location.pathname;
return () => {
const currentPath = window.location.pathname;
// if both paths are within /master-data/product-category module
const isCurrentPathProductCategory = currentPath.includes(
'/master-data/product-category'
);
const isPreviousPathProductCategory = previousPathRef.current?.includes(
'/master-data/product-category'
);
// reset if we outside product category module entirely
if (isPreviousPathProductCategory && !isCurrentPathProductCategory) {
resetSearchValue();
}
};
}, [resetSearchValue]);
useEffect(() => {
const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
if (!isNameSorted) {
updateFilter('nameSort', '');
} else {
updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
}
}, [sorting, updateFilter]);
setTableState('product-category-table', pathname);
}, [pathname, setTableState]);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.product_categories.create'>
<Button
href='/master-data/product-category/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.product_categories.create'>
<Button
href='/master-data/product-category/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Product Category
</Button>
</RequirePermission>
</div>
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Cari Product Category'
value={tableFilterState.search}
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
</div>
</div>
<Table<ProductCategory>
data={
isResponseSuccess(productCategories) ? productCategories?.data : []
}
columns={productCategoryColumns}
pageSize={tableFilterState.pageSize}
page={
isResponseSuccess(productCategories)
? productCategories?.meta?.page
: 0
}
totalItems={
isResponseSuccess(productCategories)
? productCategories?.meta?.total_results
: 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(productCategories) &&
productCategories?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(productCategories) ||
productCategories.data?.length === 0 ? (
<div className='p-3'>
<ProductCategoryTableSkeleton
columns={productCategoryColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<ProductCategory>
data={productCategories?.data}
columns={productCategoryColumns}
pageSize={tableFilterState.pageSize}
page={productCategories?.meta?.page ?? 0}
totalItems={productCategories?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { ProductCategory } from '@/types/api/master-data/product-category';
import { ColumnDef } from '@tanstack/react-table';
const ProductCategoryTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no product category data displayed. Enter product category data to get started.',
}: {
columns: ColumnDef<ProductCategory>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default ProductCategoryTableSkeleton;
@@ -1,86 +1,127 @@
'use client';
import { ChangeEventHandler, useCallback, useEffect, useState } from 'react';
import useSWR from 'swr';
import {
CellContext,
ColumnDef,
ColumnSort,
SortingState,
} from '@tanstack/react-table';
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import { useFormik } from 'formik';
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import ProductTableSkeleton from '@/components/pages/master-data/product/skeleton/ProductTableSkeleton';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';
import { Product } from '@/types/api/master-data/product';
import { ProductApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { ProductCategory } from '@/types/api/master-data/product-category';
import { ProductApi, ProductCategoryApi } from '@/services/api/master-data';
import { formatCurrency } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { useUiStore } from '@/stores/ui/ui.store';
import {
ProductFilterSchema,
ProductFilterType,
} from '@/components/pages/master-data/product/filter/ProductFilter';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Product, unknown>;
deleteClickHandler: () => void;
}) => (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.products.detail'>
<Button
href={`/master-data/product/detail/?productId=${props.row.original.id}`}
}) => {
const popoverId = `product#${props.row.original.id}`;
const popoverAnchorName = `--anchor-product#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='primary'
className='justify-start text-sm'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.products.update'>
<Button
href={`/master-data/product/detail/edit/?productId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.products.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
);
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.products.detail'>
<Button
href={`/master-data/product/detail/?productId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.products.update'>
<Button
href={`/master-data/product/detail/edit/?productId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.products.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const ProductsTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -90,21 +131,80 @@ const ProductsTable = () => {
} = useTableFilter({
initial: {
search: '',
nameSort: '',
skuSort: '',
brandSort: '',
categorySort: '',
productCategoryFilter: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
skuSort: 'sort_sku',
brandSort: 'sort_brand',
categorySort: 'sort_category',
productCategoryFilter: 'product_category_id',
},
});
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FORMIK SETUP =====
const formik = useFormik<ProductFilterType>({
initialValues: {
product_category_id: null,
},
validationSchema: ProductFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('productCategoryFilter', values.product_category_id || '');
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('productCategoryFilter', '');
},
});
// ===== PRODUCT CATEGORY OPTIONS =====
const {
setInputValue: setProductCategoryInputValue,
options: productCategoryOptions,
isLoadingOptions: isLoadingProductCategoryOptions,
loadMore: loadMoreProductCategories,
} = useSelect<ProductCategory>(
filterModal.open ? ProductCategoryApi.basePath : null,
'id',
'name',
'search'
);
// ===== FILTER HANDLERS =====
const handleFilterProductCategoryChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const category = val as OptionType | null;
const categoryId = category?.value ? String(category.value) : null;
formik.setFieldValue('product_category_id', categoryId);
},
[formik]
);
// ===== FILTER HELPERS =====
const productCategoryIdValue = useMemo(() => {
if (!formik.values.product_category_id) return null;
return (
productCategoryOptions.find(
(opt) => String(opt.value) === formik.values.product_category_id
) || null
);
}, [formik.values.product_category_id, productCategoryOptions]);
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
filterModal.openModal();
formik.validateForm();
};
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: products,
isLoading,
@@ -119,114 +219,15 @@ const ProductsTable = () => {
undefined
);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
const productsColumns: ColumnDef<Product>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'sku',
header: 'SKU',
},
{
accessorKey: 'brand',
header: 'Merek',
},
{
accessorKey: 'product_category',
header: 'Kategori',
cell: (props) => props.row.original.product_category?.name ?? '-',
},
{
accessorKey: 'uom',
header: 'Satuan',
cell: (props) => props.row.original.uom?.name ?? '-',
},
{
accessorKey: 'product_price',
header: 'Harga Produk',
cell: (props) =>
props.row.original.product_price?.toLocaleString() ?? '-',
},
{
accessorKey: 'selling_price',
header: 'Harga Jual',
cell: (props) =>
props.row.original.selling_price?.toLocaleString() ?? '-',
},
{
accessorKey: 'tax',
header: 'Pajak (%)',
cell: (props) => props.row.original.tax ?? '-',
},
{
accessorKey: 'expiry_period',
header: 'Kadaluarsa (hari)',
cell: (props) => props.row.original.expiry_period ?? '-',
},
{
accessorKey: 'suppliers',
header: 'Supplier',
cell: (props) =>
props.row.original.suppliers?.map((s) => s.name).join(', ') || '-',
},
{
accessorKey: 'flags',
header: 'Flags',
cell: (props) =>
props.row.original.flags?.length
? props.row.original.flags.join(', ')
: '-',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
useEffect(() => {
setTableState('product-table', pathname);
}, [pathname, setTableState]);
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedProduct(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -248,110 +249,197 @@ const ProductsTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const productsColumns: ColumnDef<Product>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'sku',
header: 'SKU',
},
{
accessorKey: 'brand',
header: 'Merek',
},
{
accessorFn: (row) => row.product_category?.name ?? '-',
header: 'Kategori',
},
{
accessorFn: (row) => row.uom?.name ?? '-',
header: 'Satuan',
},
{
accessorKey: 'product_price',
header: 'Harga Produk',
cell: (props) =>
props.row.original.product_price
? formatCurrency(props.row.original.product_price)
: '-',
},
{
accessorKey: 'selling_price',
header: 'Harga Jual',
cell: (props) =>
props.row.original.selling_price
? formatCurrency(props.row.original.selling_price)
: '-',
},
{
accessorKey: 'tax',
header: 'Pajak (%)',
cell: (props) => props.row.original.tax ?? '-',
},
{
accessorKey: 'expiry_period',
header: 'Kadaluarsa (hari)',
cell: (props) => props.row.original.expiry_period ?? '-',
},
{
accessorFn: (row) =>
row.suppliers?.map((s) => s.name).join(', ') || '-',
header: 'Supplier',
},
{
accessorKey: 'flag',
header: 'Flag',
cell: (props) =>
props.row.original.flag ? props.row.original.flag : '-',
},
{
accessorFn: (row) =>
row.sub_flags?.length ? row.sub_flags.join(', ') : '-',
header: 'Kategori Flags',
},
{
header: 'Aksi',
cell: (props: CellContext<Product, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
};
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const updateSortingFilter = useCallback(
(
sortName: Exclude<keyof typeof tableFilterState, 'page' | 'pageSize'>,
sortFilter: ColumnSort | undefined
) => {
if (!sortFilter) {
updateFilter(sortName, '');
} else {
updateFilter(sortName, sortFilter.desc ? 'desc' : 'asc');
}
},
[updateFilter]
const deleteClickHandler = () => {
setSelectedProduct(props.row.original);
deleteModal.openModal();
};
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
useEffect(() => {
const nameSortFilter = sorting.find((sortItem) => sortItem.id === 'name');
const skuSortFilter = sorting.find((sortItem) => sortItem.id === 'sku');
const brandSortFilter = sorting.find((sortItem) => sortItem.id === 'brand');
const categorySortFilter = sorting.find(
(sortItem) => sortItem.id === 'product_category'
);
updateSortingFilter('nameSort', nameSortFilter);
updateSortingFilter('skuSort', skuSortFilter);
updateSortingFilter('brandSort', brandSortFilter);
updateSortingFilter('categorySort', categorySortFilter);
}, [sorting, updateSortingFilter]);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.products.create'>
<Button
href='/master-data/product/add'
variant='outline'
className='w-full sm:w-fit'
color='primary'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.products.create'>
<Button
href='/master-data/product/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Product
</Button>
</RequirePermission>
</div>
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Cari Produk'
value={tableFilterState.search}
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
<Table<Product>
data={isResponseSuccess(products) ? products?.data : []}
columns={productsColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(products) ? products?.meta?.page : 0}
totalItems={
isResponseSuccess(products) ? products?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(products) && products?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(products) || products.data?.length === 0 ? (
<div className='p-3'>
<ProductTableSkeleton
columns={productsColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Product>
data={products?.data}
columns={productsColumns}
pageSize={tableFilterState.pageSize}
page={products?.meta?.page ?? 0}
totalItems={products?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
@@ -366,6 +454,68 @@ const ProductsTable = () => {
onClick: confirmationModalDeleteClickHandler,
}}
/>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInput
label='Kategori Produk'
placeholder='Pilih Kategori Produk'
options={productCategoryOptions}
value={productCategoryIdValue}
onChange={handleFilterProductCategoryChange}
onInputChange={setProductCategoryInputValue}
isLoading={isLoadingProductCategoryOptions}
isClearable
onMenuScrollToBottom={loadMoreProductCategories}
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
formik.resetForm();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
</>
);
};
@@ -0,0 +1,9 @@
import { string, object } from 'yup';
export const ProductFilterSchema = object().shape({
product_category_id: string().nullable(),
});
export type ProductFilterType = {
product_category_id: string | null;
};
@@ -1,4 +1,5 @@
import * as Yup from 'yup';
import { PRODUCT_FLAG_MAPPING } from '@/config/constant';
type ProductFormSchemaType = {
name: string;
@@ -25,7 +26,8 @@ type ProductFormSchemaType = {
} | null;
price: number;
}[];
flags: string[];
flag: string;
sub_flags?: string[];
};
export const ProductFormSchema: Yup.ObjectSchema<ProductFormSchemaType> =
@@ -94,10 +96,26 @@ export const ProductFormSchema: Yup.ObjectSchema<ProductFormSchemaType> =
)
.required('Supplier wajib diisi!'),
flags: Yup.array()
flag: Yup.string()
.min(1, 'Flag wajib diisi!')
.required('Flag wajib diisi!')
.typeError('Flag wajib diisi!'),
sub_flags: Yup.array()
.of(Yup.string().required())
.min(1, 'Minimal harus ada 1 flag!')
.required('Flag wajib diisi!'),
.when('flag', {
is: (flag: string) => {
const mapping = PRODUCT_FLAG_MAPPING.options.find(
(opt) => opt.flag.value === flag
);
return mapping?.allow_without_sub_flag === false;
},
then: (schema) =>
schema
.required('Sub flag wajib diisi!')
.min(1, 'Sub flag wajib diisi!'),
otherwise: (schema) => schema,
}),
});
export const UpdateProductFormSchema = ProductFormSchema;
@@ -36,8 +36,16 @@ import {
ProductApi,
} from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { PRODUCT_FLAG_OPTIONS } from '@/config/constant';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import { ConstantsApi } from '@/services/api/constants/constants';
import type {
TransformedConstants,
ProductFlagMapping,
} from '@/types/api/constants/constants';
import useSWR from 'swr';
import { PRODUCT_FLAG_MAPPING } from '@/config/constant';
import { Supplier } from '@/types/api/master-data/supplier';
import Card from '@/components/Card';
import { removeArrayItemAndSync } from '@/lib/utils/formik';
@@ -53,6 +61,24 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
const [productFormErrorMessage, setProductFormErrorMessage] = useState('');
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const {
data: constants,
error: constantsError,
isLoading: isLoadingConstants,
} = useSWR<TransformedConstants | undefined>(
'constants',
ConstantsApi.fetchTransformedConstants.bind(ConstantsApi),
{
shouldRetryOnError: false,
}
);
const productFlagMapping: ProductFlagMapping | null = useMemo(() => {
if (constantsError || !constants?.product_flag_mapping) {
return PRODUCT_FLAG_MAPPING as unknown as ProductFlagMapping;
}
return constants.product_flag_mapping;
}, [constants, constantsError]);
const createProductHandler = useCallback(
async (payload: CreateProductPayload) => {
@@ -110,7 +136,8 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
price: supplier.price,
}))
: [],
flags: initialValues?.flags ?? [],
flag: initialValues?.flag ?? '',
sub_flags: initialValues?.sub_flags ?? [],
}),
[initialValues]
);
@@ -139,7 +166,8 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
supplier_id: s.supplier?.value as number,
price: parseInt(s.price.toString()) || 0,
})),
flags: values.flags.filter((f): f is string => typeof f === 'string'),
flag: values.flag,
sub_flags: values.sub_flags,
};
switch (type) {
case 'add':
@@ -200,6 +228,28 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
});
}, [supplierOptions, formik.values.suppliers]);
const selectedFlagMapping = useMemo(() => {
return productFlagMapping?.options.find(
(opt) => opt.flag.value === formik.values.flag
);
}, [formik.values.flag, productFlagMapping]);
const subFlagOptions = useMemo<OptionType[]>(() => {
return selectedFlagMapping?.sub_flags ?? [];
}, [selectedFlagMapping]);
const selectedSubFlagValues = useMemo<OptionType[]>(() => {
return (
selectedFlagMapping?.sub_flags.filter((subFlag) =>
formik.values.sub_flags?.includes(subFlag.value as string)
) ?? []
);
}, [selectedFlagMapping, formik.values.sub_flags]);
const isSubFlagRequired = useMemo(() => {
return selectedFlagMapping?.allow_without_sub_flag === false;
}, [selectedFlagMapping]);
const addSupplierHandler = () => {
formik.setFieldValue('suppliers', [
...formik.values.suppliers,
@@ -213,7 +263,6 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
const deleteSupplierItemHandler = (idx: number) => {
const path = 'suppliers';
// trims values, errors, and touched at idx
removeArrayItemAndSync(formik, path, idx);
};
@@ -428,26 +477,48 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
readOnly={type === 'detail'}
/>
</div>
<div className='grid sm:grid-cols-1 gap-4'>
<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
<SelectInput
required
label='Flags'
placeholder='Pilih flags...'
isMulti
value={PRODUCT_FLAG_OPTIONS.filter((opt) =>
(formik.values.flags || []).includes(opt.value)
value={productFlagMapping?.flags.find(
(opt) => opt.value === formik.values.flag
)}
onChange={(val) => {
const selectedFlag = String((val as OptionType)?.value ?? '');
formik.setFieldValue('flag', selectedFlag);
formik.setFieldValue('sub_flags', []);
}}
options={productFlagMapping?.flags ?? []}
isLoading={isLoadingConstants && !productFlagMapping}
isError={formik.touched.flag && Boolean(formik.errors.flag)}
errorMessage={formik.errors.flag as string}
isDisabled={type === 'detail'}
isClearable
/>
<SelectInput
label='Kategori Flags'
placeholder='Pilih kategori flags...'
isMulti
required={isSubFlagRequired}
value={selectedSubFlagValues}
onChange={(val) => {
const arr = Array.isArray(val) ? val : val ? [val] : [];
formik.setFieldValue(
'flags',
arr.map((v) => (v as OptionType).value)
'sub_flags',
arr.map((v) => String((v as OptionType).value))
);
}}
options={PRODUCT_FLAG_OPTIONS}
isError={formik.touched.flags && Boolean(formik.errors.flags)}
errorMessage={formik.errors.flags as string}
isDisabled={type === 'detail'}
options={subFlagOptions}
isLoading={isLoadingConstants && !productFlagMapping}
isError={
formik.touched.sub_flags && Boolean(formik.errors.sub_flags)
}
errorMessage={formik.errors.sub_flags as string}
isDisabled={type === 'detail' || !formik.values.flag}
closeMenuOnSelect={false}
isClearable
/>
</div>
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Product } from '@/types/api/master-data/product';
import { ColumnDef } from '@tanstack/react-table';
const ProductTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no product data displayed. Enter product data to get started.',
}: {
columns: ColumnDef<Product>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default ProductTableSkeleton;
@@ -1,92 +1,211 @@
'use client';
import Button from '@/components/Button';
import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
import { ProductionStandard } from '@/types/api/master-data/production-standard';
import { Icon } from '@iconify/react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import { useFormik } from 'formik';
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import Button from '@/components/Button';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import ProductionStandardTableSkeleton from '@/components/pages/master-data/production-standard/skeleton/ProductionStandardTableSkeleton';
import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';
import { ProductionStandard } from '@/types/api/master-data/production-standard';
import { ProductionStandardApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import { CellContext } from '@tanstack/react-table';
import { useModal } from '@/components/Modal';
import { useState } from 'react';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import toast from 'react-hot-toast';
import { cn } from '@/lib/helper';
import RequirePermission from '@/components/helper/RequirePermission';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { useUiStore } from '@/stores/ui/ui.store';
import {
ProductionStandardFilterSchema,
ProductionStandardFilterType,
} from '@/components/pages/master-data/production-standard/filter/ProductionStandardFilter';
import SelectInputRadio from '@/components/input/SelectInputRadio';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<ProductionStandard, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `production-standard#${props.row.original.id}`;
const popoverAnchorName = `--anchor-production-standard#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.production_standards.detail'>
<Button
href={`/master-data/production-standard/detail/?productionStandardId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.production_standards.update'>
<Button
href={`/master-data/production-standard/detail/edit/?productionStandardId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.production_standards.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='text-error hover:text-inherit'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.production_standards.detail'>
<Button
href={`/master-data/production-standard/detail/?productionStandardId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.production_standards.update'>
<Button
href={`/master-data/production-standard/detail/edit/?productionStandardId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.production_standards.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const ProductionStandardTable = () => {
const deleteModal = useModal();
const { setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
setPage,
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: {
projectCategoryFilter: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
projectCategoryFilter: 'project_category',
},
});
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FORMIK SETUP =====
const formik = useFormik<ProductionStandardFilterType>({
initialValues: {
project_category: null,
},
validationSchema: ProductionStandardFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('projectCategoryFilter', values.project_category || '');
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('projectCategoryFilter', '');
},
});
// ===== PROJECT CATEGORY OPTIONS (GROWING or LAYING) =====
const projectCategoryOptions = useMemo(
() => [
{ value: 'GROWING', label: 'Growing' },
{ value: 'LAYING', label: 'Laying' },
],
[]
);
// ===== FILTER HANDLERS =====
const handleFilterProjectCategoryChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const option = val as OptionType | null;
const category = option?.value ? String(option.value) : null;
formik.setFieldValue('project_category', category);
},
[formik]
);
// ===== FILTER HELPERS =====
const projectCategoryValue = useMemo(() => {
if (!formik.values.project_category) return null;
return (
projectCategoryOptions.find(
(opt) => opt.value === formik.values.project_category
) || null
);
}, [formik.values.project_category, projectCategoryOptions]);
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
filterModal.openModal();
formik.validateForm();
};
useEffect(() => {
setTableState('production-standard-table', pathname);
}, [pathname, setTableState]);
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: productionStandards,
isLoading,
mutate: refreshProductionStandards,
} = useSWR(
`${ProductionStandardApi.basePath}${getTableFilterQueryString()}`,
ProductionStandardApi.getAllFetcher
);
const deleteModal = useModal();
const [selectedProductionStandard, setSelectedProductionStandard] = useState<
ProductionStandard | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const { data: productionStandards, mutate: refreshProductionStandards } =
useSWR(
`${ProductionStandardApi.basePath}`,
ProductionStandardApi.getAllFetcher
);
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -107,112 +226,197 @@ const ProductionStandardTable = () => {
setIsDeleteLoading(false);
};
const productionStandardColumns: ColumnDef<ProductionStandard>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorFn: (row) => row.project_category ?? '-',
header: 'Kategori',
},
{
header: 'Aksi',
cell: (props: CellContext<ProductionStandard, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedProductionStandard(props.row.original);
deleteModal.openModal();
};
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
return (
<>
<div className='flex flex-col gap-6 p-6'>
<div className='flex flex-row gap-6 justify-start'>
<RequirePermission permissions='lti.master.production_standards.create'>
<Button
href='/master-data/production-standard/add'
variant='outline'
>
<Icon icon='mdi:plus' /> Tambah
</Button>
</RequirePermission>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.production_standards.create'>
<Button
href='/master-data/production-standard/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Standard Production
</Button>
</RequirePermission>
</div>
{/* Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize']}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
<RequirePermission permissions='lti.master.production_standards.list'>
<Table<ProductionStandard>
data={
isResponseSuccess(productionStandards)
? productionStandards.data
: []
}
columns={[
{
header: 'No',
accessorFn: (row, index) => index + 1,
},
{
header: 'Nama',
accessorKey: 'name',
},
{
header: 'Kategori',
accessorFn: (row) => row.project_category,
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows =
props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows =
currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedProductionStandard(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
]}
className={{
headerColumnClassName: cn(
TABLE_DEFAULT_STYLING.headerColumnClassName,
'last:flex last:flex-row last:justify-end'
),
bodyColumnClassName: cn(
TABLE_DEFAULT_STYLING.bodyColumnClassName,
'last:flex last:flex-row last:justify-end'
),
}}
/>
</RequirePermission>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(productionStandards) ||
productionStandards.data?.length === 0 ? (
<div className='p-3'>
<ProductionStandardTableSkeleton
columns={productionStandardColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<ProductionStandard>
data={productionStandards.data}
columns={productionStandardColumns}
pageSize={tableFilterState.pageSize}
page={productionStandards?.meta?.page ?? 0}
totalItems={productionStandards?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<RequirePermission permissions='lti.master.production_standards.delete'>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Production Standard ini (${selectedProductionStandard?.name})?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isDeleteLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
</RequirePermission>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
text={`Apakah anda yakin ingin menghapus data Production Standard ini (${selectedProductionStandard?.name})?`}
secondaryButton={{
text: 'Tidak',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isDeleteLoading,
onClick: confirmationModalDeleteClickHandler,
}}
/>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInputRadio
label='Kategori'
placeholder='Pilih Kategori'
options={projectCategoryOptions}
value={projectCategoryValue}
onChange={handleFilterProjectCategoryChange}
isClearable
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
formik.resetForm();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
</>
);
};
@@ -0,0 +1,9 @@
import { string, object } from 'yup';
export const ProductionStandardFilterSchema = object().shape({
project_category: string().nullable(),
});
export type ProductionStandardFilterType = {
project_category: string | null;
};
@@ -178,14 +178,7 @@ const ProductionStandardForm = ({
const router = useRouter();
// ===== Store =====
const {
formData,
setFormData,
addDetail,
updateDetail,
deleteDetail,
clearCache,
} = useFormStore();
const { formData, setFormData, clearCache } = useFormStore();
// ===== Formik =====
// Initial values - only recalculate when initialValue changes (for edit/detail mode)
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { ProductionStandard } from '@/types/api/master-data/production-standard';
import { ColumnDef } from '@tanstack/react-table';
const ProductionStandardTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no production standard data displayed. Enter production standard data to get started.',
}: {
columns: ColumnDef<ProductionStandard>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default ProductionStandardTableSkeleton;
@@ -1,91 +1,125 @@
'use client';
import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import Table from '@/components/Table';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import { ROWS_OPTIONS } from '@/config/constant';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { cn } from '@/lib/helper';
import { SupplierApi } from '@/services/api/master-data';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { Supplier } from '@/types/api/master-data/supplier';
import { Icon } from '@iconify/react';
import { CellContext, ColumnDef } from '@tanstack/react-table';
import { useState } from 'react';
import toast from 'react-hot-toast';
import {
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import { useFormik } from 'formik';
const RowOptions = ({
type = 'dropdown',
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import SupplierTableSkeleton from '@/components/pages/master-data/supplier/skeleton/SupplierTableSkeleton';
import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';
import { Supplier } from '@/types/api/master-data/supplier';
import { SupplierApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { useUiStore } from '@/stores/ui/ui.store';
import {
SupplierFilterSchema,
SupplierFilterType,
} from '@/components/pages/master-data/supplier/filter/SupplierFilter';
import SelectInputRadio from '@/components/input/SelectInputRadio';
const RowOptionsMenu = ({
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Supplier, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `supplier#${props.row.original.id}`;
const popoverAnchorName = `--anchor-supplier#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.suppliers.detail'>
<Button
href={`/master-data/supplier/detail/?supplierId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon
icon='mdi:eye-outline'
width={16}
height={16}
className='justify-start text-sm'
/>
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.suppliers.update'>
<Button
href={`/master-data/supplier/detail/edit/?supplierId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon
icon='material-symbols:edit-outline'
width={16}
height={16}
className='justify-start text-sm'
/>
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.suppliers.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.suppliers.detail'>
<Button
href={`/master-data/supplier/detail/?supplierId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.suppliers.update'>
<Button
href={`/master-data/supplier/detail/edit/?supplierId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.suppliers.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const SuppliersTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -93,15 +127,132 @@ const SuppliersTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '' },
initial: {
search: '',
categoryFilter: '',
flagFilter: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
categoryFilter: 'category_id',
flagFilter: 'flag',
},
});
// Fetch Data
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FORMIK SETUP =====
const formik = useFormik<SupplierFilterType>({
initialValues: {
category_id: null,
flag: false,
},
validationSchema: SupplierFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('categoryFilter', values.category_id || '');
updateFilter(
'flagFilter',
values.flag === true ? 'EKSPEDISI' : values.flag === false ? '' : ''
);
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('categoryFilter', '');
updateFilter('flagFilter', '');
formik.setFieldValue('flag', false);
},
});
const { setFieldValue } = formik;
// ===== CATEGORY OPTIONS (SAPRONAK or BOP) =====
const categoryOptions = useMemo(
() => [
{ value: 'SAPRONAK', label: 'SAPRONAK' },
{ value: 'BOP', label: 'BOP' },
],
[]
);
// ===== FLAG OPTIONS (EKSPEDISI) =====
const flagOptions = useMemo(
() => [
{ value: 'true', label: 'Ya' },
{ value: 'false', label: 'Tidak' },
],
[]
);
// ===== FILTER HANDLERS =====
const handleFilterCategoryChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const option = val as OptionType | null;
const categoryId = option?.value ? String(option.value) : null;
setFieldValue('category_id', categoryId);
},
[setFieldValue]
);
const handleFilterFlagChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const option = val as OptionType | null;
const boolValue =
option?.value === 'true'
? true
: option?.value === 'false'
? false
: null;
setFieldValue('flag', boolValue);
},
[setFieldValue]
);
// ===== FILTER HELPERS =====
const categoryIdValue = useMemo(() => {
if (!formik.values.category_id) return null;
return (
categoryOptions.find((opt) => opt.value === formik.values.category_id) ||
null
);
}, [formik.values.category_id, categoryOptions]);
const flagValue = useMemo(() => {
if (formik.values.flag === null) return null;
return (
flagOptions.find((opt) => opt.value === String(formik.values.flag)) ||
flagOptions[1]
);
}, [formik.values.flag, flagOptions]);
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
filterModal.openModal();
formik.validateForm();
};
useEffect(() => {
if (filterModal.open) {
const flagBoolValue =
tableFilterState.flagFilter === 'EKSPEDISI' ? true : false;
setFieldValue('flag', flagBoolValue);
}
}, [filterModal.open, tableFilterState.flagFilter, setFieldValue]);
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
useEffect(() => {
setTableState('suppliers-table', pathname);
}, [pathname, setTableState]);
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: suppliers,
isLoading,
@@ -111,97 +262,17 @@ const SuppliersTable = () => {
SupplierApi.getAllFetcher
);
// State
const deleteModal = useModal();
const [selectedSupplier, setSelectedSupplier] = useState<
Supplier | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
// Columns Definition
const suppliersColumns: ColumnDef<Supplier>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'alias',
header: 'Alias',
},
{
accessorKey: 'pic',
header: 'Nama PIC',
},
{
accessorKey: 'category',
header: 'Kategori',
},
{
accessorKey: 'type',
header: 'Tipe',
},
{
accessorKey: 'phone',
header: 'No. Telp',
},
{
accessorKey: 'email',
header: 'Email',
},
{
accessorKey: 'address',
header: 'Alamat',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedSupplier(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptions
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptions
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
// Handler
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -221,82 +292,168 @@ const SuppliersTable = () => {
toast.success('Successfully delete Supplier!');
setIsDeleteLoading(false);
};
const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
updateFilter('search', e.target.value);
};
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
};
const suppliersColumns: ColumnDef<Supplier>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'alias',
header: 'Alias',
},
{
accessorKey: 'pic',
header: 'Nama PIC',
},
{
accessorKey: 'category',
header: 'Kategori',
},
{
accessorKey: 'type',
header: 'Tipe',
},
{
accessorKey: 'phone',
header: 'No. Telp',
},
{
accessorKey: 'email',
header: 'Email',
},
{
accessorKey: 'address',
header: 'Alamat',
},
{
header: 'Aksi',
cell: (props: CellContext<Supplier, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedSupplier(props.row.original);
deleteModal.openModal();
};
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.suppliers.create'>
<Button
href='/master-data/supplier/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Supplier'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.suppliers.create'>
<Button
href='/master-data/supplier/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Supplier
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
<Table<Supplier>
data={isResponseSuccess(suppliers) ? suppliers?.data : []}
columns={suppliersColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(suppliers) ? suppliers?.meta?.page : 0}
totalItems={
isResponseSuccess(suppliers) ? suppliers?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(suppliers) && suppliers?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(suppliers) || suppliers.data?.length === 0 ? (
<div className='p-3'>
<SupplierTableSkeleton
columns={suppliersColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Supplier>
data={suppliers?.data}
columns={suppliersColumns}
pageSize={tableFilterState.pageSize}
page={suppliers?.meta?.page ?? 0}
totalItems={suppliers?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
ref={deleteModal.ref}
type='error'
@@ -311,6 +468,75 @@ const SuppliersTable = () => {
onClick: confirmationModalDeleteClickHandler,
}}
/>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInputRadio
label='Kategori'
placeholder='Pilih Kategori'
options={categoryOptions}
value={categoryIdValue}
onChange={handleFilterCategoryChange}
isClearable
className={{ wrapper: 'w-full' }}
/>
<SelectInputRadio
label='Flag Ekspedisi'
placeholder='Pilih'
options={flagOptions}
value={flagValue}
onChange={handleFilterFlagChange}
isClearable
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
formik.resetForm();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
</>
);
};
@@ -0,0 +1,11 @@
import { string, boolean, object } from 'yup';
export const SupplierFilterSchema = object().shape({
category_id: string().nullable(),
flag: boolean().nullable(),
});
export type SupplierFilterType = {
category_id: string | null;
flag: boolean | null;
};
@@ -167,29 +167,26 @@ const SupplierForm = ({
},
});
const { setValues: formikSetValues } = formik;
const { setFieldValue } = formik;
// Initialize Formik
useEffect(() => {
formikSetValues(formikInitialValues);
if (formType != 'add') {
const hatcheryArrays = formikInitialValues.hatchery?.split(',');
const hatcheryCreatedOptions = hatcheryArrays?.map((item) => ({
if (formType !== 'add' && initialValues?.hatchery) {
const hatcheryArrays = initialValues.hatchery.split(',');
const hatcheryCreatedOptions = hatcheryArrays.map((item) => ({
value: item,
label: item,
}));
setHatcheryOptionValues(hatcheryCreatedOptions ?? []);
setHatcheryOptionValues(hatcheryCreatedOptions);
}
}, [formikSetValues, formikInitialValues, setHatcheryOptionValues]);
}, [formType, initialValues?.hatchery]);
useEffect(() => {
const commaSeparatedValues = hatcheryOptionsValues
.map((item) => item.value)
.join(',');
formikSetValues({
...formik.values,
hatchery: commaSeparatedValues,
});
}, [hatcheryOptionsValues, formikSetValues]);
setFieldValue('hatchery', commaSeparatedValues);
}, [hatcheryOptionsValues, setFieldValue]);
// Option Handler
const typeChangeHandler = (val: OptionType | OptionType[] | null) => {
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Supplier } from '@/types/api/master-data/supplier';
import { ColumnDef } from '@tanstack/react-table';
const SupplierTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no supplier data displayed. Enter supplier data to get started.',
}: {
columns: ColumnDef<Supplier>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default SupplierTableSkeleton;
+208 -182
View File
@@ -1,6 +1,6 @@
'use client';
import { ChangeEventHandler, useEffect, useState } from 'react';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
@@ -11,75 +11,101 @@ import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import UomTableSkeleton from '@/components/pages/master-data/uom/skeleton/UomTableSkeleton';
import { Uom } from '@/types/api/master-data/uom';
import { UomApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Uom, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `uom#${props.row.original.id}`;
const popoverAnchorName = `--anchor-uom#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.uoms.detail'>
<Button
href={`/master-data/uom/detail/?uomId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.uoms.update'>
<Button
href={`/master-data/uom/detail/edit/?uomId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.uoms.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.uoms.detail'>
<Button
href={`/master-data/uom/detail/?uomId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.uoms.update'>
<Button
href={`/master-data/uom/detail/edit/?uomId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.uoms.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const UomsTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -87,10 +113,25 @@ const UomsTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '' },
paramMap: { page: 'page', pageSize: 'limit', nameSort: 'sort_name' },
initial: {
search: searchValue,
},
paramMap: {
page: 'page',
pageSize: 'limit',
},
});
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
useEffect(() => {
setTableState('uoms-table', pathname);
}, [pathname, setTableState]);
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: uoms,
isLoading,
@@ -101,65 +142,13 @@ const UomsTable = () => {
);
const deleteModal = useModal();
const [selectedUom, setSelectedUom] = useState<Uom | undefined>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
const uomsColumns: ColumnDef<Uom>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedUom(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -179,93 +168,130 @@ const UomsTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const uomsColumns: ColumnDef<Uom>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
header: 'Aksi',
cell: (props: CellContext<Uom, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
setPageSize(newVal.value as number);
};
const deleteClickHandler = () => {
setSelectedUom(props.row.original);
deleteModal.openModal();
};
// track sorting
useEffect(() => {
const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
if (!isNameSorted) {
updateFilter('nameSort', '');
} else {
updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
}
}, [sorting, updateFilter]);
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.uoms.create'>
<Button
href='/master-data/uom/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari UOM'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.uoms.create'>
<Button
href='/master-data/uom/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add UOM
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
</div>
</div>
<Table<Uom>
data={isResponseSuccess(uoms) ? uoms?.data : []}
columns={uomsColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(uoms) ? uoms?.meta?.page : 0}
totalItems={isResponseSuccess(uoms) ? uoms?.meta?.total_results : 0}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20': isResponseSuccess(uoms) && uoms?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(uoms) || uoms.data?.length === 0 ? (
<div className='p-3'>
<UomTableSkeleton
columns={uomsColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Uom>
data={uoms?.data}
columns={uomsColumns}
pageSize={tableFilterState.pageSize}
page={uoms?.meta?.page ?? 0}
totalItems={uoms?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Uom } from '@/types/api/master-data/uom';
import { ColumnDef } from '@tanstack/react-table';
const UomTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no uom data displayed. Enter uom data to get started.',
}: {
columns: ColumnDef<Uom>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default UomTableSkeleton;
@@ -1,90 +1,128 @@
'use client';
import { ChangeEventHandler, useCallback, useEffect, useState } from 'react';
import useSWR from 'swr';
import {
CellContext,
ColumnDef,
ColumnSort,
SortingState,
} from '@tanstack/react-table';
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { usePathname } from 'next/navigation';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
import { useFormik } from 'formik';
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import WarehouseTableSkeleton from '@/components/pages/master-data/warehouse/skeleton/WarehouseTableSkeleton';
import { OptionType } from '@/components/input/SelectInput';
import ButtonFilter from '@/components/helper/ButtonFilter';
import { Warehouse } from '@/types/api/master-data/warehouse';
import { WarehouseApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { WarehouseApi, AreaApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { useUiStore } from '@/stores/ui/ui.store';
import {
WarehouseFilterSchema,
WarehouseFilterType,
} from '@/components/pages/master-data/warehouse/filter/WarehouseFilter';
import { Area } from '@/types/api/master-data/area';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import SelectInputRadio from '@/components/input/SelectInputRadio';
const RowOptionsMenu = ({
type = 'dropdown',
popoverPosition = 'bottom',
props,
deleteClickHandler,
}: {
type: 'dropdown' | 'collapse';
popoverPosition: 'bottom' | 'top';
props: CellContext<Warehouse, unknown>;
deleteClickHandler: () => void;
}) => {
const popoverId = `warehouse#${props.row.original.id}`;
const popoverAnchorName = `--anchor-warehouse#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<RowOptionsMenuWrapper type={type}>
<RequirePermission permissions='lti.master.warehouses.detail'>
<Button
href={`/master-data/warehouse/detail/?warehouseId=${props.row.original.id}`}
variant='ghost'
color='primary'
className='justify-start text-sm'
>
<Icon icon='mdi:eye-outline' width={16} height={16} />
Detail
</Button>
</RequirePermission>
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<RequirePermission permissions='lti.master.warehouses.update'>
<Button
href={`/master-data/warehouse/detail/edit/?warehouseId=${props.row.original.id}`}
variant='ghost'
color='warning'
className='justify-start text-sm'
>
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.warehouses.delete'>
<Button
onClick={deleteClickHandler}
variant='ghost'
color='error'
className='text-error hover:text-inherit'
>
<Icon
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete
</Button>
</RequirePermission>
</RowOptionsMenuWrapper>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.warehouses.detail'>
<Button
href={`/master-data/warehouse/detail/?warehouseId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:eye' width={20} height={20} />
Detail
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.warehouses.update'>
<Button
href={`/master-data/warehouse/detail/edit/?warehouseId=${props.row.original.id}`}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
>
<Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit
</Button>
</RequirePermission>
<RequirePermission permissions='lti.master.warehouses.delete'>
<Button
onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost'
color='none'
className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
>
<Icon icon='heroicons:trash' width={20} height={20} />
Delete
</Button>
</RequirePermission>
</div>
</PopoverContent>
</div>
);
};
const WarehousesTable = () => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const {
state: tableFilterState,
updateFilter,
@@ -94,23 +132,139 @@ const WarehousesTable = () => {
} = useTableFilter({
initial: {
search: '',
nameSort: '',
typeSort: '',
areaSort: '',
locationSort: '',
kandangSort: '',
areaFilter: '',
activeProjectFlockFilter: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
nameSort: 'sort_name',
typeSort: 'sort_type',
areaSort: ' sort_area',
locationSort: ' sort_location',
kandangSort: ' sort_kandang',
areaFilter: 'area_id',
activeProjectFlockFilter: 'active_project_flock',
},
});
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FORMIK SETUP =====
const formik = useFormik<WarehouseFilterType>({
initialValues: {
area_id: null,
active_project_flock: false,
},
validationSchema: WarehouseFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('areaFilter', values.area_id || '');
updateFilter(
'activeProjectFlockFilter',
values.active_project_flock === true ? 'true' : ''
);
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('areaFilter', '');
updateFilter('activeProjectFlockFilter', '');
formik.setFieldValue('active_project_flock', false);
},
});
const { setFieldValue } = formik;
// ===== AREA OPTIONS =====
const {
setInputValue: setAreaInputValue,
options: areaOptions,
isLoadingOptions: isLoadingAreaOptions,
loadMore: loadMoreAreas,
} = useSelect<Area>(
filterModal.open ? AreaApi.basePath : null,
'id',
'name',
'search'
);
// ===== ACTIVE PROJECT FLOCK OPTIONS =====
const activeProjectFlockOptions = useMemo(
() => [
{ value: 'true', label: 'Kandang Aktif' },
{ value: 'false', label: 'Semua Kandang' },
],
[]
);
// ===== FILTER HANDLERS =====
const handleFilterAreaChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const area = val as OptionType | null;
const areaId = area?.value ? String(area.value) : null;
formik.setFieldValue('area_id', areaId);
},
[formik]
);
const handleFilterActiveProjectFlockChange = useCallback(
(val: OptionType | OptionType[] | null) => {
const option = val as OptionType | null;
const boolValue =
option?.value === 'true'
? true
: option?.value === 'false'
? false
: null;
formik.setFieldValue('active_project_flock', boolValue);
},
[formik]
);
// ===== FILTER HELPERS =====
const areaIdValue = useMemo(() => {
if (!formik.values.area_id) return null;
return (
areaOptions.find((opt) => String(opt.value) === formik.values.area_id) ||
null
);
}, [formik.values.area_id, areaOptions]);
const activeProjectFlockValue = useMemo(() => {
if (formik.values.active_project_flock === null) return null;
return (
activeProjectFlockOptions.find(
(opt) => opt.value === String(formik.values.active_project_flock)
) || activeProjectFlockOptions[1]
);
}, [formik.values.active_project_flock, activeProjectFlockOptions]);
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
filterModal.openModal();
formik.validateForm();
};
useEffect(() => {
if (filterModal.open) {
const activeProjectFlockValue =
tableFilterState.activeProjectFlockFilter === 'true' ? true : false; // Default ke false (Semua Kandang)
setFieldValue('active_project_flock', activeProjectFlockValue);
}
}, [
filterModal.open,
tableFilterState.activeProjectFlockFilter,
setFieldValue,
]);
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
useEffect(() => {
setTableState('warehouses-table', pathname);
}, [pathname, setTableState]);
const [sorting, setSorting] = useState<SortingState>([]);
const {
data: warehouses,
isLoading,
@@ -121,101 +275,15 @@ const WarehousesTable = () => {
);
const deleteModal = useModal();
const [selectedWarehouse, setSelectedWarehouse] = useState<
Warehouse | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
const warehousesColumns: ColumnDef<Warehouse>[] = [
{
header: '#',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'type',
header: 'Tipe',
},
{
accessorKey: 'area',
header: 'Area',
cell: (props) => props.row.original.area.name,
},
{
accessorKey: 'location',
header: 'Lokasi',
cell: (props) => {
if (
props.row.original.type === 'LOKASI' ||
props.row.original.type === 'KANDANG'
) {
return props.row.original.location.name;
} else {
return '-';
}
},
},
{
accessorKey: 'kandang',
header: 'Kandang',
cell: (props) => {
if (props.row.original.type === 'KANDANG') {
return props.row.original.kandang.name;
} else {
return '-';
}
},
},
{
header: 'Aksi',
cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedWarehouse(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu
type='dropdown'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
);
},
},
];
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
@@ -237,118 +305,169 @@ const WarehousesTable = () => {
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const warehousesColumns: ColumnDef<Warehouse>[] = useMemo(
() => [
{
header: 'No',
cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
},
{
accessorKey: 'name',
header: 'Nama',
},
{
accessorKey: 'type',
header: 'Tipe',
},
{
accessorFn: (row) => row.area?.name ?? '-',
header: 'Area',
},
{
accessorKey: 'location',
header: 'Lokasi',
cell: (props) => {
if (
props.row.original.type === 'LOKASI' ||
props.row.original.type === 'KANDANG'
) {
return props.row.original.location?.name ?? '-';
}
return '-';
},
},
{
accessorKey: 'kandang',
header: 'Kandang',
cell: (props) => {
if (props.row.original.type === 'KANDANG') {
return props.row.original.kandang?.name ?? '-';
}
return '-';
},
},
{
header: 'Aksi',
cell: (props: CellContext<Warehouse, unknown>) => {
const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
setPageSize(newVal.value as number);
};
const deleteClickHandler = () => {
setSelectedWarehouse(props.row.original);
deleteModal.openModal();
};
const updateSortingFilter = useCallback(
(
sortName: Exclude<keyof typeof tableFilterState, 'page' | 'pageSize'>,
sortFilter: ColumnSort | undefined
) => {
if (!sortFilter) {
updateFilter(sortName, '');
} else {
updateFilter(sortName, sortFilter.desc ? 'desc' : 'asc');
}
},
[updateFilter]
return (
<RowOptionsMenu
props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler}
/>
);
},
},
],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
);
// track sorting
useEffect(() => {
const nameSortFilter = sorting.find((sortItem) => sortItem.id === 'name');
const typeSortFilter = sorting.find((sortItem) => sortItem.id === 'type');
const areaSortFilter = sorting.find((sortItem) => sortItem.id === 'area');
const locationSortFilter = sorting.find(
(sortItem) => sortItem.id === 'location'
);
const kandangSortFilter = sorting.find(
(sortItem) => sortItem.id === 'kandang'
);
updateSortingFilter('nameSort', nameSortFilter);
updateSortingFilter('typeSort', typeSortFilter);
updateSortingFilter('areaSort', areaSortFilter);
updateSortingFilter('locationSort', locationSortFilter);
updateSortingFilter('kandangSort', kandangSortFilter);
}, [sorting, updateSortingFilter]);
return (
<>
<div className='w-full p-0 sm:p-4'>
<div className='flex flex-col gap-2 mb-4'>
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
<div className='w-full flex flex-row'>
<RequirePermission permissions='lti.master.warehouses.create'>
<Button
href='/master-data/warehouse/add'
variant='outline'
color='primary'
className='w-full sm:w-fit'
>
<Icon icon='ic:round-plus' width={24} height={24} />
Tambah
</Button>
</RequirePermission>
</div>
<DebouncedTextInput
name='search'
placeholder='Cari Warehouse'
value={tableFilterState.search}
onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }}
/>
<div className='w-full'>
{/* Header Section */}
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
{/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.warehouses.create'>
<Button
href='/master-data/warehouse/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Warehouse
</Button>
</RequirePermission>
</div>
<div className='flex flex-row justify-end'>
<SelectInput
label='Baris'
options={ROWS_OPTIONS}
value={{
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
{/* Search and Filter */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput
name='search'
placeholder='Search'
value={tableFilterState.search ?? ''}
onChange={searchChangeHandler}
startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/>
}
className={{
wrapper: 'w-full min-w-24 max-w-3xs',
inputWrapper: 'rounded-xl! shadow-button-soft',
input:
'placeholder:font-semibold placeholder:text-base-content/50',
}}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/>
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
</div>
</div>
<Table<Warehouse>
data={isResponseSuccess(warehouses) ? warehouses?.data : []}
columns={warehousesColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(warehouses) ? warehouses?.meta?.page : 0}
totalItems={
isResponseSuccess(warehouses) ? warehouses?.meta?.total_results : 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(warehouses) && warehouses?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
/>
{/* Table Section */}
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(warehouses) ||
warehouses.data?.length === 0 ? (
<div className='p-3'>
<WarehouseTableSkeleton
columns={warehousesColumns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<Warehouse>
data={warehouses?.data}
columns={warehousesColumns}
pageSize={tableFilterState.pageSize}
page={warehouses?.meta?.page ?? 0}
totalItems={warehouses?.meta?.total_results ?? 0}
onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={false}
sorting={sorting}
setSorting={setSorting}
className={{
containerClassName: 'p-3 mb-0',
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
<ConfirmationModal
@@ -365,6 +484,77 @@ const WarehousesTable = () => {
onClick: confirmationModalDeleteClickHandler,
}}
/>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInput
label='Area'
placeholder='Pilih Area'
options={areaOptions}
value={areaIdValue}
onChange={handleFilterAreaChange}
onInputChange={setAreaInputValue}
isLoading={isLoadingAreaOptions}
isClearable
onMenuScrollToBottom={loadMoreAreas}
className={{ wrapper: 'w-full' }}
/>
<SelectInputRadio
label='Filter Berdasarkan'
placeholder='Pilih'
options={activeProjectFlockOptions}
value={activeProjectFlockValue}
onChange={handleFilterActiveProjectFlockChange}
className={{ wrapper: 'w-full' }}
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='button'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={() => {
formik.resetForm();
filterModal.closeModal();
}}
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
</>
);
};
@@ -0,0 +1,11 @@
import { string, boolean, object } from 'yup';
export const WarehouseFilterSchema = object().shape({
area_id: string().nullable(),
active_project_flock: boolean().nullable(),
});
export type WarehouseFilterType = {
area_id: string | null;
active_project_flock: boolean | null;
};
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { Warehouse } from '@/types/api/master-data/warehouse';
import { ColumnDef } from '@tanstack/react-table';
const WarehouseTableSkeleton = ({
columns,
icon,
title = 'No Data Available',
subtitle = 'There is no warehouse data displayed. Enter warehouse data to get started.',
}: {
columns: ColumnDef<Warehouse>[];
icon: React.ReactNode;
title?: string;
subtitle?: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default WarehouseTableSkeleton;
@@ -23,7 +23,7 @@ const ChickinLogsView = ({
rawDataApprovals: BaseApproval[];
}) => {
const [chickinErrorMessage, setChickinErrorMessage] = useState('');
const { openChickinApproveModal } = useChickinStore();
const { openChickinApproveModal, openChickinDeleteModal } = useChickinStore();
const handleClickApprove = () => {
openChickinApproveModal(initialValues, async (notes?: string) => {
@@ -44,6 +44,21 @@ const ChickinLogsView = ({
});
};
const handleDeleteChickin = (chickinId: number) => {
openChickinDeleteModal(chickinId, async () => {
const deleteRes = await ChickinApi.delete(chickinId);
if (isResponseSuccess(deleteRes)) {
toast.success(deleteRes?.message || 'Chickin berhasil dihapus');
afterSubmit && afterSubmit();
}
if (isResponseError(deleteRes)) {
toast.error(deleteRes?.message || 'Gagal menghapus chickin');
}
});
};
return (
<>
<div className='px-4 pb-4 flex flex-col gap-4'>
@@ -86,14 +101,30 @@ const ChickinLogsView = ({
<div className='text-lg font-semibold'>
Chick In #{index + 1} - {latestApproval?.step_number}
</div>
<PillBadge
content={
isApproved ? 'Disetujui' : isPending ? 'Pending' : '-'
}
color={
isApproved ? 'green' : isPending ? 'yellow' : 'gray'
}
/>
<div className='flex flex-row gap-2 items-center'>
<PillBadge
content={
isApproved ? 'Disetujui' : isPending ? 'Pending' : '-'
}
color={
isApproved ? 'green' : isPending ? 'yellow' : 'gray'
}
/>
{isApproved && (
<Button
color='error'
className='w-fit text-sm text-base-100 rounded-lg shadow-sm btn-xs!'
onClick={() => handleDeleteChickin(chickin.id)}
>
<Icon
icon='heroicons:trash-solid'
width={10}
height={10}
/>
</Button>
)}
</div>
</div>
{/* Tanggal Chick In */}
@@ -3,7 +3,10 @@
import Button from '@/components/Button';
import CheckboxInput from '@/components/input/CheckboxInput';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import { OptionType, useSelect } from '@/components/input/SelectInput';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
@@ -18,20 +21,30 @@ import { Kandang } from '@/types/api/master-data/kandang';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { Icon } from '@iconify/react';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import { useRouter } from 'next/navigation';
import { useRouter, usePathname } from 'next/navigation';
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import { useUiStore } from '@/stores/ui/ui.store';
import toast from 'react-hot-toast';
import useSWR from 'swr';
import { useFormik } from 'formik';
import RequirePermission from '@/components/helper/RequirePermission';
import StatusBadge from '@/components/helper/StatusBadge';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import ProjectFlockConfirmationModal from './ProjectFlockConfirmationModal';
import ProjectFlockTableSkeleton from '@/components/pages/production/project-flock/skeleton/ProjectFlockTableSkeleton';
import { useProjectFlockStore } from '@/stores/production/project-flock/project-flock.store';
import { ProjectFlockFormValues } from './form/ProjectFlockForm.schema';
import { useChickinStore } from '@/stores/production/chickin/chickin.store';
import { useProjectFlockClosingStore } from '@/stores/production/project-flock-closing/project-flock-closing.store';
import {
ProjectFlockFilterSchema,
ProjectFlockFilterType,
} from './filter/ProjectFlockFilter';
import Modal from '@/components/Modal';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import ButtonFilter from '@/components/helper/ButtonFilter';
const RowOptionsMenu = ({
props,
@@ -136,6 +149,9 @@ const RowOptionsMenu = ({
};
const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
const { searchValue, setSearchValue, setTableState } = useUiStore();
const pathname = usePathname();
const isSuccess = useProjectFlockStore((s) => s.isSuccess);
const setIsSuccess = useProjectFlockStore((s) => s.setIsSuccess);
const createdProjectFlock = useProjectFlockStore(
@@ -154,19 +170,21 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
} = useTableFilter({
initial: {
search: '',
areaFilter: '',
locationFilter: '',
kandangFilter: '',
periodFilter: '',
area_id: '',
location_id: '',
kandang_id: '',
category: '',
period: '',
},
paramMap: {
page: 'page',
pageSize: 'limit',
search: 'search',
areaFilter: 'area_id',
locationFilter: 'location_id',
kandangFilter: 'kandang_id',
periodFilter: 'period',
area_id: 'area_id',
location_id: 'location_id',
kandang_id: 'kandang_id',
category: 'category',
period: 'period',
},
});
const router = useRouter();
@@ -182,6 +200,7 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
const confirmModal = useModal();
const successModal = useModal();
const chickinApproveModal = useModal();
const chickinDeleteModal = useModal();
const closingModal = useModal();
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
'APPROVED'
@@ -196,6 +215,11 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
chickinApproveCallback,
closeChickinApproveModal,
setChickinApproveLoading,
isChickinDeleteModalOpen,
isChickinDeleteLoading,
chickinDeleteCallback,
closeChickinDeleteModal,
setChickinDeleteLoading,
} = useChickinStore();
const {
@@ -207,6 +231,171 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
setClosingLoading,
} = useProjectFlockClosingStore();
// ===== FILTER MODAL STATE =====
const filterModal = useModal();
// ===== FILTER DEPENDENCIES STATE =====
const [filterAreaId, setFilterAreaId] = useState<string | undefined>(
undefined
);
const [filterLocationId, setFilterLocationId] = useState<string | undefined>(
undefined
);
// ===== FORMIK SETUP FOR FILTER =====
const formik = useFormik<ProjectFlockFilterType>({
initialValues: {
area_id: null,
location_id: null,
kandang_id: null,
category: null,
period: null,
},
validationSchema: ProjectFlockFilterSchema,
onSubmit: (values, { setSubmitting }) => {
updateFilter('area_id', values.area_id || '');
updateFilter('location_id', values.location_id || '');
updateFilter('kandang_id', values.kandang_id || '');
updateFilter('category', values.category || '');
updateFilter('period', values.period || '');
filterModal.closeModal();
setSubmitting(false);
},
onReset: () => {
updateFilter('area_id', '');
updateFilter('location_id', '');
updateFilter('kandang_id', '');
updateFilter('category', '');
updateFilter('period', '');
setFilterAreaId(undefined);
setFilterLocationId(undefined);
filterModal.closeModal();
},
});
// ===== FILTER OPTIONS =====
const {
setInputValue: setAreaInputValue,
options: areaOptions,
isLoadingOptions: isLoadingAreaOptions,
loadMore: loadMoreAreas,
} = useSelect(AreaApi.basePath, 'id', 'name');
const {
setInputValue: setLocationInputValue,
options: locationOptions,
isLoadingOptions: isLoadingLocationOptions,
loadMore: loadMoreLocations,
} = useSelect(LocationApi.basePath, 'id', 'name', 'search', {
area_id: filterAreaId || '',
});
const {
setInputValue: setKandangInputValue,
options: kandangOptions,
isLoadingOptions: isLoadingKandangOptions,
loadMore: loadMoreKandangs,
} = useSelect(KandangApi.basePath, 'id', 'name', 'search', {
area_id: filterAreaId || '',
location_id: filterLocationId || '',
});
const categoryOptions = useMemo(
() => [
{ value: 'GROWING', label: 'Growing' },
{ value: 'LAYING', label: 'Laying' },
],
[]
);
const periodOptions = useMemo(
() => [
{ value: '1', label: 'Periode 1' },
{ value: '2', label: 'Periode 2' },
],
[]
);
// ===== FILTER HELPERS =====
const areaValue = useMemo(() => {
if (!formik.values.area_id) return null;
return (
areaOptions.find((opt) => String(opt.value) === formik.values.area_id) ||
null
);
}, [formik.values.area_id, areaOptions]);
const locationValue = useMemo(() => {
if (!formik.values.location_id) return null;
return (
locationOptions.find(
(opt) => String(opt.value) === formik.values.location_id
) || null
);
}, [formik.values.location_id, locationOptions]);
const kandangValue = useMemo(() => {
if (!formik.values.kandang_id) return null;
return (
kandangOptions.find(
(opt) => String(opt.value) === formik.values.kandang_id
) || null
);
}, [formik.values.kandang_id, kandangOptions]);
const categoryValue = useMemo(() => {
if (!formik.values.category) return null;
return (
categoryOptions.find((opt) => opt.value === formik.values.category) ||
null
);
}, [formik.values.category, categoryOptions]);
const periodValue = useMemo(() => {
if (!formik.values.period) return null;
return (
periodOptions.find((opt) => opt.value === formik.values.period) || null
);
}, [formik.values.period, periodOptions]);
// ===== FILTER DEPENDENCY HANDLERS =====
const handleFilterAreaChange = (area: OptionType | null) => {
const areaId = area?.value ? String(area.value) : undefined;
setFilterAreaId(areaId);
if (!areaId) {
setFilterLocationId(undefined);
formik.setFieldValue('location_id', null);
formik.setFieldValue('kandang_id', null);
}
};
const handleFilterLocationChange = (location: OptionType | null) => {
const locationId = location?.value ? String(location.value) : undefined;
setFilterLocationId(locationId);
if (!locationId) {
formik.setFieldValue('kandang_id', null);
}
};
// ===== HANDLE FILTER MODAL OPEN =====
const handleFilterModalOpen = () => {
const areaId = tableFilterState.area_id || null;
const locationId = tableFilterState.location_id || null;
formik.setValues({
area_id: areaId,
location_id: locationId,
kandang_id: tableFilterState.kandang_id || null,
category: tableFilterState.category || null,
period: tableFilterState.period || null,
});
setFilterAreaId(areaId || undefined);
setFilterLocationId(locationId || undefined);
filterModal.openModal();
};
// ===== Fetch Data =====
const {
data: projectFlocks,
@@ -237,7 +426,16 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
setIsDeleteLoading(false);
setRowSelection({});
};
useEffect(() => {
updateFilter('search', searchValue);
}, [searchValue, updateFilter]);
useEffect(() => {
setTableState('project-flock-table', pathname);
}, [pathname, setTableState]);
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
const confirmApprovalHandler = async (
@@ -286,6 +484,14 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
}
}, [isChickinApproveModalOpen, chickinApproveModal]);
useEffect(() => {
if (isChickinDeleteModalOpen) {
chickinDeleteModal.openModal();
} else {
chickinDeleteModal.closeModal();
}
}, [isChickinDeleteModalOpen, chickinDeleteModal]);
useEffect(() => {
if (isClosingModalOpen) {
closingModal.openModal();
@@ -765,30 +971,12 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
}}
/>
<Button
variant='outline'
color='none'
// onClick={filterModal.openModal}
className={cn(
'px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft transition-all',
{
// 'border-primary-gradient text-primary': isFilterActive,
}
)}
>
<Icon icon='heroicons:funnel' width={20} height={20} />
Filter
{/* {isFilterActive && (
<Badge
className={{
badge:
'p-1.5 bg-[#FF3535] text-xs text-base-100 border border-base-300 rounded-lg',
}}
>
{filterCount}
</Badge>
)} */}
</Button>
<ButtonFilter
values={tableFilterState}
excludeFields={['page', 'pageSize', 'search']}
onClick={handleFilterModalOpen}
className='px-3 py-2.5'
/>
<Dropdown
align='end'
@@ -837,46 +1025,69 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
</div>
</div>
<Table<ProjectFlock>
data={isResponseSuccess(projectFlocks) ? projectFlocks?.data : []}
columns={columns}
pageSize={tableFilterState.pageSize}
page={
isResponseSuccess(projectFlocks) ? projectFlocks?.meta?.page : 0
}
totalItems={
isResponseSuccess(projectFlocks)
? projectFlocks?.meta?.total_results
: 0
}
onPageChange={(page) => {
setPage(page);
}}
onPageSizeChange={(pageSize) => {
setPageSize(pageSize);
}}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
rowSelection={rowSelection}
setRowSelection={setRowSelection}
enableRowSelection={(row) => {
const projectFlock = row.original;
return (
projectFlock.approval?.step_number === 1 &&
projectFlock.approval?.action !== 'REJECTED'
);
}}
withCheckbox
className={{
containerClassName: cn('p-3', {
'w-full mb-20':
isResponseSuccess(projectFlocks) &&
projectFlocks?.data?.length === 0,
}),
headerColumnClassName: 'text-nowrap',
}}
/>
<div className='flex flex-col mb-4'>
{isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : !isResponseSuccess(projectFlocks) ||
projectFlocks.data?.length === 0 ? (
<div className='p-3'>
<ProjectFlockTableSkeleton
columns={columns}
icon={
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
}
/>
</div>
) : (
<Table<ProjectFlock>
data={
isResponseSuccess(projectFlocks) ? projectFlocks?.data : []
}
columns={columns}
pageSize={tableFilterState.pageSize}
page={
isResponseSuccess(projectFlocks)
? projectFlocks?.meta?.page
: 0
}
totalItems={
isResponseSuccess(projectFlocks)
? projectFlocks?.meta?.total_results
: 0
}
onPageChange={(page) => {
setPage(page);
}}
onPageSizeChange={(pageSize) => {
setPageSize(pageSize);
}}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
rowSelection={rowSelection}
setRowSelection={setRowSelection}
enableRowSelection={(row) => {
const projectFlock = row.original;
return (
projectFlock.approval?.step_number === 1 &&
projectFlock.approval?.action !== 'REJECTED'
);
}}
withCheckbox
className={{
containerClassName: cn('p-3 mb-0'),
headerColumnClassName: 'text-nowrap',
}}
/>
)}
</div>
</div>
</div>
@@ -1011,6 +1222,169 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
}}
/>
{/* Chickin Delete Modal */}
<ConfirmationModal
ref={chickinDeleteModal.ref}
type='error'
text='Apakah anda yakin ingin menghapus data chick in ini?'
secondaryButton={{
text: 'Tidak',
onClick: () => {
closeChickinDeleteModal();
},
}}
className={{
modal: 'z-9999',
}}
primaryButton={{
text: 'Ya',
color: 'error',
isLoading: isChickinDeleteLoading,
onClick: async () => {
if (chickinDeleteCallback) {
setChickinDeleteLoading(true);
try {
await chickinDeleteCallback();
} finally {
setChickinDeleteLoading(false);
closeChickinDeleteModal();
}
}
},
}}
/>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
<div className='p-4 flex flex-col gap-1.5'>
<SelectInput
label='Area'
placeholder='Pilih Area'
options={areaOptions}
value={areaValue}
onChange={(val) => {
if (!Array.isArray(val)) {
const areaValue = val?.value ? String(val.value) : null;
formik.setFieldValue('area_id', areaValue);
handleFilterAreaChange(val || null);
}
}}
onInputChange={setAreaInputValue}
isLoading={isLoadingAreaOptions}
isClearable
onMenuScrollToBottom={loadMoreAreas}
className={{ wrapper: 'w-full' }}
/>
<SelectInput
label='Lokasi'
placeholder='Pilih Lokasi'
options={locationOptions}
value={locationValue}
onChange={(val) => {
if (!Array.isArray(val)) {
const locationValue = val?.value ? String(val.value) : null;
formik.setFieldValue('location_id', locationValue);
handleFilterLocationChange(val || null);
}
}}
onInputChange={setLocationInputValue}
isLoading={isLoadingLocationOptions}
isClearable
onMenuScrollToBottom={loadMoreLocations}
className={{ wrapper: 'w-full' }}
/>
<SelectInput
label='Kandang'
placeholder='Pilih Kandang'
options={kandangOptions}
value={kandangValue}
onChange={(val) => {
if (!Array.isArray(val)) {
formik.setFieldValue(
'kandang_id',
val?.value ? String(val.value) : null
);
}
}}
onInputChange={setKandangInputValue}
isLoading={isLoadingKandangOptions}
isClearable
onMenuScrollToBottom={loadMoreKandangs}
className={{ wrapper: 'w-full' }}
/>
<SelectInputRadio
label='Kategori'
placeholder='Pilih Kategori'
options={categoryOptions}
value={categoryValue}
onChange={(val) => {
if (!Array.isArray(val)) {
formik.setFieldValue('category', val?.value || null);
}
}}
className={{ wrapper: 'w-full' }}
isClearable={true}
/>
<SelectInputRadio
label='Periode'
placeholder='Pilih Periode'
options={periodOptions}
value={periodValue}
onChange={(val) => {
if (!Array.isArray(val)) {
formik.setFieldValue('period', val?.value || null);
}
}}
className={{ wrapper: 'w-full' }}
isClearable
/>
</div>
{/* Modal Footer */}
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
type='reset'
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
>
Reset Filter
</Button>
<Button
type='submit'
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
disabled={!formik.isValid || formik.isSubmitting}
>
Apply Filter
</Button>
</div>
</form>
</Modal>
{/* Project Flock Closing Modal */}
<ConfirmationModal
ref={closingModal.ref}
@@ -1,6 +1,7 @@
import Button from '@/components/Button';
import Card from '@/components/Card';
import { RadioGroup, RadioGroupItem } from '@/components/input/RadioInput';
import { useSelect } from '@/components/input/SelectInput';
import Tooltip from '@/components/Tooltip';
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
import { cn, formatCurrency, formatDate, formatNumber } from '@/lib/helper';
@@ -37,10 +38,37 @@ const ProjectFlockDetail = ({
null
);
const { rawData: projectFlockRawData } = useSelect<ProjectFlock>(
ProjectFlockApi.basePath,
'id',
'flock_name',
'search',
selectedKandangId ? { kandang_id: `[${selectedKandangId}]` } : undefined
);
const selectedKandang = projectFlock.kandangs?.find(
(kandang) => kandang.id === Number(selectedKandangId)
);
// Cek apakah ada project aktif di kandang yang sama (selain project saat ini)
// Hanya boleh 1 kandang aktif, jadi jika ada project lain yang aktif, tidak bisa di-unclose baik kategori growing maupun laying
const hasActiveProjectWithSameKandang = isResponseSuccess(projectFlockRawData)
? projectFlockRawData.data.some((pf) =>
pf.kandangs?.some(
(k) =>
k.id === Number(selectedKandangId) &&
pf.id !== projectFlock.id &&
k.status !== 'NON_ACTIVE'
)
)
: false;
const isCloseButtonDisabled =
!selectedKandangId ||
projectFlock?.approval?.step_number == 1 ||
(selectedKandang?.status === 'NON_ACTIVE' &&
hasActiveProjectWithSameKandang);
const { data: projectFlockApprovalResponse } = useSWR(
projectFlock.id ? ['approval-project-flock', projectFlock.id] : undefined,
([, id]) => ProjectFlockApi.getApprovalLineHistory(Number(id))
@@ -419,10 +447,7 @@ const ProjectFlockDetail = ({
className='w-full px-2 py-1 text-sm'
variant='outline'
color='error'
disabled={
!selectedKandangId ||
projectFlock?.approval?.step_number == 1
}
disabled={isCloseButtonDisabled}
>
{selectedKandang?.status === 'NON_ACTIVE' ? (
<>
@@ -0,0 +1,21 @@
import * as yup from 'yup';
export type ProjectFlockFilterType = {
area_id: string | null;
location_id: string | null;
kandang_id: string | null;
category: string | null;
period: string | null;
};
export const ProjectFlockFilterSchema = yup.object({
area_id: yup.string().nullable(),
location_id: yup.string().nullable(),
kandang_id: yup.string().nullable(),
category: yup.string().nullable(),
period: yup.string().nullable(),
});
export type ProjectFlockFilterValues = yup.InferType<
typeof ProjectFlockFilterSchema
>;

Some files were not shown because too many files have changed in this diff Show More