Enhance DetailJadwalShift and ListJadwalShift components with improved employee fetching, form handling, and UI updates

This commit is contained in:
2025-10-24 10:52:03 +07:00
parent cf1ad6d511
commit b5c1888153
2 changed files with 579 additions and 347 deletions

View File

@@ -1,172 +1,173 @@
import React, { useEffect, useState } from 'react';
import {
Modal,
Input,
Typography,
Button,
ConfigProvider,
Row,
Col
Form,
Select,
Spin,
Input
} from 'antd';
import { NotifOk } from '../../../components/Global/ToastNotif';
import { NotifOk, NotifAlert } from '../../../components/Global/ToastNotif';
import { updateJadwalShift, createJadwalShift } from '../../../api/jadwal-shift.jsx';
const { Text } = Typography;
const { Option } = Select;
const DetailJadwalShift = (props) => {
const [form] = Form.useForm();
const [confirmLoading, setConfirmLoading] = useState(false);
const [employees, setEmployees] = useState([]);
const [loadingEmployees, setLoadingEmployees] = useState(false);
const defaultData = {
id: '',
nama_shift: '',
jam_masuk: '',
jam_pulang: '',
username: '',
nama_employee: '',
whatsapp: ''
};
const [FormData, setFormData] = useState(defaultData);
const isReadOnly = props.actionMode === 'preview';
const handleCancel = () => {
props.setSelectedData(null);
props.setActionMode('list');
};
const fetchEmployees = async () => {
setLoadingEmployees(true);
try {
// Data dummy untuk dropdown karyawan
const dummyEmployees = [
{ employee_id: '101', nama_employee: 'Andi Pratama' },
{ employee_id: '102', nama_employee: 'Budi Santoso' },
{ employee_id: '103', nama_employee: 'Citra Lestari' },
{ employee_id: '104', nama_employee: 'Dewi Anggraini' },
{ employee_id: '105', nama_employee: 'Eko Wahyudi' },
{ employee_id: '106', nama_employee: 'Fitriani' },
];
setEmployees(dummyEmployees);
} catch (error) {
NotifAlert({ icon: 'error', title: 'Gagal', message: 'Gagal memuat daftar karyawan.' });
} finally {
setLoadingEmployees(false);
}
};
const handleSave = async () => {
setConfirmLoading(true);
// This is a dummy save function for slicing purposes
setTimeout(() => {
try {
const values = await form.validateFields();
let payload;
let responseMessage;
setConfirmLoading(true);
if (props.actionMode === 'edit') {
payload = { ...props.selectedData, ...values };
// await updateJadwalShift(payload.schedule_id, payload);
console.log("Updating schedule with payload:", payload);
responseMessage = 'Jadwal berhasil diperbarui.';
} else { // 'add' mode
payload = {
employee_id: values.employee_id,
shift_name: props.selectedData.shift_name,
schedule_date: new Date().toISOString().split('T')[0], // Example date
};
// await createJadwalShift(payload);
console.log("Creating schedule with payload:", payload);
responseMessage = 'User berhasil ditambahkan ke jadwal.';
}
await new Promise(resolve => setTimeout(resolve, 500)); // Simulasi API call
NotifOk({ icon: 'success', title: 'Berhasil', message: responseMessage });
props.setActionMode('list'); // Menutup modal dan memicu refresh di parent
} catch (error) {
const message = error.response?.data?.message || 'Gagal memperbarui jadwal.';
NotifAlert({ icon: 'error', title: 'Gagal', message });
} finally {
setConfirmLoading(false);
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Data dummy berhasil disimpan.',
});
props.setActionMode('list');
}, 1000);
}
};
useEffect(() => {
if (props.selectedData) {
setFormData(props.selectedData);
} else {
setFormData(defaultData);
// Hanya jalankan jika modal untuk 'edit' atau 'preview' terbuka
if (props.showModal) {
fetchEmployees();
if (props.actionMode === 'edit' || props.actionMode === 'preview') {
form.setFieldsValue({
employee_id: props.selectedData.employee_id,
shift_name: props.selectedData.shift_name,
});
} else if (props.actionMode === 'add') {
form.setFieldsValue({
shift_name: props.selectedData.shift_name,
employee_id: null, // Reset employee selection
});
}
}
}, [props.showModal, props.selectedData]);
// Dummy handler for slicing
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({ ...FormData, [name]: value });
};
}, [props.actionMode, props.showModal, props.selectedData, form]);
return (
<Modal
title={`${
props.actionMode === 'add'
? 'Tambah'
: props.actionMode === 'preview'
? 'Preview'
: 'Edit'
} Jadwal Shift`}
title={isReadOnly ? 'Preview Jadwal' : (props.actionMode === 'edit' ? 'Edit Jadwal' : 'Tambah User')}
open={props.showModal}
onCancel={handleCancel}
width={800}
width={600}
footer={[
<React.Fragment key="modal-footer">
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
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>
<Button key="back" onClick={handleCancel}>
{isReadOnly ? 'Tutup' : 'Batal'}
</Button>
{!isReadOnly && (
<Button key="submit" type="primary" loading={confirmLoading} onClick={handleSave} style={{ backgroundColor: '#23A55A' }}>
Simpan
</Button>
)}
</React.Fragment>,
]}
>
{FormData && (
<div>
<Row gutter={[16, 16]}>
<Col span={12}>
<Text strong>Nama Karyawan</Text>
<Input
name="nama_employee"
value={FormData.nama_employee}
onChange={handleInputChange}
readOnly={props.readOnly}
/>
</Col>
<Col span={12}>
<Text strong>Username</Text>
<Input
name="username"
value={FormData.username}
onChange={handleInputChange}
readOnly={props.readOnly}
/>
</Col>
<Col span={12}>
<Text strong>Nama Shift</Text>
<Input
name="nama_shift"
value={FormData.nama_shift}
onChange={handleInputChange}
readOnly={props.readOnly}
/>
</Col>
<Col span={12}>
<Text strong>Whatsapp</Text>
<Input
name="whatsapp"
value={FormData.whatsapp}
onChange={handleInputChange}
readOnly={props.readOnly}
/>
</Col>
<Col span={12}>
<Text strong>Jam Masuk</Text>
<Input
name="jam_masuk"
value={FormData.jam_masuk}
onChange={handleInputChange}
readOnly={props.readOnly}
/>
</Col>
<Col span={12}>
<Text strong>Jam Pulang</Text>
<Input
name="jam_pulang"
value={FormData.jam_pulang}
onChange={handleInputChange}
readOnly={props.readOnly}
/>
</Col>
</Row>
</div>
)}
<Spin spinning={loadingEmployees} tip="Memuat data...">
<Form form={form} layout="vertical" name="shift_form">
{props.actionMode === 'add' ? (
<>
<Form.Item
name="shift_name"
label="Shift"
>
<Input disabled />
</Form.Item>
<Form.Item
name="employee_id"
label="Nama Karyawan"
rules={[{ required: true, message: 'Nama karyawan wajib dipilih!' }]}
>
<Select
placeholder="Pilih karyawan"
showSearch
optionFilterProp="children"
>
{employees.map(emp => (
<Option key={emp.employee_id} value={emp.employee_id}>{emp.nama_employee}</Option>
))}
</Select>
</Form.Item>
</>
) : (
<>
<Form.Item
name="employee_id"
label="Nama Karyawan"
rules={[{ required: true, message: 'Nama karyawan wajib dipilih!' }]}
>
<Select placeholder="Pilih karyawan" disabled={isReadOnly} showSearch optionFilterProp="children">
{employees.map(emp => (
<Option key={emp.employee_id} value={emp.employee_id}>{emp.nama_employee}</Option>
))}
</Select>
</Form.Item>
<Form.Item name="shift_name" label="Shift" rules={[{ required: true, message: 'Shift wajib dipilih!' }]}>
<Select placeholder="Pilih shift" disabled={isReadOnly}>
<Option value="PAGI">PAGI</Option>
<Option value="SIANG">SIANG</Option>
<Option value="MALAM">MALAM</Option>
</Select>
</Form.Item>
</>
)}
</Form>
</Spin>
</Modal>
);
};

View File

@@ -1,153 +1,146 @@
import React, { memo, useState, useEffect } from 'react';
import { Space, Tag, ConfigProvider, Button, Row, Col, Card, Input } from 'antd';
import { Space, ConfigProvider, Button, Row, Col, Card, Input, Typography, Spin, Divider, Checkbox, Select } from 'antd';
import {
PlusOutlined,
SearchOutlined,
EyeOutlined,
EditOutlined,
DeleteOutlined,
EyeOutlined,
SearchOutlined,
} from '@ant-design/icons';
import { NotifAlert, NotifConfirmDialog } from '../../../components/Global/ToastNotif';
import { NotifAlert, NotifOk, NotifConfirmDialog } from '../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom';
import TableList from '../../../components/Global/TableList';
import { getAllJadwalShift, deleteJadwalShift } from '../../../api/jadwal-shift';
import { getAllJadwalShift, deleteJadwalShift, updateJadwalShift } from '../../../api/jadwal-shift.jsx';
const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
{
title: 'Tanggal Jadwal',
dataIndex: 'schedule_date',
key: 'schedule_date',
render: (date) => date ? new Date(date).toLocaleDateString('id-ID') : '-',
},
{
title: 'Nama Shift',
dataIndex: 'shift_name',
key: 'shift_name',
render: (text) => text || '-',
},
{
title: 'Jam Masuk',
dataIndex: 'start_time',
key: 'start_time',
render: (time) => time || '-',
},
{
title: 'Jam Pulang',
dataIndex: 'end_time',
key: 'end_time',
render: (time) => time || '-',
},
{
title: 'Status',
dataIndex: 'is_active',
key: 'is_active',
render: (isActive) => (
<Tag color={isActive ? 'green' : 'red'}>
{isActive ? 'Aktif' : 'Tidak Aktif'}
</Tag>
),
},
{
title: 'Aksi',
key: 'aksi',
align: 'center',
render: (_, record) => (
<Space>
<Button
type="text"
icon={<EyeOutlined style={{ color: '#1890ff' }} />}
onClick={() => showPreviewModal(record)}
/>
<Button
type="text"
icon={<EditOutlined style={{ color: '#faad14' }} />}
onClick={() => showEditModal(record)}
/>
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={() => showDeleteDialog(record)}
/>
</Space>
),
},
];
const { Title, Text } = Typography;
const ListJadwalShift = memo(function ListJadwalShift(props) {
const [trigerFilter, setTrigerFilter] = useState(false);
const defaultFilter = { criteria: '' };
const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
const [groupedSchedules, setGroupedSchedules] = useState({});
const [loading, setLoading] = useState(true);
const [searchValue, setSearchValue] = useState('');
const [isEditMode, setIsEditMode] = useState(false);
const [selectedSchedules, setSelectedSchedules] = useState([]);
const [editingShift, setEditingShift] = useState(null); // State for shift-specific edit mode
const [pendingChanges, setPendingChanges] = useState({}); // State for bulk shift edits
const [employeeOptions, setEmployeeOptions] = useState([]); // State for employee dropdown
const navigate = useNavigate();
const getData = async (queryParams) => {
try {
const params = new URLSearchParams({
page: queryParams.page || 1,
limit: queryParams.limit || 10,
criteria: queryParams.criteria || ''
});
// Function to format timestamp without moment.js
const formatTimestamp = (timestamp) => {
const date = new Date(timestamp);
const optionsDate = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const optionsTime = { hour: '2-digit', minute: '2-digit', hour12: false };
const response = await getAllJadwalShift(params);
return response;
} catch (error) {
console.error('Error fetching jadwal shift:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Gagal mengambil data jadwal shift.',
});
return {
status: 500,
data: {
data: [],
paging: {
page: 1,
limit: 10,
total: 0,
page_total: 0
}
const formattedDate = date.toLocaleDateString('id-ID', optionsDate);
const formattedTime = date.toLocaleTimeString('id-ID', optionsTime);
return `${formattedDate} pukul ${formattedTime}`;
};
const formatRelativeTimestamp = (timestamp) => {
const now = new Date();
const date = new Date(timestamp);
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const startOfYesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
let dayString;
if (date >= startOfToday) {
dayString = 'Hari ini';
} else if (date >= startOfYesterday) {
dayString = 'Kemarin';
} else {
dayString = date.toLocaleDateString('id-ID', { day: 'numeric', month: 'long' });
}
const timeString = date.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', hour12: false }).replace('.', ':');
return `${dayString}, ${timeString}`;
};
const fetchData = async () => {
setLoading(true);
try {
// const params = new URLSearchParams({ ... });
// const response = await getAllJadwalShift(params);
// ================== START: DUMMY DATA FOR VISUAL PREVIEW ==================
// This section creates dummy schedules and users to ensure all shifts are populated.
// The actual API call is commented out for now.
const mockSchedules = [
{ schedule_id: 1, employee_id: '101', shift_name: 'PAGI', nama_employee: 'Andi Pratama', whatsapp: '081234567890', updated_by: 'Admin Super', updated_at: '2024-05-21T10:00:00' },
{ schedule_id: 2, employee_id: '102', shift_name: 'PAGI', nama_employee: 'Budi Santoso', whatsapp: '081234567891', updated_by: 'Admin Super', updated_at: '2024-05-21T10:00:00' },
{ schedule_id: 3, employee_id: '103', shift_name: 'SIANG', nama_employee: 'Citra Lestari', whatsapp: '081234567892', updated_by: 'John Doe', updated_at: '2024-05-21T09:45:00' },
{ schedule_id: 4, employee_id: '104', shift_name: 'SIANG', nama_employee: 'Dewi Anggraini', whatsapp: '081234567893', updated_by: 'John Doe', updated_at: '2024-05-21T09:45:00' },
{ schedule_id: 5, employee_id: '105', shift_name: 'MALAM', nama_employee: 'Eko Wahyudi', whatsapp: '081234567894', updated_by: 'Jane Smith', updated_at: '2024-05-20T22:15:00' },
{ schedule_id: 6, employee_id: '106', shift_name: 'MALAM', nama_employee: 'Fitriani', whatsapp: '081234567895', updated_by: 'Jane Smith', updated_at: '2024-05-20T22:15:00' },
];
// Dummy employee data for dropdowns
const dummyEmployees = [
{ employee_id: '101', nama_employee: 'Andi Pratama' },
{ employee_id: '102', nama_employee: 'Budi Santoso' },
{ employee_id: '103', nama_employee: 'Citra Lestari' },
{ employee_id: '104', nama_employee: 'Dewi Anggraini' },
{ employee_id: '105', nama_employee: 'Eko Wahyudi' },
{ employee_id: '106', nama_employee: 'Fitriani' },
];
setEmployeeOptions(dummyEmployees);
// =================== END: DUMMY DATA FOR VISUAL PREVIEW ===================
const grouped = mockSchedules.reduce((acc, schedule) => {
const shiftName = schedule.shift_name.toUpperCase().trim();
if (!acc[shiftName]) {
acc[shiftName] = { users: [], lastUpdate: { user: 'N/A', timestamp: '1970-01-01T00:00:00Z' } };
}
acc[shiftName].users.push(schedule);
// Find the latest update timestamp for the shift
const currentUpdate = new Date(schedule.updated_at || schedule.created_at);
const lastUpdate = new Date(acc[shiftName].lastUpdate.timestamp);
if (currentUpdate > lastUpdate) {
acc[shiftName].lastUpdate = {
user: schedule.updated_by || 'N/A',
timestamp: currentUpdate.toISOString()
};
}
return acc;
}, {});
const finalGrouped = {
'PAGI': grouped['PAGI'] || { users: [], lastUpdate: { user: 'N/A', timestamp: new Date().toISOString() } },
'SIANG': grouped['SIANG'] || { users: [], lastUpdate: { user: 'N/A', timestamp: new Date().toISOString() } },
'MALAM': grouped['MALAM'] || { users: [], lastUpdate: { user: 'N/A', timestamp: new Date().toISOString() } },
};
setGroupedSchedules(finalGrouped);
} catch (error) {
console.error('Error processing dummy data:', error);
NotifAlert({ // Changed to NotifAlert for consistency
icon: 'error', // Changed to error icon
title: 'Gagal Memuat Data', // Changed title
message: 'Terjadi kesalahan saat memuat data jadwal shift.', // Changed message
});
} finally {
// Add a small delay to simulate network loading
setTimeout(() => setLoading(false), 500);
}
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
if (props.actionMode === 'list') {
setFormDataFilter(defaultFilter);
doFilter();
}
fetchData();
} else {
navigate('/signin');
}
}, [props.actionMode]);
}, [searchValue, props.actionMode]); // Refetch when searchValue changes or after modal closes
const doFilter = () => {
setTrigerFilter((prev) => !prev);
};
const handleSearch = () => {
setFormDataFilter({ criteria: searchValue });
setTrigerFilter((prev) => !prev);
const handleSearch = (value) => {
setSearchValue(value);
};
const handleSearchClear = () => {
setSearchValue('');
setFormDataFilter({ criteria: '' });
setTrigerFilter((prev) => !prev);
};
const showPreviewModal = (param) => {
props.setSelectedData(param);
props.setActionMode('preview');
};
const showEditModal = (param = null) => {
props.setSelectedData(param);
props.setActionMode('edit');
};
const showAddModal = (param = null) => {
@@ -155,123 +148,361 @@ const ListJadwalShift = memo(function ListJadwalShift(props) {
props.setActionMode('add');
};
const showDeleteDialog = (param) => {
const dateStr = param.schedule_date ? new Date(param.schedule_date).toLocaleDateString('id-ID') : 'tanggal tidak diketahui';
const handleAction = (mode, record) => {
props.setSelectedData(record);
props.setActionMode(mode);
};
const showDeleteDialog = (user) => {
NotifConfirmDialog({
icon: 'question',
title: 'Konfirmasi Hapus',
message: `Jadwal shift tanggal ${dateStr} akan dihapus?`,
onConfirm: () => handleDelete(param.schedule_id),
onCancel: () => props.setSelectedData(null),
message: `Hapus jadwal untuk karyawan "${user.nama_employee}"?`,
onConfirm: () => handleDelete(user.schedule_id),
});
};
const handleDelete = async (id) => {
const handleDelete = async (schedule_id) => {
try {
const response = await deleteJadwalShift(id);
if (response.statusCode === 200) {
NotifAlert({
icon: 'success',
title: 'Berhasil',
message: 'Data Jadwal Shift berhasil dihapus.',
});
doFilter();
} else {
NotifAlert({
icon: 'error',
title: 'Error',
message: response.message || 'Gagal menghapus data jadwal shift.',
});
}
await deleteJadwalShift(schedule_id);
NotifOk({ icon: 'success', title: 'Berhasil', message: 'Jadwal berhasil dihapus.' });
fetchData(); // Refresh data
} catch (error) {
console.error('Error deleting jadwal shift:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Terjadi kesalahan saat menghapus data.',
});
console.error("Failed to delete schedule:", error);
NotifAlert({ icon: "error", title: "Gagal", message: "Gagal menghapus jadwal." });
}
};
const handleShiftEditMode = (shiftName) => {
setEditingShift(shiftName);
setPendingChanges({}); // Clear pending changes
setSelectedSchedules([]); // Clear selections when entering a new edit mode
};
const cancelShiftEditMode = () => {
setEditingShift(null);
setPendingChanges({});
setSelectedSchedules([]);
};
const handleSelectSchedule = (scheduleId, isChecked) => {
if (isChecked) {
setSelectedSchedules(prev => [...prev, scheduleId]);
} else {
setSelectedSchedules(prev => prev.filter(id => id !== scheduleId));
}
};
const handleBulkUpdateChange = (scheduleId, field, value) => {
setPendingChanges(prev => ({
...prev,
[scheduleId]: {
...prev[scheduleId],
[field]: value,
}
}));
};
const handleBulkSave = async () => {
if (Object.keys(pendingChanges).length === 0) {
NotifAlert({ icon: 'info', title: 'Tidak Ada Perubahan', message: 'Tidak ada perubahan untuk disimpan.' });
cancelShiftEditMode();
return;
}
const updatePromises = Object.keys(pendingChanges).map(scheduleId => {
const originalSchedule = groupedSchedules[editingShift].users.find(u => u.schedule_id.toString() === scheduleId);
const updatedData = { ...originalSchedule, ...pendingChanges[scheduleId] };
// return updateJadwalShift(scheduleId, updatedData); // UNCOMMENT FOR REAL API
console.log(`Simulating update for schedule ${scheduleId}:`, updatedData); // DUMMY LOG
return Promise.resolve(); // DUMMY PROMISE
});
try {
await Promise.all(updatePromises);
NotifOk({ icon: 'success', title: 'Berhasil', message: 'Semua perubahan berhasil disimpan.' });
fetchData();
cancelShiftEditMode();
} catch (error) {
NotifAlert({ icon: 'error', title: 'Gagal', message: 'Gagal menyimpan beberapa perubahan.' });
}
};
const handleBulkDelete = () => {
if (selectedSchedules.length === 0) {
NotifAlert({ icon: 'warning', title: 'Perhatian', message: 'Pilih setidaknya satu jadwal untuk dihapus.' });
return;
}
NotifConfirmDialog({
icon: 'question',
title: `Konfirmasi Hapus`,
message: `Anda yakin ingin menghapus ${selectedSchedules.length} jadwal yang dipilih?`,
onConfirm: async () => {
await Promise.all(selectedSchedules.map(id => deleteJadwalShift(id)));
NotifOk({ icon: 'success', title: 'Berhasil', message: `${selectedSchedules.length} jadwal berhasil dihapus.` });
fetchData();
// Exit both edit modes
setIsEditMode(false);
setEditingShift(null);
setSelectedSchedules([]);
},
});
};
return (
<React.Fragment>
<Card>
<Title level={3}>Jadwal Shift</Title>
<Divider />
<Row>
<Col xs={24}>
<Row justify="space-between" align="middle" gutter={[8, 8]}>
<Col xs={24} sm={24} md={12} lg={12}>
<Input.Search
placeholder="Cari jadwal shift..."
value={searchValue}
onChange={(e) => {
const value = e.target.value;
setSearchValue(value);
if (value === '') {
handleSearchClear();
}
}}
onSearch={handleSearch}
allowClear={{
clearIcon: <span onClick={handleSearchClear}></span>,
}}
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
{isEditMode ? (
<Col span={24}>
<Row justify="space-between" align="middle">
<Text strong>Mode Edit Halaman</Text>
<Space wrap align="center">
<Button onClick={() => { setIsEditMode(false); setPendingChanges({}); setSelectedSchedules([]); }}>
Batal
</Button>
<Button
type="primary"
danger
onClick={handleBulkDelete}
disabled={selectedSchedules.length === 0}
>
Hapus yang Dipilih ({selectedSchedules.length})
</Button>
<Button
type="primary"
onClick={handleBulkSave}
style={{ backgroundColor: '#23A55A', borderColor: '#23A55A' }}
>
Simpan Semua Perubahan
</Button>
</Space>
</Row>
</Col>
) : (
<>
<Col>
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
},
},
}}
>
Search
</Button>
}
size="large"
/>
</Col>
<Col>
<Space wrap size="small">
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
},
},
}}
>
<Button
icon={<PlusOutlined />}
onClick={() => showAddModal()}
<Button
icon={<EditOutlined />}
size="large"
onClick={() => { setIsEditMode(true); setEditingShift(null); setPendingChanges({}); setSelectedSchedules([]); }}
>
Edit Halaman
</Button>
</ConfigProvider>
</Col>
<Col xs={24} sm={24} md={12} lg={12}>
<Input.Search
placeholder="Cari berdasarkan nama..."
value={searchValue}
onChange={(e) => {
const value = e.target.value;
setSearchValue(value);
if (value === '') {
handleSearchClear();
}
}}
onSearch={handleSearch}
allowClear
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
}}
/>
}
size="large"
>
Tambah Data
</Button>
</ConfigProvider>
</Space>
</Col>
/>
</Col>
</>
)}
</Row>
</Col>
<Col xs={24} style={{ marginTop: '16px' }}>
<TableList
mobile
cardColor={'#42AAFF'}
header={'schedule_date'}
showPreviewModal={showPreviewModal}
showEditModal={showEditModal}
showDeleteDialog={showDeleteDialog}
getData={getData}
queryParams={formDataFilter}
columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
triger={trigerFilter}
/>
</Col>
</Row>
<Spin spinning={loading} tip="Memuat data...">
<div style={{ marginTop: '24px' }}>
{(Object.keys(groupedSchedules).length === 0 && !loading) ? (
<Text>Tidak ada data jadwal untuk ditampilkan.</Text>
) : (
Object.keys(groupedSchedules).map(shiftName => ( // Iterate through each shift (PAGI, SIANG, MALAM)
<div key={shiftName} style={{ marginBottom: '32px' }}> {/* Container for each shift section */}
<Row justify="space-between" align="middle" style={{ paddingBottom: '12px', borderBottom: '1px solid #f0f0f0', marginBottom: '16px' }}>
<Col>
<Title level={5} style={{ margin: 0 }}>
SHIFT {shiftName} ({groupedSchedules[shiftName].users.length} Karyawan)
</Title>
</Col>
{editingShift === shiftName ? (
<Col>
<Space wrap>
<Button onClick={cancelShiftEditMode}>Batal</Button>
<Button
type="primary"
danger
onClick={handleBulkDelete}
disabled={selectedSchedules.length === 0}
>
Hapus Dipilih ({selectedSchedules.length})
</Button>
<Button
type="primary"
onClick={handleBulkSave}
style={{ backgroundColor: '#23A55A', borderColor: '#23A55A' }}
>
Simpan Perubahan
</Button>
</Space>
</Col>
) : (
<Col>
<Space wrap>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => showAddModal({ shift_name: shiftName })}
style={{ backgroundColor: '#23A55A', borderColor: '#23A55A' }}
disabled={editingShift !== null || isEditMode}
>
Tambah User
</Button>
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
defaultHoverBorderColor: '#23A55A',
},
},
}}
>
<Button
icon={<EditOutlined />}
onClick={() => handleShiftEditMode(shiftName)}
disabled={editingShift !== null || isEditMode}
>
Edit
</Button>
</ConfigProvider>
</Space>
</Col>
)}
</Row>
{/* Horizontal scrollable container for employee cards */}
<div style={{ display: 'flex', overflowX: 'auto', gap: '16px', paddingBottom: '10px' }}>
{groupedSchedules[shiftName].users.length > 0 ? (
groupedSchedules[shiftName].users.map(user => (
<Card
key={user.nik}
hoverable
style={{
width: 320, height: 240, flexShrink: 0, textAlign: 'left', border: '1px solid #42AAFF',
opacity: (editingShift !== null && editingShift !== shiftName) ? 0.5 : 1, // Dim inactive shifts
pointerEvents: (editingShift !== null && editingShift !== shiftName) ? 'none' : 'auto' // Disable interaction on inactive shifts
}}
bodyStyle={{ padding: '16px', height: '100%' }}
>
{isEditMode && editingShift === null && ( // Checkbox for global delete mode only
<Checkbox
style={{ position: 'absolute', top: 16, right: 16, zIndex: 10 }}
checked={selectedSchedules.includes(user.schedule_id)}
onChange={(e) => handleSelectSchedule(user.schedule_id, e.target.checked)}
onClick={(e) => e.stopPropagation()} // Prevent card click
/>
)}
{editingShift === shiftName || (isEditMode && editingShift === null) ? ( // Global or Shift-specific Edit Mode
// EDIT MODE VIEW
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<Space direction="vertical" style={{ width: '100%', marginTop: '24px' }}>
<Select
showSearch
style={{ width: '100%' }}
placeholder="Pilih Karyawan"
optionFilterProp="children"
defaultValue={user.employee_id}
onChange={(value) => handleBulkUpdateChange(user.schedule_id, 'employee_id', value)}
>
{employeeOptions.map(emp => (
<Select.Option key={emp.employee_id} value={emp.employee_id}>{emp.nama_employee}</Select.Option>
))}
</Select>
<Select
style={{ width: '100%' }}
defaultValue={user.shift_name}
onChange={(value) => handleBulkUpdateChange(user.schedule_id, 'shift_name', value)}
>
<Select.Option value="PAGI">PAGI</Select.Option>
<Select.Option value="SIANG">SIANG</Select.Option>
<Select.Option value="MALAM">MALAM</Select.Option>
</Select>
</Space>
<Checkbox
style={{ position: 'absolute', top: 16, right: 16, zIndex: 10 }}
checked={selectedSchedules.includes(user.schedule_id)}
onChange={(e) => handleSelectSchedule(user.schedule_id, e.target.checked)}
/>
</div>
) : (
// NORMAL VIEW
<div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: '100%' }}>
<div>
<Text strong ellipsis style={{
fontSize: '22px', display: 'inline-block', backgroundColor: '#42AAFF',
color: '#FFFFFF', padding: '4px 8px', borderRadius: '4px', marginBottom: '8px'
}}>{user.nama_employee}</Text>
<Text style={{ fontSize: '18px', display: 'block' }}>{user.whatsapp}</Text>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
<Text style={{ fontSize: '12px', display: 'block', lineHeight: '1.4' }}>
<Text strong>Terakhir diperbarui</Text> <br />
{formatRelativeTimestamp(groupedSchedules[shiftName].lastUpdate.timestamp)} <br />
oleh {groupedSchedules[shiftName].lastUpdate.user}
</Text>
<Space>
<Button type="text" size="small" icon={<EyeOutlined />} onClick={() => handleAction('preview', user)} style={{ color: '#1890ff', borderColor: '#1890ff' }} />
<Button type="text" size="small" icon={<EditOutlined />} onClick={() => handleAction('edit', user)} style={{ color: '#faad14', borderColor: '#faad14' }} />
<Button danger type="text" size="small" icon={<DeleteOutlined />} onClick={() => showDeleteDialog(user)} style={{ borderColor: '#ff4d4f' }} />
</Space>
</div>
</div>
)}
</Card>
))
) : (
<Text type="secondary" style={{ marginLeft: '16px' }}>Tidak ada karyawan yang dijadwalkan untuk shift ini.</Text>
)}
</div>
</div>
))
)}
</div>
</Spin>
</Card>
</React.Fragment>
);
});
export default ListJadwalShift;
export default ListJadwalShift;