penambahan modul employee

This commit is contained in:
aji@catalis.app
2025-09-07 23:38:20 +07:00
parent b1040ac851
commit aa9a285684
2 changed files with 643 additions and 18 deletions

View File

@@ -0,0 +1,605 @@
<script lang="ts">
import { supabase } from "$lib/supabaseClient";
import { onMount } from "svelte";
import { writable } from "svelte/store";
type EmployeeItem = {
id: string;
employee_name: string;
employee_status: string;
location: string;
department: string;
contract_start: Date;
end_of_contract: Date;
employee_type: string;
date_of_birth: Date;
photo_url: string;
phone: string;
mobile: string;
personal_email: string;
wok_email: string;
permanent_address: string;
temporary_address: string;
job_title: string;
emergency_contact_name: string;
emergency_contract_phone: string;
bank_account: string;
jamsostek_id: string;
npwp_id: string;
remarks: string;
salary: number;
last_edu: string;
document: string;
url: string;
created_at?: Date;
};
type POItem = {
id: number;
item_name: string;
created_at?: Date;
};
let allRows: EmployeeItem[] = [];
let offset = 0;
type columns = {
key: string;
title: string;
};
const columns: columns[] = [
{ key: "no", title: "No. " },
{ key: "employee_name", title: "Employee Name" },
{ key: "employee_status", title: "Status" },
{ key: "location", title: "Location" },
{ key: "department", title: "Department" },
{ key: "contract_start", title: "Contract Start" },
{ key: "end_of_contract", title: "End of Contract" },
{ key: "employee_type", title: "Type" },
{ key: "date_of_birth", title: "Date of Birth" },
{ key: "photo_url", title: "Photo" },
{ key: "phone", title: "Phone" },
{ key: "mobile", title: "Mobile" },
{ key: "personal_email", title: "Personal Email" },
{ key: "wok_email", title: "Work Email" },
{ key: "permanent_address", title: "Permanent Address" },
{ key: "temporary_address", title: "Temporary Address" },
{ key: "job_title", title: "Job Title" },
{ key: "emergency_contact_name", title: "Emergency Contact Name" },
{ key: "emergency_contract_phone", title: "Emergency Contact Phone" },
{ key: "bank_account", title: "Bank Account" },
{ key: "jamsostek_id", title: "Jamsostek ID" },
{ key: "npwp_id", title: "NPWP ID" },
{ key: "remarks", title: "Remarks" },
{ key: "salary", title: "Salary" },
{ key: "last_edu", title: "Last Education" },
{ key: "document", title: "Document" },
{ key: "url", title: "URL" },
{ key: "created_at", title: "Created At" },
{ key: "actions", title: "Actions" },
];
let currentPage = offset + 1;
let rowsPerPage = 10;
let totalItems = 0;
async function fetchEmployee(
searchTerm: string | null = null,
sortColumn: string | null = "created_at",
sortOrder: "asc" | "desc" = "desc",
offset: number = 0,
limit: number = 10,
) {
const fromIndex = offset * limit;
const toIndex = fromIndex + limit - 1;
// Inisialisasi query
let query = supabase
.from("vb_employee")
.select("*", { count: "exact" })
.order(sortColumn || "created_at", {
ascending: sortOrder === "asc",
})
.range(fromIndex, toIndex); // Ini sudah termasuk offset & limit
// Tambahkan filter pencarian jika ada
if (searchTerm) {
query = query.ilike("emoloyee_name", `%${searchTerm}%`);
}
// Jalankan query
const { data, count, error } = await query;
if (error) {
console.error("Error fetching PO Employee:", error);
return;
}
allRows = data as EmployeeItem[];
totalItems = count || 0;
console.log("Fetched Employee:", allRows);
console.log("Total Items:", totalItems);
}
$: totalPages = Math.ceil(totalItems / rowsPerPage);
function goToPage(page: number) {
if (page < 1 || page > totalPages) return;
currentPage = page;
offset = (currentPage - 1) * rowsPerPage;
fetchEmployee(
null,
"created_at",
"desc",
(currentPage - 1) * rowsPerPage,
rowsPerPage,
);
}
function pageRange(
totalPages: number,
currentPage: number,
): (number | string)[] {
const range: (number | string)[] = [];
const maxDisplay = 5;
if (totalPages <= maxDisplay + 2) {
for (let i = 1; i <= totalPages; i++) range.push(i);
} else {
const start = Math.max(2, currentPage - 2);
const end = Math.min(totalPages - 1, currentPage + 2);
range.push(1);
if (start > 2) range.push("...");
for (let i = start; i <= end; i++) {
range.push(i);
}
if (end < totalPages - 1) range.push("...");
range.push(totalPages);
}
return range;
}
function changePage(page: number) {
if (page < 1 || page > totalPages || page === currentPage) return;
currentPage = page;
offset = (currentPage - 1) * rowsPerPage;
fetchEmployee(
null,
"created_at",
"desc",
(currentPage - 1) * rowsPerPage,
rowsPerPage,
);
}
onMount(() => {
fetchEmployee();
});
// Initialize the first page
$: currentPage = 1;
let showModal = false;
let isEditing = false;
let currentEditingId: string | null = null;
let newEmployeeInsert: EmployeeItem = {
id: "",
employee_name: "",
employee_status: "",
location: "",
department: "",
contract_start: new Date(),
end_of_contract: new Date(),
employee_type: "",
date_of_birth: new Date(),
photo_url: "",
phone: "",
mobile: "",
personal_email: "",
wok_email: "",
permanent_address: "",
temporary_address: "",
job_title: "",
emergency_contact_name: "",
emergency_contract_phone: "",
bank_account: "",
jamsostek_id: "",
npwp_id: "",
remarks: "",
salary: 0,
last_edu: "",
document: "",
url: "",
created_at: new Date(),
};
const excludedKeys = ["id", "actions", "created_at", "no"];
const formColumns = columns.filter(
(col) => !excludedKeys.includes(col.key),
);
function openModal(newEmployeeItem?: EmployeeItem) {
if (newEmployeeItem) {
console.log("Editing Employee:", newEmployeeItem);
isEditing = true;
currentEditingId = newEmployeeItem.id;
console.log("Current Editing ID:", currentEditingId);
// Copy data to avoid direct mutation
newEmployeeInsert = { ...newEmployeeItem };
} else {
isEditing = false;
currentEditingId = null;
newEmployeeInsert = {
id: "",
employee_name: "",
employee_status: "",
location: "",
department: "",
contract_start: new Date(),
end_of_contract: new Date(),
employee_type: "",
date_of_birth: new Date(),
photo_url: "",
phone: "",
mobile: "",
personal_email: "",
wok_email: "",
permanent_address: "",
temporary_address: "",
job_title: "",
emergency_contact_name: "",
emergency_contract_phone: "",
bank_account: "",
jamsostek_id: "",
npwp_id: "",
remarks: "",
salary: 0,
last_edu: "",
document: "",
url: "",
created_at: new Date(),
};
}
showModal = true;
}
async function saveEmployee(event: Event) {
event.preventDefault();
const formData = new FormData(event.target as HTMLFormElement);
// Validate form data
if (!validateForm(formData)) {
console.error("Form validation failed");
return;
}
console.log("Saving Employee:", newEmployeeInsert);
if (isEditing && currentEditingId) {
const { error } = await supabase
.from("vb_employee")
.update(newEmployeeInsert)
.eq("id", currentEditingId);
if (error) {
alert("Error updating Employee: " + error.message);
console.error("Error updating Employee:", error);
return;
} else {
alert("Employee updated successfully!");
}
} else {
const { error } = await supabase
.from("vb_employee")
.insert(newEmployeeInsert);
if (error) {
alert("Error creating New Employee: " + error.message);
console.error("Error creating New Employee:", error);
return;
} else {
alert("New Employee created successfully!");
}
}
await fetchEmployee(
null,
"created_at",
"desc",
(currentPage - 1) * rowsPerPage,
rowsPerPage,
);
showModal = false;
}
async function deleteEmployee(id: string) {
if (confirm("Are you sure you want to delete this Employee?")) {
const { error } = await supabase
.from("vb_employee")
.delete()
.eq("id", id);
if (error) {
console.error("Error deleting Employee:", error);
return;
}
await fetchEmployee(
null,
"created_at",
"desc",
(currentPage - 1) * rowsPerPage,
rowsPerPage,
);
}
}
export let formErrors = writable<{ [key: string]: string }>({});
function validateForm(formData: FormData): boolean {
const errors: { [key: string]: string } = {};
const requiredFields = [
"employee_name",
// Add other required fields here if necessary
];
requiredFields.forEach((field) => {
if (!formData.get(field) || formData.get(field) === "") {
errors[field] = `${field.replace(/_/g, " ")} is required.`;
}
});
formErrors.set(errors);
return Object.keys(errors).length === 0;
}
function errorClass(field: string): string {
return $formErrors[field] ? "border-red-500" : "border";
}
</script>
<div>
<div
class="p-6 bg-white shadow-md rounded-2xl mb-4 flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4"
>
<div>
<h2
class="text-lg font-semibold text-gray-800 flex items-center gap-2"
>
<span class="text-blue-600">👥</span>
Employee
</h2>
<p class="text-sm text-gray-600">Manage your employee data here.</p>
</div>
<div class="flex flex-col sm:flex-row sm:items-center gap-2">
<input
type="text"
placeholder="🔍 Search by item name..."
class="border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none px-4 py-2 rounded-xl text-sm w-64 transition"
on:input={(e) => {
const searchTerm = (
e.target as HTMLInputElement
).value.toLowerCase();
fetchEmployee(searchTerm, "created_at", "desc");
}}
/>
<button
class="bg-gray-200 text-gray-700 px-4 py-2 rounded-xl hover:bg-gray-300 text-sm transition"
on:click={() =>
fetchEmployee(null, "created_at", "desc", 0, 10)}
>
🔄 Reset
</button>
<button
class="bg-blue-600 text-white px-4 py-2 rounded-xl hover:bg-blue-700 text-sm transition"
on:click={() => openModal()}
>
New Employee
</button>
</div>
</div>
<div class="overflow-x-auto rounded-lg shadow mb-4">
<table class="w-full divide-y divide-gray-200 text-sm">
<thead class="bg-gray-100">
<tr>
{#each columns as col}
{#if col.key === "guest_name"}
<th
class="sticky left-0 px-4 py-3 text-left font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap"
style="background-color: #f0f8ff; z-index: 10;"
>
{col.title}
</th>
{:else}
<th
class="px-4 py-3 text-left font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap"
>
{col.title}
</th>
{/if}
{/each}
</tr>
</thead>
<tbody class="divide-y divide-gray-200 bg-white">
{#each allRows as row, i}
<tr class="hover:bg-gray-50 transition">
{#each columns as col}
{#if col.key === "no"}
<td class="px-4 py-2 font-medium text-gray-800">
{offset + i + 1}
</td>
{:else if col.key === "employee_name"}
<td class="px-4 py-2 font-medium text-gray-800">
{row[col.key as keyof EmployeeItem]}
</td>
{:else if col.key === "created_at"}
<td class="px-4 py-2">
{row[col.key as keyof EmployeeItem]
? new Date(
row[
col.key as keyof EmployeeItem
] as string | number | Date,
).toLocaleDateString()
: "N/A"}
</td>
{:else if col.key === "actions"}
<td class="px-4 py-2">
<button
class="inline-flex items-center gap-1 rounded bg-blue-600 px-3 py-1.5 text-white text-xs font-medium hover:bg-blue-700"
on:click={() => openModal(row)}
>
✏️ Edit
</button>
<button
class="inline-flex items-center gap-1 rounded bg-red-600 px-3 py-1.5 text-white text-xs font-medium hover:bg-red-700"
on:click={() => deleteEmployee(row.id)}
>
🗑️ Delete
</button>
</td>
{:else}
<td class="px-4 py-2">
{row[col.key as keyof EmployeeItem]}
</td>
{/if}
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
<!-- Pagination controls -->
<div class="flex justify-between items-center text-sm">
<div>
Showing {(currentPage - 1) * rowsPerPage + 1}
{Math.min(currentPage * rowsPerPage, totalItems)} of {totalItems} items
</div>
<div class="space-x-2">
<button
class="px-3 py-1 rounded border border-gray-300 bg-white hover:bg-gray-100 disabled:opacity-50"
on:click={() => goToPage(currentPage - 1)}
disabled={currentPage === 1}
>
Previous
</button>
{#each pageRange(totalPages, currentPage) as page}
{#if page === "..."}
<span class="px-2">...</span>
{:else}
<button
on:click={() => changePage(page as number)}
class="px-2 py-1 border rounded {page === currentPage
? 'bg-blue-600 text-white border-blue-600'
: 'bg-white border-gray-300 hover:bg-gray-100'}"
>
{page}
</button>
{/if}
{/each}
<button
class="px-3 py-1 rounded border border-gray-300 bg-white hover:bg-gray-100 disabled:opacity-50"
on:click={() => goToPage(currentPage + 1)}
disabled={currentPage === totalPages}
>
Next
</button>
</div>
</div>
</div>
{#if showModal}
<div
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
>
<div
class="bg-white rounded-lg shadow-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto"
>
<h2 class="text-xl font-semibold mb-4">
{isEditing ? "Edit Employee" : "New Employee"}
</h2>
<form on:submit={saveEmployee} class="space-y-4">
{#each formColumns as col}
<div class="mb-4">
<label
for={col.key}
class="block text-sm font-medium text-gray-700 mb-1"
>{col.title}</label
>
{#if col.key === "contract_start" || col.key === "end_of_contract" || col.key === "date_of_birth"}
<input
type="date"
id={col.key}
bind:value={
newEmployeeInsert[
col.key as keyof EmployeeItem
]
}
class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 {errorClass(
col.key,
)}"
/>
{:else if col.key === "salary"}
<input
type="number"
id={col.key}
bind:value={
newEmployeeInsert[
col.key as keyof EmployeeItem
]
}
class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 {errorClass(
col.key,
)}"
/>
{:else}
<input
type="text"
id={col.key}
bind:value={
newEmployeeInsert[
col.key as keyof EmployeeItem
]
}
class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 {errorClass(
col.key,
)}"
/>
{/if}
{#if $formErrors[col.key]}
<p class="text-red-500 text-xs mt-1">
{$formErrors[col.key]}
</p>
{/if}
</div>
{/each}
<div class="flex justify-end space-x-2">
<button
type="button"
class="px-4 py-2 bg-gray-200 text-gray-700 rounded-xl hover:bg-gray-300"
on:click={() => (showModal = false)}
>
Cancel
</button>
<button
type="submit"
class="px-4 py-2 bg-blue-600 text-white rounded-xl hover:bg-blue-700"
>
{isEditing ? "Update" : "Create"}
</button>
</div>
</form>
</div>
</div>
{/if}

View File

@@ -10,10 +10,10 @@
"@jridgewell/gen-mapping" "^0.3.5"
"@jridgewell/trace-mapping" "^0.3.24"
"@esbuild/win32-x64@0.25.4":
"@esbuild/linux-x64@0.25.4":
version "0.25.4"
resolved "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.4.tgz"
integrity sha512-nOT2vZNw6hJ+z43oP1SPea/G/6AbN6X+bGNhNuq8NtRHy4wsMhw765IKLNmnjek7GvjWBYQ8Q5VBoYTFg9y1UQ==
resolved "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.4.tgz"
integrity sha512-6e0cvXwzOnVWJHq+mskP8DNSrKBr1bULBvnFLpc1KY+d+irZSgZ02TGse5FsafKS5jg2e4pbvK6TPXaF/A6+CA==
"@fast-csv/format@4.3.5":
version "4.3.5"
@@ -144,10 +144,20 @@
estree-walker "^2.0.2"
picomatch "^4.0.2"
"@rollup/rollup-win32-x64-msvc@4.41.1":
"@rollup/rollup-linux-x64-gnu@4.41.1":
version "4.41.1"
resolved "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.41.1.tgz"
integrity sha512-Wq2zpapRYLfi4aKxf2Xff0tN+7slj2d4R87WEzqw7ZLsVvO5zwYCIuEGSZYiK41+GlwUo1HiR+GdkLEJnCKTCw==
resolved "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.41.1.tgz"
integrity sha512-cWBOvayNvA+SyeQMp79BHPK8ws6sHSsYnK5zDcsC3Hsxr1dgTABKjMnMslPq1DvZIp6uO7kIWhiGwaTdR4Og9A==
"@rollup/rollup-linux-x64-gnu@4.9.5":
version "4.9.5"
resolved "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.9.5.tgz"
integrity sha512-Dq1bqBdLaZ1Gb/l2e5/+o3B18+8TI9ANlA1SkejZqDgdU/jK/ThYaMPMJpVMMXy2uRHvGKbkz9vheVGdq3cJfA==
"@rollup/rollup-linux-x64-musl@4.41.1":
version "4.41.1"
resolved "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.41.1.tgz"
integrity sha512-y5CbN44M+pUCdGDlZFzGGBSKCA4A/J2ZH4edTYSSxFg7ce1Xt3GtydbVKWLlzL+INfFIZAEg1ZV6hh9+QQf9YQ==
"@supabase/auth-js@2.69.1":
version "2.69.1"
@@ -283,10 +293,15 @@
source-map-js "^1.2.1"
tailwindcss "4.1.7"
"@tailwindcss/oxide-win32-x64-msvc@4.1.7":
"@tailwindcss/oxide-linux-x64-gnu@4.1.7":
version "4.1.7"
resolved "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.1.7.tgz"
integrity sha512-rYHGmvoHiLJ8hWucSfSOEmdCBIGZIq7SpkPRSqLsH2Ab2YUNgKeAPT1Fi2cx3+hnYOrAb0jp9cRyode3bBW4mQ==
resolved "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.1.7.tgz"
integrity sha512-HMs+Va+ZR3gC3mLZE00gXxtBo3JoSQxtu9lobbZd+DmfkIxR54NO7Z+UQNPsa0P/ITn1TevtFxXTpsRU7qEvWg==
"@tailwindcss/oxide-linux-x64-musl@4.1.7":
version "4.1.7"
resolved "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.1.7.tgz"
integrity sha512-MHZ6jyNlutdHH8rd+YTdr3QbXrHXqwIhHw9e7yXEBcQdluGwhpQY2Eku8UZK6ReLaWtQ4gijIv5QoM5eE+qlsA==
"@tailwindcss/oxide@4.1.7":
version "4.1.7"
@@ -588,9 +603,9 @@ crc32-stream@^4.0.2:
readable-stream "^3.4.0"
dayjs@^1.8.34:
version "1.11.13"
resolved "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz"
integrity sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==
version "1.11.18"
resolved "https://registry.npmjs.org/dayjs/-/dayjs-1.11.18.tgz"
integrity sha512-zFBQ7WFRvVRhKcWoUh+ZA1g2HVgUbsZm9sbddh8EC5iv93sui8DVVz1Npvz+r6meo9VKfa8NyLWBsQK1VvIKPA==
debug@^4.3.7, debug@^4.4.0:
version "4.4.1"
@@ -854,10 +869,15 @@ lie@~3.3.0:
dependencies:
immediate "~3.0.5"
lightningcss-win32-x64-msvc@1.30.1:
lightningcss-linux-x64-gnu@1.30.1:
version "1.30.1"
resolved "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.30.1.tgz"
integrity sha512-PVqXh48wh4T53F/1CCu8PIPCxLzWyCnn/9T5W1Jpmdy5h9Cwd+0YQS6/LwhHXSafuc61/xg9Lv5OrCby6a++jg==
resolved "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.30.1.tgz"
integrity sha512-piWx3z4wN8J8z3+O5kO74+yr6ze/dKmPnI7vLqfSqI8bccaTGY5xiSGVIJBDd5K5BHlvVLpUB3S2YCfelyJ1bw==
lightningcss-linux-x64-musl@1.30.1:
version "1.30.1"
resolved "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.30.1.tgz"
integrity sha512-rRomAK7eIkL+tHY0YPxbc5Dra2gXlI63HL+v1Pdi1a3sC+tJTcFrHX+E86sulgAXeI7rSzDYhPSeHHjqFhqfeQ==
lightningcss@^1.21.0, lightningcss@1.30.1:
version "1.30.1"
@@ -1358,9 +1378,9 @@ tinyglobby@^0.2.13:
picomatch "^4.0.2"
tmp@^0.2.0:
version "0.2.4"
resolved "https://registry.npmjs.org/tmp/-/tmp-0.2.4.tgz"
integrity sha512-UdiSoX6ypifLmrfQ/XfiawN6hkjSBpCjhKxxZcWlUUmoXLaCKQU0bx4HF/tdDK2uzRuchf1txGvrWBzYREssoQ==
version "0.2.5"
resolved "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz"
integrity sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==
totalist@^3.0.0:
version "3.0.1"