Refactor: integration shift

This commit is contained in:
2025-10-24 10:27:56 +07:00
parent a3d24a9426
commit cf1ad6d511
2 changed files with 391 additions and 192 deletions

View File

@@ -1,11 +1,22 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Modal, Input, Typography, Switch, Button, ConfigProvider, Divider, TimePicker, Space } from 'antd'; import {
Modal,
Input,
Typography,
Switch,
Button,
ConfigProvider,
Divider,
TimePicker,
Space,
} from 'antd';
import { NotifOk } from '../../../../components/Global/ToastNotif'; import { NotifOk } from '../../../../components/Global/ToastNotif';
import { createShift, updateShift } from '../../../../api/master-shift';
import { validateRun } from '../../../../Utils/validate';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
// Mock API calls for demonstration dayjs.extend(utc);
const createShift = async (payload) => ({ statusCode: 201, data: { ...payload, shift_id: Date.now() } });
const updateShift = async (id, payload) => ({ statusCode: 200, data: { ...payload, shift_id: id } });
const { Text } = Typography; const { Text } = Typography;
const timeFormat = 'HH:mm'; const timeFormat = 'HH:mm';
@@ -16,13 +27,21 @@ const DetailShift = (props) => {
const defaultData = { const defaultData = {
shift_id: '', shift_id: '',
shift_name: '', shift_name: '',
start_time: '08:00', start_time: '',
end_time: '16:00', end_time: '',
is_active: true, is_active: true,
}; };
const [formData, setFormData] = useState(defaultData); const [formData, setFormData] = useState(defaultData);
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
const handleCancel = () => { const handleCancel = () => {
props.setSelectedData(null); props.setSelectedData(null);
props.setActionMode('list'); props.setActionMode('list');
@@ -31,123 +50,262 @@ const DetailShift = (props) => {
const handleSave = async () => { const handleSave = async () => {
setConfirmLoading(true); setConfirmLoading(true);
if (!formData.shift_name) { // Daftar aturan validasi
NotifOk({ icon: 'warning', title: 'Peringatan', message: 'Nama Shift wajib diisi.' }); const validationRules = [
{ field: 'shift_name', label: 'Shift Name', required: true },
{ field: 'start_time', label: 'Start Time', required: true },
{ field: 'end_time', label: 'End Time', required: true },
];
if (
validateRun(formData, validationRules, (errorMessages) => {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: errorMessages,
});
setConfirmLoading(false);
})
)
return;
// Validasi format waktu
if (!formData.start_time || !formData.end_time) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Waktu Mulai dan Waktu Selesai wajib diisi.',
});
setConfirmLoading(false); setConfirmLoading(false);
return; return;
} }
try { try {
// Pastikan format waktu HH:mm sesuai validasi BE (regex: /^([01]\d|2[0-3]):([0-5]\d)(:[0-5]\d)?$/)
const formatTimeForAPI = (timeValue) => {
if (!timeValue) return '';
// Jika sudah dalam format HH:mm, return langsung
if (typeof timeValue === 'string' && timeValue.match(/^\d{2}:\d{2}$/)) {
return timeValue;
}
// Parse dengan dayjs dan format ke HH:mm (string murni, bukan Date object)
const time = dayjs(timeValue, 'HH:mm', true); // strict mode
if (time.isValid()) {
return time.format('HH:mm'); // Return string "08:00" bukan Date object
}
// Fallback: coba parse sebagai ISO date dan ambil jam/menitnya (gunakan UTC)
const isoTime = dayjs.utc(timeValue);
if (isoTime.isValid()) {
return isoTime.format('HH:mm');
}
return '';
};
const payload = { const payload = {
shift_name: formData.shift_name, shift_name: formData.shift_name,
start_time: formData.start_time, start_time: formatTimeForAPI(formData.start_time),
end_time: formData.end_time, end_time: formatTimeForAPI(formData.end_time),
is_active: formData.is_active, is_active: formData.is_active,
}; };
console.log('Payload yang dikirim:', payload);
console.log('Type start_time:', typeof payload.start_time, payload.start_time);
console.log('Type end_time:', typeof payload.end_time, payload.end_time);
const response = const response =
props.actionMode === 'edit' props.actionMode === 'edit'
? await updateShift(formData.shift_id, payload) ? await updateShift(formData.shift_id, payload)
: await createShift(payload); : await createShift(payload);
if (response && (response.statusCode === 200 || response.statusCode === 201)) { if (response && (response.statusCode === 200 || response.statusCode === 201)) {
NotifOk({ icon: 'success', title: 'Berhasil', message: `Data Shift berhasil disimpan.` }); const action = props.actionMode === 'edit' ? 'diubah' : 'ditambahkan';
NotifOk({
icon: 'success',
title: 'Berhasil',
message: `Data Shift berhasil ${action}.`,
});
props.setActionMode('list'); props.setActionMode('list');
} else { } else {
NotifOk({ icon: 'error', title: 'Gagal', message: response?.message || 'Gagal menyimpan data.' }); NotifOk({
icon: 'error',
title: 'Gagal',
message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
});
} }
} catch (error) { } catch (error) {
NotifOk({ icon: 'error', title: 'Error', message: error.message || 'Terjadi kesalahan server.' }); NotifOk({
icon: 'error',
title: 'Error',
message: error.message || 'Terjadi kesalahan pada server.',
});
} finally { } finally {
setConfirmLoading(false); setConfirmLoading(false);
} }
}; };
const handleInputChange = (e) => { const handleTimeChange = (time, _, field) => {
const { name, value } = e.target; // Pastikan format HH:mm yang konsisten sesuai validasi BE
setFormData({ ...formData, [name]: value }); const formattedTime = time && time.isValid() ? time.format('HH:mm') : '';
setFormData({
...formData,
[field]: formattedTime,
});
}; };
const handleTimeChange = (time, timeString, field) => { const handleStatusToggle = (checked) => {
setFormData({ ...formData, [field]: timeString }); setFormData({
...formData,
is_active: checked,
});
}; };
useEffect(() => { useEffect(() => {
if (props.selectedData) { if (props.selectedData) {
setFormData(props.selectedData); // Konversi waktu dari berbagai format ke HH:mm menggunakan dayjs
const convertTimeToString = (timeValue) => {
if (!timeValue) return '';
// Jika sudah dalam format HH:mm, return langsung
if (typeof timeValue === 'string' && timeValue.match(/^\d{2}:\d{2}$/)) {
return timeValue;
}
// Jika dalam format ISO (1970-01-01T08:00:00.000Z), extract jam:menit dalam UTC
const time = dayjs.utc(timeValue);
if (time.isValid()) {
return time.format('HH:mm');
}
return '';
};
setFormData({
...props.selectedData,
start_time: convertTimeToString(props.selectedData.start_time),
end_time: convertTimeToString(props.selectedData.end_time),
});
} else { } else {
setFormData(defaultData); setFormData(defaultData);
} }
}, [props.showModal, props.selectedData]); }, [props.showModal, props.selectedData, props.actionMode]);
const modalTitle = `${props.actionMode === 'add' ? 'Tambah' : props.actionMode === 'preview' ? 'Preview' : 'Edit'} Shift`;
return ( return (
<Modal <Modal
title={modalTitle} title={`${
props.actionMode === 'add'
? 'Tambah'
: props.actionMode === 'preview'
? 'Preview'
: 'Edit'
} Shift`}
open={props.showModal} open={props.showModal}
onCancel={handleCancel} onCancel={handleCancel}
footer={[ footer={[
<ConfigProvider key="footer-buttons" theme={{ components: { Button: { defaultColor: '#23A55A', defaultBorderColor: '#23A55A' } } }}> <React.Fragment key="modal-footer">
<Button key="back" onClick={handleCancel}>{props.readOnly ? 'Tutup' : 'Batal'}</Button> <ConfigProvider
{!props.readOnly && ( theme={{
<Button key="submit" type="primary" loading={confirmLoading} onClick={handleSave} style={{ backgroundColor: '#23a55a' }}> components: {
Simpan Button: {
</Button> defaultBg: 'white',
)} defaultColor: '#23A55A',
</ConfigProvider>, defaultBorderColor: '#23A55A',
},
},
}}
>
<Button onClick={handleCancel}>{props.readOnly ? 'Tutup' : 'Batal'}</Button>
</ConfigProvider>
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
},
},
}}
>
{!props.readOnly && (
<Button loading={confirmLoading} onClick={handleSave}>
Simpan
</Button>
)}
</ConfigProvider>
</React.Fragment>,
]} ]}
> >
<div> {formData && (
<div> <div>
<Text strong>Status</Text> <div>
<div style={{ display: 'flex', alignItems: 'center', marginTop: '8px' }}> <div>
<Switch <Text strong>Status</Text>
disabled={props.readOnly} </div>
style={{ backgroundColor: formData.is_active ? '#23A55A' : '#bfbfbf' }} <div style={{ display: 'flex', alignItems: 'center', marginTop: '8px' }}>
checked={formData.is_active} <div style={{ marginRight: '8px' }}>
onChange={(checked) => setFormData({ ...formData, is_active: checked })} <Switch
disabled={props.readOnly}
style={{
backgroundColor: formData.is_active ? '#23A55A' : '#bfbfbf',
}}
checked={formData.is_active}
onChange={handleStatusToggle}
/>
</div>
<div>
<Text>{formData.is_active ? 'Active' : 'Inactive'}</Text>
</div>
</div>
</div>
<Divider style={{ margin: '12px 0' }} />
<div style={{ marginBottom: 12 }}>
<Text strong>Shift Name</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="shift_name"
value={formData.shift_name}
onChange={handleInputChange}
placeholder="Contoh: Pagi, Sore, Malam"
readOnly={props.readOnly}
/> />
<Text style={{ marginLeft: '8px' }}>{formData.is_active ? 'Active' : 'Inactive'}</Text> </div>
<div style={{ marginBottom: 12 }}>
<Text strong>Shift Time</Text>
<Text style={{ color: 'red' }}> *</Text>
<Space.Compact block style={{ marginTop: '4px' }}>
<TimePicker
format={timeFormat}
onChange={(time, timeString) =>
handleTimeChange(time, timeString, 'start_time')
}
style={{ width: '50%' }}
placeholder="Start Time "
disabled={props.readOnly}
/>
<TimePicker
value={
formData.end_time ? dayjs(formData.end_time, timeFormat) : null
}
format={timeFormat}
onChange={(time, timeString) =>
handleTimeChange(time, timeString, 'end_time')
}
style={{ width: '50%' }}
placeholder="End Time "
disabled={props.readOnly}
/>
</Space.Compact>
</div> </div>
</div> </div>
<Divider style={{ margin: '12px 0' }} /> )}
<div style={{ marginBottom: 12 }}>
<Text strong>Nama Shift</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="shift_name"
value={formData.shift_name}
onChange={handleInputChange}
placeholder="Contoh: Pagi, Sore, Malam"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Waktu Shift</Text>
<Text style={{ color: 'red' }}> *</Text>
<Space.Compact block style={{ marginTop: '4px' }}>
<TimePicker
value={dayjs(formData.start_time, timeFormat)}
format={timeFormat}
onChange={(time, timeString) => handleTimeChange(time, timeString, 'start_time')}
style={{ width: '50%' }}
placeholder="Waktu Mulai"
disabled={props.readOnly}
/>
<TimePicker
value={dayjs(formData.end_time, timeFormat)}
format={timeFormat}
onChange={(time, timeString) => handleTimeChange(time, time-string, 'end_time')}
style={{ width: '50%' }}
placeholder="Waktu Selesai"
disabled={props.readOnly}
/>
</Space.Compact>
</div>
</div>
</Modal> </Modal>
); );
}; };

View File

@@ -9,19 +9,23 @@ import {
} from '@ant-design/icons'; } from '@ant-design/icons';
import { NotifAlert, NotifConfirmDialog } from '../../../../components/Global/ToastNotif'; import { NotifAlert, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { deleteShift, getAllShift } from '../../../../api/master-shift';
import TableList from '../../../../components/Global/TableList'; import TableList from '../../../../components/Global/TableList';
// import { getAllShift, deleteShift } from '../../../../api/master-shift'; // <-- API needs to be created import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
// Mock API calls for demonstration dayjs.extend(utc);
const getAllShift = async () => ({
data: [ // Helper function untuk convert ISO time ke HH:mm
{ shift_id: 1, shift_name: 'Pagi', start_time: '08:00', end_time: '16:00', is_active: true }, const formatTime = (timeValue) => {
{ shift_id: 2, shift_name: 'Sore', start_time: '16:00', end_time: '00:00', is_active: true }, if (!timeValue) return '-';
{ shift_id: 3, shift_name: 'Malam', start_time: '00:00', end_time: '08:00', is_active: false }, if (typeof timeValue === 'string' && timeValue.match(/^\d{2}:\d{2}$/)) {
], return timeValue;
statusCode: 200, }
}); // UTC untuk menghindari timezone conversion
const deleteShift = async (id) => ({ statusCode: 200, message: 'Data berhasil dihapus' }); const time = dayjs.utc(timeValue);
return time.isValid() ? time.format('HH:mm') : '-';
};
const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
{ {
@@ -29,7 +33,6 @@ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
dataIndex: 'shift_name', dataIndex: 'shift_name',
key: 'shift_name', key: 'shift_name',
width: '30%', width: '30%',
render: (text, record, index) => `${index + 1}. ${text}`,
}, },
{ {
title: 'Start Time', title: 'Start Time',
@@ -37,6 +40,7 @@ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
key: 'start_time', key: 'start_time',
width: '15%', width: '15%',
align: 'center', align: 'center',
render: (time) => formatTime(time),
}, },
{ {
title: 'End Time', title: 'End Time',
@@ -44,6 +48,7 @@ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
key: 'end_time', key: 'end_time',
width: '15%', width: '15%',
align: 'center', align: 'center',
render: (time) => formatTime(time),
}, },
{ {
title: 'Status', title: 'Status',
@@ -51,15 +56,9 @@ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
key: 'is_active', key: 'is_active',
width: '15%', width: '15%',
align: 'center', align: 'center',
render: (_, { is_active }) => { render: (status) => (
const color = is_active ? 'green' : 'red'; <Tag color={status ? 'green' : 'red'}>{status ? 'Active' : 'Inactive'}</Tag>
const text = is_active ? 'Active' : 'Inactive'; ),
return (
<Tag color={color} key={'status'}>
{text}
</Tag>
);
},
}, },
{ {
title: 'Aksi', title: 'Aksi',
@@ -68,9 +67,25 @@ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
width: '25%', width: '25%',
render: (_, record) => ( render: (_, record) => (
<Space> <Space>
<Button ghost icon={<EyeOutlined />} onClick={() => showPreviewModal(record)} style={{ color: '#1890ff', borderColor: '#1890ff' }} /> <Button
<Button ghost icon={<EditOutlined />} onClick={() => showEditModal(record)} style={{ color: '#faad14', borderColor: '#faad14' }} /> type="text"
<Button danger ghost icon={<DeleteOutlined />} onClick={() => showDeleteDialog(record)} /> style={{ borderColor: '#1890ff' }}
icon={<EyeOutlined style={{ color: '#1890ff' }} />}
onClick={() => showPreviewModal(record)}
/>
<Button
type="text"
style={{ borderColor: '#faad14' }}
icon={<EditOutlined style={{ color: '#faad14' }} />}
onClick={() => showEditModal(record)}
/>
<Button
type="text"
danger
style={{ borderColor: 'red' }}
icon={<DeleteOutlined />}
onClick={() => showDeleteDialog(record)}
/>
</Space> </Space>
), ),
}, },
@@ -78,25 +93,36 @@ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
const ListShift = memo(function ListShift(props) { const ListShift = memo(function ListShift(props) {
const [trigerFilter, setTrigerFilter] = useState(false); const [trigerFilter, setTrigerFilter] = useState(false);
const [formDataFilter, setFormDataFilter] = useState({ criteria: '' }); const defaultFilter = { criteria: '' };
const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
const [searchValue, setSearchValue] = useState(''); const [searchValue, setSearchValue] = useState('');
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
if (props.actionMode === 'list') { const token = localStorage.getItem('token');
doFilter(); if (token) {
if (props.actionMode === 'list') {
setFormDataFilter(defaultFilter);
doFilter();
}
} else {
navigate('/signin');
} }
}, [props.actionMode]); }, [props.actionMode]);
const doFilter = () => setTrigerFilter((prev) => !prev); const doFilter = () => {
const handleSearch = () => { setTrigerFilter((prev) => !prev);
setFormDataFilter((prev) => ({ ...prev, criteria: searchValue }));
doFilter();
}; };
const handleSearch = () => {
setFormDataFilter({ criteria: searchValue });
setTrigerFilter((prev) => !prev);
};
const handleSearchClear = () => { const handleSearchClear = () => {
setSearchValue(''); setSearchValue('');
setFormDataFilter((prev) => ({ ...prev, criteria: '' })); setFormDataFilter({ criteria: '' });
doFilter(); setTrigerFilter((prev) => !prev);
}; };
const showPreviewModal = (param) => { const showPreviewModal = (param) => {
@@ -116,95 +142,110 @@ const ListShift = memo(function ListShift(props) {
const showDeleteDialog = (param) => { const showDeleteDialog = (param) => {
NotifConfirmDialog({ NotifConfirmDialog({
icon: 'question',
title: 'Konfirmasi Hapus', title: 'Konfirmasi Hapus',
message: `Apakah Anda yakin ingin menghapus shift "${param.shift_name}"?`, message: 'Shift "' + param.shift_name + '" akan dihapus?',
onConfirm: () => handleDelete(param), onConfirm: () => handleDelete(param.shift_id),
onCancel: () => props.setSelectedData(null),
}); });
}; };
const handleDelete = async (param) => { const handleDelete = async (shift_id) => {
try { const response = await deleteShift(shift_id);
const response = await deleteShift(param.shift_id); if (response.statusCode === 200) {
if (response.statusCode === 200) { NotifAlert({
NotifAlert({ icon: 'success', title: 'Berhasil', message: 'Data shift berhasil dihapus.' }); icon: 'success',
doFilter(); title: 'Berhasil',
} else { message: 'Data Shift berhasil dihapus.',
NotifAlert({ icon: 'error', title: 'Gagal', message: response.message || 'Gagal menghapus data.' }); });
} doFilter();
} catch (error) { } else {
NotifAlert({ icon: 'error', title: 'Error', message: error.message || 'Terjadi kesalahan server.' }); NotifAlert({
icon: 'error',
title: 'Gagal',
message: response?.message || 'Gagal Menghapus Data Shift',
});
} }
}; };
return ( return (
<Card> <React.Fragment>
<Row justify="space-between" align="middle" gutter={[8, 8]}> <Card>
<Col xs={24}> <Row>
<Row justify="space-between" align="middle" gutter={[8, 8]}> <Col xs={24}>
<Col xs={24} sm={24} md={12} lg={12}> <Row justify="space-between" align="middle" gutter={[8, 8]}>
<Input.Search <Col xs={24} sm={24} md={12} lg={12}>
placeholder="Cari berdasarkan nama shift..." <Input.Search
value={searchValue} placeholder="Cari berdasarkan nama shift..."
onChange={(e) => { value={searchValue}
const value = e.target.value; onChange={(e) => {
setSearchValue(value); const value = e.target.value;
// Auto search when clearing by backspace/delete setSearchValue(value);
if (value === '') { if (value === '') {
handleSearchClear(); handleSearchClear();
} }
}}
onSearch={handleSearch}
allowClear
onClear={handleSearchClear}
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
style={{ backgroundColor: '#23A55A', borderColor: '#23A55A' }}
>
Search
</Button>
}
size="large"
/>
</Col>
<Col>
<Space wrap size="small">
<ConfigProvider
theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
defaultHoverBorderColor: '#23A55A',
},
},
}} }}
> onSearch={handleSearch}
<Button icon={<PlusOutlined />} onClick={() => showAddModal()} size="large"> allowClear={{
Tambah Data clearIcon: <span onClick={handleSearchClear}></span>,
</Button> }}
</ConfigProvider> enterButton={
</Space> <Button
</Col> type="primary"
</Row> icon={<SearchOutlined />}
</Col> style={{
<Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}> backgroundColor: '#23A55A',
<TableList borderColor: '#23A55A',
mobile }}
cardColor={'#42AAFF'} >
header={'shift_name'} // Menggunakan shift_name langsung untuk judul kartu Search
getData={getAllShift} </Button>
queryParams={formDataFilter} }
columns={columns(showPreviewModal, showEditModal, showDeleteDialog)} size="large"
triger={trigerFilter} />
/> </Col>
</Col> <Col>
</Row> <Space wrap size="small">
</Card> <ConfigProvider
theme={{
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
},
},
}}
>
<Button
icon={<PlusOutlined />}
onClick={() => showAddModal()}
size="large"
>
Tambah Data
</Button>
</ConfigProvider>
</Space>
</Col>
</Row>
</Col>
<Col xs={24} style={{ marginTop: '16px' }}>
<TableList
mobile
cardColor={'#42AAFF'}
header={'shift_name'}
showPreviewModal={showPreviewModal}
showEditModal={showEditModal}
showDeleteDialog={showDeleteDialog}
getData={getAllShift}
queryParams={formDataFilter}
columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
triger={trigerFilter}
/>
</Col>
</Row>
</Card>
</React.Fragment>
); );
}); });