CI / build (push) Successful in 2m2s
Contractors are not in HR. Store them in COST_MODEL_DATA_DIR (contractors.json, never in Git) behind a PUT /api/cost-model/contractors endpoint with server-side normalization, and save automatically from the board whenever the contractor list changes. Production no longer shows the synthetic seed contractors. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
6078 lines
315 KiB
HTML
6078 lines
315 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-TW">
|
||
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Studio Cost Model Pro - Animation KPI System</title>
|
||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/xlsx.full.min.js"></script>
|
||
<style>
|
||
:root {
|
||
/* Color Palette - Premium Dark Mode SaaS */
|
||
--bg-deep: #030712;
|
||
--bg-surface: rgba(10, 10, 10, 0.5);
|
||
--bg-glass: rgba(255, 255, 255, 0.02);
|
||
--border-glass: rgba(255, 255, 255, 0.08);
|
||
|
||
--accent-primary: #3b82f6;
|
||
--accent-secondary: #8b5cf6;
|
||
--accent-success: #10b981;
|
||
--accent-warning: #f59e0b;
|
||
--accent-danger: #ef4444;
|
||
|
||
--text-main: #ffffff;
|
||
--text-muted: #9ca3af;
|
||
--text-dim: #6b7280;
|
||
|
||
--panel-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5);
|
||
--transition-speed: 0.3s;
|
||
}
|
||
|
||
* {
|
||
margin: 0;
|
||
padding: 0;
|
||
box-sizing: border-box;
|
||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||
}
|
||
|
||
body {
|
||
background-color: var(--bg-deep);
|
||
color: var(--text-main);
|
||
overflow-x: hidden;
|
||
min-height: 100vh;
|
||
position: relative;
|
||
}
|
||
|
||
/* --- Keyframe Animations --- */
|
||
@keyframes blobShift {
|
||
0% {
|
||
background: var(--accent-primary);
|
||
opacity: 0.15;
|
||
}
|
||
|
||
50% {
|
||
background: var(--accent-secondary);
|
||
opacity: 0.18;
|
||
}
|
||
|
||
100% {
|
||
background: var(--accent-primary);
|
||
opacity: 0.15;
|
||
}
|
||
}
|
||
|
||
@keyframes simBlobShift {
|
||
0% {
|
||
background: #f59e0b;
|
||
opacity: 0.20;
|
||
}
|
||
|
||
33% {
|
||
background: #ef4444;
|
||
opacity: 0.15;
|
||
}
|
||
|
||
66% {
|
||
background: #f97316;
|
||
opacity: 0.22;
|
||
}
|
||
|
||
100% {
|
||
background: #f59e0b;
|
||
opacity: 0.20;
|
||
}
|
||
}
|
||
|
||
@keyframes simBlobShift2 {
|
||
0% {
|
||
background: #dc2626;
|
||
opacity: 0.15;
|
||
}
|
||
|
||
50% {
|
||
background: #f59e0b;
|
||
opacity: 0.20;
|
||
}
|
||
|
||
100% {
|
||
background: #dc2626;
|
||
opacity: 0.15;
|
||
}
|
||
}
|
||
|
||
@keyframes sidebarPulse {
|
||
|
||
0%,
|
||
100% {
|
||
box-shadow: inset -1px 0 0 rgba(245, 158, 11, 0.3), -4px 0 20px rgba(245, 158, 11, 0.0);
|
||
}
|
||
|
||
50% {
|
||
box-shadow: inset -1px 0 0 rgba(245, 158, 11, 0.8), -4px 0 28px rgba(245, 158, 11, 0.25);
|
||
}
|
||
}
|
||
|
||
@keyframes badgePulse {
|
||
|
||
0%,
|
||
100% {
|
||
box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.6);
|
||
transform: scale(1);
|
||
}
|
||
|
||
50% {
|
||
box-shadow: 0 0 0 6px rgba(245, 158, 11, 0);
|
||
transform: scale(1.04);
|
||
}
|
||
}
|
||
|
||
@keyframes simBarFlow {
|
||
0% {
|
||
background-position: 0% 50%;
|
||
}
|
||
|
||
50% {
|
||
background-position: 100% 50%;
|
||
}
|
||
|
||
100% {
|
||
background-position: 0% 50%;
|
||
}
|
||
}
|
||
|
||
@keyframes simBarSlideIn {
|
||
from {
|
||
transform: translateY(-100%);
|
||
opacity: 0;
|
||
}
|
||
|
||
to {
|
||
transform: translateY(0);
|
||
opacity: 1;
|
||
}
|
||
}
|
||
|
||
@keyframes blobMorph {
|
||
0% {
|
||
border-radius: 50%;
|
||
}
|
||
|
||
33% {
|
||
border-radius: 60% 40% 55% 45%;
|
||
}
|
||
|
||
66% {
|
||
border-radius: 40% 60% 45% 55%;
|
||
}
|
||
|
||
100% {
|
||
border-radius: 50%;
|
||
}
|
||
}
|
||
|
||
/* Glowing Nebula Background Blobs */
|
||
body::before,
|
||
body::after {
|
||
content: "";
|
||
position: fixed;
|
||
border-radius: 50%;
|
||
filter: blur(120px);
|
||
z-index: -1;
|
||
opacity: 0.15;
|
||
pointer-events: none;
|
||
transition: background 1.5s ease, opacity 1.5s ease;
|
||
}
|
||
|
||
body::before {
|
||
top: -10%;
|
||
left: -10%;
|
||
width: 50vw;
|
||
height: 50vw;
|
||
background: var(--accent-primary);
|
||
animation: blobMorph 8s ease-in-out infinite, blobShift 6s ease-in-out infinite;
|
||
}
|
||
|
||
body::after {
|
||
bottom: -10%;
|
||
right: -10%;
|
||
width: 60vw;
|
||
height: 60vw;
|
||
background: var(--accent-secondary);
|
||
animation: blobMorph 10s ease-in-out infinite reverse, blobShift 8s ease-in-out infinite reverse;
|
||
}
|
||
|
||
/* ============================================
|
||
SIMULATION MODE - Immersive Visual Override
|
||
============================================ */
|
||
.mode-sim::before {
|
||
animation: blobMorph 5s ease-in-out infinite, simBlobShift 4s ease-in-out infinite !important;
|
||
}
|
||
|
||
.mode-sim::after {
|
||
animation: blobMorph 7s ease-in-out infinite reverse, simBlobShift2 5s ease-in-out infinite !important;
|
||
}
|
||
|
||
/* Sidebar amber pulse in sim mode */
|
||
.mode-sim header {
|
||
border-right-color: rgba(245, 158, 11, 0.4);
|
||
animation: sidebarPulse 2.5s ease-in-out infinite;
|
||
transition: border-right-color 0.8s ease;
|
||
}
|
||
|
||
/* Nav active item in sim mode */
|
||
.mode-sim .nav-item.active {
|
||
box-shadow: inset 0 0 0 1px rgba(245, 158, 11, 0.3), 0 0 15px rgba(245, 158, 11, 0.15);
|
||
background: rgba(245, 158, 11, 0.08);
|
||
}
|
||
|
||
.mode-sim .nav-item:hover {
|
||
background-color: rgba(245, 158, 11, 0.06);
|
||
}
|
||
|
||
/* Sim mode persistent top banner */
|
||
#sim-mode-topbar {
|
||
display: none;
|
||
position: fixed;
|
||
top: 0;
|
||
left: 0;
|
||
right: 0;
|
||
z-index: 999;
|
||
height: 4px;
|
||
background: linear-gradient(90deg, #f59e0b, #ef4444, #f97316, #f59e0b, #ef4444, #f97316);
|
||
background-size: 300% 100%;
|
||
animation: simBarFlow 2s linear infinite;
|
||
}
|
||
|
||
.mode-sim #sim-mode-topbar {
|
||
display: block;
|
||
}
|
||
|
||
/* --- Layout --- */
|
||
.app-container {
|
||
display: grid;
|
||
grid-template-columns: 260px minmax(0, 1fr);
|
||
grid-template-rows: auto minmax(0, 1fr);
|
||
grid-template-areas: "sidebar notice" "sidebar content";
|
||
height: 100vh;
|
||
height: 100dvh;
|
||
}
|
||
|
||
#data-source-banner {
|
||
grid-area: notice;
|
||
min-width: 0;
|
||
}
|
||
|
||
/* --- Sidebar --- */
|
||
header {
|
||
grid-area: sidebar;
|
||
min-height: 0;
|
||
overflow: hidden;
|
||
background-color: transparent;
|
||
border-right: 1px solid var(--border-glass);
|
||
padding: 2rem 1.5rem;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 1.5rem;
|
||
position: sticky;
|
||
top: 0;
|
||
height: 100%;
|
||
backdrop-filter: blur(10px);
|
||
}
|
||
|
||
.logo {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: flex-start;
|
||
padding: 0.5rem 0;
|
||
}
|
||
|
||
.logo img {
|
||
max-width: 100%;
|
||
height: auto;
|
||
max-height: 32px;
|
||
filter: drop-shadow(0 0 8px rgba(59, 130, 246, 0.3));
|
||
}
|
||
|
||
.nav-group {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 0.5rem;
|
||
}
|
||
|
||
header > .logo { flex-shrink: 0; }
|
||
.sidebar-navigation { flex: 1; min-height: 0; overflow-y: auto; }
|
||
.sidebar-account { flex-shrink: 0; margin-top: auto; padding-top: 0.75rem; border-top: 1px solid var(--border-glass); }
|
||
.sidebar-account .btn { width: 100%; justify-content: center; text-align: center; }
|
||
|
||
.nav-item {
|
||
padding: 0.75rem 1rem;
|
||
border-radius: 99px;
|
||
cursor: pointer;
|
||
transition: all var(--transition-speed);
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 0.75rem;
|
||
color: var(--text-muted);
|
||
font-weight: 500;
|
||
}
|
||
|
||
.nav-item:hover,
|
||
.nav-item.active {
|
||
background-color: rgba(255, 255, 255, 0.05);
|
||
color: var(--text-main);
|
||
}
|
||
|
||
.nav-item.active {
|
||
box-shadow: inset 0 0 0 1px var(--border-glass), 0 0 15px rgba(59, 130, 246, 0.1);
|
||
background: rgba(59, 130, 246, 0.05);
|
||
}
|
||
|
||
.mode-badge {
|
||
font-size: 0.7rem;
|
||
padding: 4px 10px;
|
||
border-radius: 99px;
|
||
margin-top: 1rem;
|
||
text-align: center;
|
||
text-transform: uppercase;
|
||
font-weight: 900;
|
||
transition: background 0.6s ease, color 0.6s ease, box-shadow 0.6s ease;
|
||
}
|
||
|
||
.mode-admin .mode-badge {
|
||
background: var(--accent-secondary);
|
||
color: white;
|
||
}
|
||
|
||
.mode-sim .mode-badge {
|
||
background: linear-gradient(90deg, #f59e0b, #ef4444, #f97316);
|
||
background-size: 200% 100%;
|
||
color: white;
|
||
animation: simBarFlow 1.8s linear infinite, badgePulse 1.8s ease-in-out infinite;
|
||
}
|
||
|
||
|
||
/* --- Input & Forms --- */
|
||
input::-webkit-outer-spin-button,
|
||
input::-webkit-inner-spin-button {
|
||
-webkit-appearance: none;
|
||
appearance: none;
|
||
margin: 0;
|
||
}
|
||
|
||
input[type=number] {
|
||
-moz-appearance: textfield;
|
||
appearance: textfield;
|
||
}
|
||
|
||
input {
|
||
background: rgba(255, 255, 255, 0.03);
|
||
border: 1px solid var(--border-glass);
|
||
padding: 6px 10px;
|
||
border-radius: 6px;
|
||
color: white;
|
||
font-size: 0.85rem;
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
input:focus {
|
||
outline: none;
|
||
border-color: var(--accent-primary);
|
||
background: rgba(255, 255, 255, 0.08);
|
||
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
|
||
}
|
||
|
||
.input-mini {
|
||
padding: 4px 2px !important;
|
||
text-align: center;
|
||
}
|
||
|
||
.sub-item.active::before {
|
||
background: var(--accent-primary);
|
||
opacity: 1;
|
||
}
|
||
|
||
@keyframes slideDown {
|
||
from {
|
||
opacity: 0;
|
||
transform: translateY(-5px);
|
||
}
|
||
|
||
to {
|
||
opacity: 1;
|
||
transform: translateY(0);
|
||
}
|
||
}
|
||
|
||
|
||
/* --- Main Content --- */
|
||
main {
|
||
grid-area: content;
|
||
min-width: 0;
|
||
min-height: 0;
|
||
padding: 1.25rem 2rem;
|
||
overflow-y: auto;
|
||
}
|
||
|
||
/* Dashboard grows with its content; the main panel owns scrolling. */
|
||
#dashboard.view.active {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 1rem;
|
||
}
|
||
.dashboard-heading { display:flex; flex-wrap:wrap; align-items:center; gap:1rem; }
|
||
#dashboard-invoice-hero { flex:1 1 600px; min-width:0; }
|
||
#dashboard-invoice-hero > div { flex-wrap:wrap; }
|
||
#dashboard-invoice-hero > div > div:last-child { flex-wrap:wrap; }
|
||
.dashboard-panels {
|
||
display:grid;
|
||
grid-template-columns:repeat(auto-fit, minmax(min(100%, 280px), 1fr));
|
||
gap:1rem;
|
||
align-items:stretch;
|
||
}
|
||
.dashboard-panels > .card { min-width:0; margin:0; }
|
||
#dashboard .kpi-grid { margin:0; }
|
||
#dashboard .card-value { overflow-wrap:anywhere; }
|
||
|
||
.view {
|
||
display: none;
|
||
animation: fadeIn 0.4s ease-out;
|
||
}
|
||
|
||
.view.active {
|
||
display: block;
|
||
}
|
||
|
||
.invoice-allocation-scroll { overflow-x: auto; }
|
||
#personnel > div:first-child { flex-wrap: wrap; gap: 1rem; }
|
||
#personnel > div:first-child > div:last-child { flex-wrap: wrap; }
|
||
#personnel > div:first-child .card { flex-wrap: wrap; }
|
||
#personnel-search { min-width: 190px; }
|
||
#personnel .btn { white-space: nowrap; }
|
||
#personnel-detail-kpi { flex-wrap: wrap; }
|
||
#personnel-detail-kpi > div { min-width: 160px; }
|
||
#personnel .table-container { overflow-x: auto; }
|
||
#person-table { min-width: 1300px; }
|
||
#person-table th { white-space: nowrap; }
|
||
#person-table td:first-child input { width: 125px !important; }
|
||
.invoice-allocation-table { min-width: 1000px; }
|
||
.invoice-allocation-row {
|
||
display: grid;
|
||
grid-template-columns: 1.5fr 1fr 1fr 1fr 1fr 1.2fr 1.2fr auto;
|
||
gap: 0.5rem;
|
||
align-items: center;
|
||
}
|
||
|
||
@media (max-width: 1350px) {
|
||
#global-params { grid-template-columns: minmax(0, 1fr) !important; }
|
||
.org-tree-container { align-items: flex-start; overflow-x: auto; }
|
||
.app-container { grid-template-columns: 210px minmax(0, 1fr); }
|
||
header { padding: 1.25rem 1rem; }
|
||
main { padding: 1rem; }
|
||
}
|
||
|
||
@keyframes fadeIn {
|
||
from {
|
||
opacity: 0;
|
||
transform: translateY(10px);
|
||
}
|
||
|
||
to {
|
||
opacity: 1;
|
||
transform: translateY(0);
|
||
}
|
||
}
|
||
|
||
/* --- KPI Cards --- */
|
||
.kpi-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||
gap: 0.9rem;
|
||
margin-bottom: 0.9rem;
|
||
}
|
||
|
||
/* Dept Invoice Target Bars */
|
||
.dept-invoice-bar-row {
|
||
margin-bottom: 0.65rem;
|
||
}
|
||
|
||
.dept-invoice-bar-row:last-child {
|
||
margin-bottom: 0;
|
||
}
|
||
|
||
.dept-invoice-bar-label {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
margin-bottom: 4px;
|
||
font-size: 0.8rem;
|
||
}
|
||
|
||
.dept-invoice-bar-track {
|
||
height: 8px;
|
||
background: rgba(255, 255, 255, 0.06);
|
||
border-radius: 4px;
|
||
overflow: hidden;
|
||
}
|
||
|
||
.dept-invoice-bar-fill {
|
||
height: 100%;
|
||
border-radius: 4px;
|
||
transition: width 0.6s cubic-bezier(0.16, 1, 0.3, 1);
|
||
}
|
||
|
||
.card {
|
||
background: var(--bg-glass);
|
||
backdrop-filter: blur(20px);
|
||
border: 1px solid var(--border-glass);
|
||
border-radius: 16px;
|
||
padding: 1.25rem 1.5rem;
|
||
box-shadow: var(--panel-shadow);
|
||
position: relative;
|
||
overflow: hidden;
|
||
}
|
||
|
||
.card::before {
|
||
content: "";
|
||
position: absolute;
|
||
top: 0;
|
||
left: 0;
|
||
width: 100%;
|
||
height: 2px;
|
||
background: linear-gradient(90deg, transparent, var(--accent-primary), transparent);
|
||
opacity: 0.8;
|
||
}
|
||
|
||
.card.secondary::before {
|
||
background: linear-gradient(90deg, transparent, var(--accent-secondary), transparent);
|
||
}
|
||
|
||
.card.success::before {
|
||
background: linear-gradient(90deg, transparent, var(--accent-success), transparent);
|
||
}
|
||
|
||
.card.warning::before {
|
||
background: linear-gradient(90deg, transparent, var(--accent-warning), transparent);
|
||
}
|
||
|
||
.card-label {
|
||
color: var(--text-dim);
|
||
font-size: 0.75rem;
|
||
text-transform: uppercase;
|
||
letter-spacing: 1px;
|
||
margin-bottom: 0.5rem;
|
||
}
|
||
|
||
.card-value {
|
||
font-size: 1.65rem;
|
||
font-weight: 800;
|
||
color: var(--text-main);
|
||
text-shadow: 0 0 20px rgba(255, 255, 255, 0.2);
|
||
}
|
||
|
||
.card.primary .card-value {
|
||
color: var(--accent-primary);
|
||
text-shadow: 0 0 20px rgba(59, 130, 246, 0.4);
|
||
}
|
||
|
||
.card-trend {
|
||
font-size: 0.72rem;
|
||
margin-top: 0.25rem;
|
||
color: var(--text-muted);
|
||
}
|
||
|
||
/* --- Chart Bars --- */
|
||
.chart-bar-container {
|
||
height: 30px;
|
||
background: rgba(255, 255, 255, 0.05);
|
||
border-radius: 8px;
|
||
overflow: hidden;
|
||
display: flex;
|
||
margin-top: 10px;
|
||
border: 1px solid var(--border-glass);
|
||
}
|
||
|
||
.chart-bar {
|
||
height: 100%;
|
||
transition: width 0.6s cubic-bezier(0.16, 1, 0.3, 1);
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 0.7rem;
|
||
font-weight: 700;
|
||
color: white;
|
||
white-space: nowrap;
|
||
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
|
||
}
|
||
|
||
|
||
/* --- Table Styling --- */
|
||
.table-container {
|
||
margin-top: 1rem;
|
||
border-radius: 20px;
|
||
overflow: auto;
|
||
border: 1px solid var(--border-glass);
|
||
background: var(--bg-glass);
|
||
backdrop-filter: blur(10px);
|
||
max-height: 70vh;
|
||
}
|
||
|
||
table {
|
||
width: 100%;
|
||
border-collapse: separate;
|
||
border-spacing: 0;
|
||
background: transparent;
|
||
font-size: 0.82rem;
|
||
}
|
||
|
||
thead {
|
||
position: sticky;
|
||
top: 0;
|
||
z-index: 10;
|
||
}
|
||
|
||
th {
|
||
background: rgba(255, 255, 255, 0.03);
|
||
text-align: left;
|
||
padding: 1rem;
|
||
color: var(--text-dim);
|
||
font-weight: 600;
|
||
text-transform: uppercase;
|
||
letter-spacing: 0.5px;
|
||
}
|
||
|
||
th.sortable {
|
||
cursor: pointer;
|
||
transition: all 0.2s;
|
||
position: relative;
|
||
padding-right: 1.5rem;
|
||
}
|
||
|
||
th.sortable:hover {
|
||
color: var(--accent-primary);
|
||
background: rgba(255, 255, 255, 0.05);
|
||
}
|
||
|
||
.sort-icon {
|
||
font-size: 0.7rem;
|
||
margin-left: 4px;
|
||
opacity: 0.5;
|
||
display: inline-block;
|
||
width: 12px;
|
||
}
|
||
|
||
th.active-sort {
|
||
color: var(--accent-primary);
|
||
background: rgba(59, 130, 246, 0.05);
|
||
}
|
||
|
||
th.active-sort .sort-icon {
|
||
opacity: 1;
|
||
}
|
||
|
||
th.num,
|
||
td.num {
|
||
text-align: right;
|
||
}
|
||
|
||
td {
|
||
padding: 0.75rem 0.5rem;
|
||
border-top: 1px solid var(--border-glass);
|
||
vertical-align: middle;
|
||
}
|
||
|
||
tr:hover td {
|
||
background: rgba(255, 255, 255, 0.02);
|
||
}
|
||
|
||
.role-pill {
|
||
padding: 4px 10px;
|
||
border-radius: 6px;
|
||
font-size: 0.75rem;
|
||
font-weight: 700;
|
||
}
|
||
|
||
.role-a {
|
||
background: rgba(59, 130, 246, 0.2);
|
||
color: #60a5fa;
|
||
}
|
||
|
||
.role-p {
|
||
background: rgba(16, 185, 129, 0.2);
|
||
color: #34d399;
|
||
}
|
||
|
||
.role-o {
|
||
background: rgba(245, 158, 11, 0.2);
|
||
color: #fbbf24;
|
||
}
|
||
|
||
/* --- Inputs & Buttons --- */
|
||
input {
|
||
background: rgba(0, 0, 0, 0.3);
|
||
border: 1px solid var(--border-glass);
|
||
border-radius: 99px;
|
||
padding: 0.5rem 1rem;
|
||
color: var(--text-main);
|
||
outline: none;
|
||
width: 100%;
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
.table-container input {
|
||
padding: 0.4rem 0.6rem;
|
||
border-radius: 6px;
|
||
border-color: transparent;
|
||
background: transparent;
|
||
}
|
||
|
||
.table-container input:hover,
|
||
.table-container input:focus {
|
||
background: rgba(0, 0, 0, 0.5);
|
||
border-color: var(--accent-primary);
|
||
}
|
||
|
||
input:focus {
|
||
border-color: var(--accent-primary);
|
||
}
|
||
|
||
.btn {
|
||
padding: 0.6rem 1.2rem;
|
||
border-radius: 99px;
|
||
/* Pill shape */
|
||
cursor: pointer;
|
||
font-weight: 600;
|
||
border: none;
|
||
transition: all 0.3s;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
gap: 0.5rem;
|
||
}
|
||
|
||
.btn-primary {
|
||
background: var(--accent-primary);
|
||
color: white;
|
||
box-shadow: 0 0 15px rgba(59, 130, 246, 0.3);
|
||
}
|
||
|
||
.btn-primary:hover {
|
||
box-shadow: 0 0 25px rgba(59, 130, 246, 0.5);
|
||
transform: translateY(-2px);
|
||
}
|
||
|
||
.btn-outline {
|
||
background: transparent;
|
||
border: 1px solid var(--border-glass);
|
||
color: var(--text-main);
|
||
}
|
||
|
||
.btn-outline:hover {
|
||
background: rgba(255, 255, 255, 0.05);
|
||
border-color: rgba(255, 255, 255, 0.2);
|
||
transform: translateY(-1px);
|
||
}
|
||
|
||
/* Customize Personnel Search Selects */
|
||
select.btn-outline {
|
||
background-color: #000 !important;
|
||
color: #fff !important;
|
||
appearance: none;
|
||
-webkit-appearance: none;
|
||
padding-right: 2rem !important;
|
||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='white' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
|
||
background-repeat: no-repeat;
|
||
background-position: calc(100% - 0.75rem) center;
|
||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||
}
|
||
|
||
select.btn-outline:hover {
|
||
background-color: #fff !important;
|
||
color: #000 !important;
|
||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='black' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
|
||
}
|
||
|
||
/* Ensure options are visible */
|
||
select.btn-outline option {
|
||
background-color: #151b23;
|
||
color: #fff;
|
||
}
|
||
|
||
/* --- Bottom Controls --- */
|
||
.bottom-shelf {
|
||
position: fixed;
|
||
bottom: 1.5rem;
|
||
right: 1.5rem;
|
||
display: flex;
|
||
gap: 1rem;
|
||
z-index: 100;
|
||
}
|
||
|
||
/* --- Add Person Modal --- */
|
||
.modal-backdrop {
|
||
position: fixed;
|
||
inset: 0;
|
||
background: rgba(0, 0, 0, 0.7);
|
||
backdrop-filter: blur(6px);
|
||
z-index: 2000;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
opacity: 0;
|
||
pointer-events: none;
|
||
transition: opacity 0.25s ease;
|
||
}
|
||
|
||
.modal-backdrop.open {
|
||
opacity: 1;
|
||
pointer-events: all;
|
||
}
|
||
|
||
.modal-overlay {
|
||
position: fixed;
|
||
top: 0;
|
||
left: 0;
|
||
width: 100vw;
|
||
height: 100vh;
|
||
background: rgba(0, 0, 0, 0.6);
|
||
backdrop-filter: blur(8px);
|
||
z-index: 9999;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
opacity: 0;
|
||
pointer-events: none;
|
||
transition: opacity 0.3s;
|
||
}
|
||
|
||
.modal-overlay.open {
|
||
opacity: 1;
|
||
pointer-events: auto;
|
||
}
|
||
|
||
.modal-box {
|
||
background: #171b22;
|
||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||
border-radius: 16px;
|
||
width: 90%;
|
||
max-width: 800px;
|
||
padding: 2rem;
|
||
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
|
||
transform: translateY(20px) scale(0.97);
|
||
transition: transform 0.25s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.25s ease;
|
||
opacity: 0;
|
||
position: relative;
|
||
}
|
||
|
||
.modal-backdrop.open .modal-box {
|
||
transform: translateY(0) scale(1);
|
||
opacity: 1;
|
||
}
|
||
|
||
.modal-box::before {
|
||
content: '';
|
||
position: absolute;
|
||
top: 0;
|
||
left: 0;
|
||
right: 0;
|
||
height: 3px;
|
||
border-radius: 20px 20px 0 0;
|
||
background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));
|
||
}
|
||
|
||
.mode-sim .modal-box::before {
|
||
background: linear-gradient(90deg, #f59e0b, #ef4444, #f97316);
|
||
}
|
||
|
||
.modal-title {
|
||
font-size: 1.15rem;
|
||
font-weight: 800;
|
||
color: var(--text-main);
|
||
margin-bottom: 1.5rem;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 0.5rem;
|
||
}
|
||
|
||
.modal-grid {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 1rem 1.25rem;
|
||
}
|
||
|
||
.modal-field {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 0.4rem;
|
||
}
|
||
|
||
.modal-field.full-width {
|
||
grid-column: 1 / -1;
|
||
}
|
||
|
||
.modal-label {
|
||
font-size: 0.72rem;
|
||
font-weight: 700;
|
||
color: var(--text-dim);
|
||
text-transform: uppercase;
|
||
letter-spacing: 0.8px;
|
||
}
|
||
|
||
.modal-input {
|
||
background: rgba(255, 255, 255, 0.04);
|
||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||
border-radius: 10px;
|
||
padding: 0.55rem 0.9rem;
|
||
color: var(--text-main);
|
||
font-size: 0.9rem;
|
||
font-family: inherit;
|
||
transition: border-color 0.2s, box-shadow 0.2s;
|
||
width: 100%;
|
||
appearance: none;
|
||
-webkit-appearance: none;
|
||
}
|
||
|
||
.modal-input:focus {
|
||
outline: none;
|
||
border-color: var(--accent-primary);
|
||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
||
background: rgba(59, 130, 246, 0.05);
|
||
}
|
||
|
||
.mode-sim .modal-input:focus {
|
||
border-color: #f59e0b;
|
||
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.15);
|
||
background: rgba(245, 158, 11, 0.05);
|
||
}
|
||
|
||
select.modal-input {
|
||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%236b7280' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
|
||
background-repeat: no-repeat;
|
||
background-position: calc(100% - 0.75rem) center;
|
||
background-color: rgba(255, 255, 255, 0.04);
|
||
padding-right: 2rem;
|
||
}
|
||
|
||
select.modal-input option {
|
||
background: #0d1117;
|
||
color: white;
|
||
}
|
||
|
||
.modal-h-period {
|
||
display: grid;
|
||
grid-template-columns: 1fr auto 1fr;
|
||
align-items: center;
|
||
gap: 0.5rem;
|
||
}
|
||
|
||
.modal-h-period span {
|
||
text-align: center;
|
||
color: var(--text-dim);
|
||
font-size: 0.85rem;
|
||
}
|
||
|
||
.modal-salary-wrapper {
|
||
display: grid;
|
||
grid-template-columns: auto 1fr;
|
||
align-items: center;
|
||
gap: 0;
|
||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||
border-radius: 10px;
|
||
overflow: hidden;
|
||
background: rgba(255, 255, 255, 0.04);
|
||
}
|
||
|
||
.modal-salary-prefix {
|
||
background: rgba(255, 255, 255, 0.06);
|
||
padding: 0.55rem 0.75rem;
|
||
font-size: 0.75rem;
|
||
color: var(--text-dim);
|
||
font-weight: 700;
|
||
border-right: 1px solid rgba(255, 255, 255, 0.08);
|
||
white-space: nowrap;
|
||
}
|
||
|
||
.modal-salary-input {
|
||
background: transparent;
|
||
border: none;
|
||
padding: 0.55rem 0.9rem;
|
||
color: var(--text-main);
|
||
font-size: 0.9rem;
|
||
font-family: inherit;
|
||
width: 100%;
|
||
}
|
||
|
||
.modal-salary-input:focus {
|
||
outline: none;
|
||
}
|
||
|
||
.modal-salary-wrapper:focus-within {
|
||
border-color: var(--accent-primary);
|
||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
||
}
|
||
|
||
.mode-sim .modal-salary-wrapper:focus-within {
|
||
border-color: #f59e0b;
|
||
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.15);
|
||
}
|
||
|
||
.modal-checkbox-row {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 0.6rem;
|
||
padding: 0.55rem 0.9rem;
|
||
background: rgba(255, 255, 255, 0.04);
|
||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||
border-radius: 10px;
|
||
cursor: pointer;
|
||
transition: background 0.15s;
|
||
}
|
||
|
||
.modal-checkbox-row:hover {
|
||
background: rgba(255, 255, 255, 0.07);
|
||
}
|
||
|
||
.modal-checkbox-row input[type=checkbox] {
|
||
width: 15px;
|
||
height: 15px;
|
||
cursor: pointer;
|
||
accent-color: var(--accent-primary);
|
||
background: transparent;
|
||
border: none;
|
||
}
|
||
|
||
.modal-checkbox-row label {
|
||
font-size: 0.88rem;
|
||
color: var(--text-muted);
|
||
cursor: pointer;
|
||
}
|
||
|
||
.modal-footer {
|
||
display: flex;
|
||
justify-content: flex-end;
|
||
gap: 0.75rem;
|
||
margin-top: 1.75rem;
|
||
padding-top: 1.25rem;
|
||
border-top: 1px solid rgba(255, 255, 255, 0.06);
|
||
}
|
||
|
||
/* --- Simulation Specific --- */
|
||
.sim-overlay {
|
||
position: fixed;
|
||
top: 0.8rem;
|
||
left: 50%;
|
||
transform: translateX(-50%);
|
||
/* Flowing gradient banner */
|
||
background: linear-gradient(90deg, #92400e, #f59e0b, #ef4444, #f97316, #92400e);
|
||
background-size: 300% 100%;
|
||
color: white;
|
||
padding: 0.45rem 2.5rem;
|
||
border-radius: 99px;
|
||
font-weight: 800;
|
||
font-size: 0.82rem;
|
||
letter-spacing: 0.5px;
|
||
pointer-events: none;
|
||
box-shadow: 0 0 30px rgba(245, 158, 11, 0.55), 0 2px 12px rgba(0, 0, 0, 0.4);
|
||
display: none;
|
||
z-index: 1000;
|
||
white-space: nowrap;
|
||
animation: simBarFlow 2.5s linear infinite;
|
||
}
|
||
|
||
.mode-sim .sim-overlay {
|
||
animation: simBarSlideIn 0.4s ease-out forwards, simBarFlow 2.5s linear infinite;
|
||
}
|
||
|
||
/* --- R&D Tag UI --- */
|
||
.rd-search-container {
|
||
position: relative;
|
||
margin-top: 0.5rem;
|
||
}
|
||
|
||
.rd-tag-container {
|
||
display: flex;
|
||
flex-wrap: wrap;
|
||
gap: 0.5rem;
|
||
margin-top: 0.5rem;
|
||
}
|
||
|
||
.currency-wrap {
|
||
display: inline-grid;
|
||
grid-template-columns: var(--symbol-width, 35px) 1fr;
|
||
gap: var(--symbol-gap, 0.5rem);
|
||
font-variant-numeric: tabular-nums;
|
||
text-align: right;
|
||
align-items: baseline;
|
||
}
|
||
|
||
.rd-tag {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
background: rgba(59, 130, 246, 0.1);
|
||
border: 1px solid rgba(59, 130, 246, 0.3);
|
||
color: var(--accent-primary);
|
||
padding: 4px 12px;
|
||
border-radius: 99px;
|
||
font-size: 0.8rem;
|
||
font-weight: 600;
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
.rd-tag:hover {
|
||
background: rgba(59, 130, 246, 0.2);
|
||
border-color: var(--accent-primary);
|
||
}
|
||
|
||
.rd-tag-remove {
|
||
cursor: pointer;
|
||
opacity: 0.6;
|
||
transition: opacity 0.2s;
|
||
font-size: 1.1rem;
|
||
line-height: 1;
|
||
}
|
||
|
||
.rd-tag-remove:hover {
|
||
opacity: 1;
|
||
color: var(--accent-danger);
|
||
}
|
||
|
||
.rd-suggestions {
|
||
position: absolute;
|
||
top: 100%;
|
||
left: 0;
|
||
right: 0;
|
||
background: var(--bg-deep);
|
||
border: 1px solid var(--border-glass);
|
||
border-radius: 12px;
|
||
margin-top: 4px;
|
||
max-height: 200px;
|
||
overflow-y: auto;
|
||
z-index: 1000;
|
||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
|
||
display: none;
|
||
}
|
||
|
||
.rd-suggestion-item {
|
||
padding: 10px 15px;
|
||
cursor: pointer;
|
||
font-size: 0.85rem;
|
||
color: var(--text-muted);
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
.rd-suggestion-item:hover {
|
||
background: rgba(255, 255, 255, 0.05);
|
||
color: var(--text-main);
|
||
}
|
||
|
||
.rd-search-input {
|
||
width: 100%;
|
||
background: rgba(255, 255, 255, 0.03);
|
||
border: 1px solid var(--border-glass);
|
||
border-radius: 99px;
|
||
padding: 10px 20px;
|
||
color: var(--text-main);
|
||
font-size: 0.9rem;
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
.rd-search-input:focus {
|
||
outline: none;
|
||
border-color: var(--accent-primary);
|
||
background: rgba(255, 255, 255, 0.06);
|
||
box-shadow: 0 0 15px rgba(59, 130, 246, 0.1);
|
||
}
|
||
|
||
input[type="number"] {
|
||
background: rgba(255, 255, 255, 0.03);
|
||
border: 1px solid var(--border-glass);
|
||
border-radius: 8px;
|
||
padding: 6px 12px;
|
||
color: var(--text-main);
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
/* --- Hierarchical Org Chart (Tree) --- */
|
||
.org-tree-container {
|
||
display: flex;
|
||
flex-direction: column;
|
||
align-items: center;
|
||
padding: 1rem;
|
||
min-height: 500px;
|
||
width: 100%;
|
||
justify-content: flex-start;
|
||
}
|
||
|
||
.org-root-node {
|
||
background: #b91c1c;
|
||
/* Deep Red for Control Center */
|
||
color: white;
|
||
padding: 0.6rem 2rem;
|
||
border-radius: 8px;
|
||
font-weight: 800;
|
||
font-size: 1rem;
|
||
box-shadow: 0 4px 15px rgba(185, 28, 28, 0.3);
|
||
position: relative;
|
||
z-index: 2;
|
||
margin-bottom: 1.5rem;
|
||
}
|
||
|
||
/* Root to Depts Vertical Line */
|
||
.org-root-node::after {
|
||
content: '';
|
||
position: absolute;
|
||
bottom: -1.5rem;
|
||
left: 50%;
|
||
width: 2px;
|
||
height: 1.5rem;
|
||
background: var(--border-glass);
|
||
}
|
||
|
||
.org-branches-row {
|
||
display: flex;
|
||
gap: 1rem;
|
||
position: relative;
|
||
padding-top: 1rem;
|
||
align-items: flex-start;
|
||
justify-content: center;
|
||
}
|
||
|
||
/* Horizontal Connector Line */
|
||
.org-branches-row::before {
|
||
content: '';
|
||
position: absolute;
|
||
top: 0;
|
||
left: 100px;
|
||
right: 100px;
|
||
height: 2px;
|
||
background: var(--border-glass);
|
||
}
|
||
|
||
.org-dept-branch {
|
||
display: flex;
|
||
flex-direction: column;
|
||
align-items: center;
|
||
position: relative;
|
||
width: 200px;
|
||
}
|
||
|
||
/* Vertical Connector from Horizontal Line to Dept Header */
|
||
.org-dept-branch::before {
|
||
content: '';
|
||
position: absolute;
|
||
top: -1rem;
|
||
left: 50%;
|
||
width: 2px;
|
||
height: 1rem;
|
||
background: var(--border-glass);
|
||
}
|
||
|
||
.org-dept-card {
|
||
width: 100%;
|
||
background: var(--bg-surface);
|
||
border: 1px solid var(--border-glass);
|
||
border-radius: 10px;
|
||
padding: 0.75rem;
|
||
backdrop-filter: blur(20px);
|
||
transition: all 0.3s ease;
|
||
margin-bottom: 1.5rem;
|
||
position: relative;
|
||
z-index: 1;
|
||
}
|
||
|
||
.org-dept-card:hover {
|
||
border-color: var(--accent-primary);
|
||
box-shadow: 0 0 30px rgba(59, 130, 246, 0.1);
|
||
transform: translateY(-3px);
|
||
}
|
||
|
||
.org-dept-header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
border-bottom: 1px solid var(--border-glass);
|
||
padding-bottom: 0.75rem;
|
||
margin-bottom: 1rem;
|
||
}
|
||
|
||
/* Vertical Groups under Dept */
|
||
.org-group-list-vertical {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 0.5rem;
|
||
position: relative;
|
||
}
|
||
|
||
/* Line from Dept Box to Groups */
|
||
.org-dept-card::after {
|
||
content: '';
|
||
position: absolute;
|
||
bottom: -2rem;
|
||
left: 50%;
|
||
width: 2px;
|
||
height: 2rem;
|
||
background: var(--border-glass);
|
||
display: none;
|
||
/* Only show if we want lines BETWEEN group items too */
|
||
}
|
||
|
||
.org-group-item {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
background: rgba(255, 255, 255, 0.03);
|
||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||
padding: 0.5rem 0.75rem;
|
||
border-radius: 6px;
|
||
font-size: 0.8rem;
|
||
transition: all 0.2s;
|
||
width: 100%;
|
||
}
|
||
|
||
.org-group-item:hover {
|
||
background: rgba(255, 255, 255, 0.07);
|
||
border-color: rgba(255, 255, 255, 0.15);
|
||
}
|
||
|
||
.org-add-btn {
|
||
width: 100%;
|
||
margin-top: 0.75rem;
|
||
padding: 0.5rem;
|
||
background: rgba(255, 255, 255, 0.02);
|
||
border: 1px dashed var(--border-glass);
|
||
color: var(--text-dim);
|
||
border-radius: 8px;
|
||
cursor: pointer;
|
||
font-size: 0.8rem;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
gap: 6px;
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
.org-add-btn:hover {
|
||
background: rgba(59, 130, 246, 0.05);
|
||
border-color: var(--accent-primary);
|
||
color: var(--text-main);
|
||
}
|
||
|
||
.status-pill {
|
||
padding: 3px 10px;
|
||
border-radius: 99px;
|
||
font-size: 0.72rem;
|
||
font-weight: 600;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
white-space: nowrap;
|
||
line-height: 1;
|
||
vertical-align: middle;
|
||
}
|
||
|
||
.status-active {
|
||
background: rgba(16, 185, 129, 0.1);
|
||
color: #10b981;
|
||
border: 1px solid rgba(16, 185, 129, 0.2);
|
||
}
|
||
|
||
.status-new {
|
||
background: rgba(59, 130, 246, 0.1);
|
||
color: #3b82f6;
|
||
border: 1px solid rgba(59, 130, 246, 0.2);
|
||
}
|
||
|
||
.status-resign {
|
||
background: rgba(239, 68, 68, 0.1);
|
||
color: #ef4444;
|
||
border: 1px solid rgba(239, 68, 68, 0.2);
|
||
}
|
||
|
||
.status-temp {
|
||
background: rgba(245, 158, 11, 0.1);
|
||
color: #f59e0b;
|
||
border: 1px solid rgba(245, 158, 11, 0.2);
|
||
}
|
||
|
||
input[type="number"]:focus {
|
||
outline: none;
|
||
border-color: var(--accent-primary);
|
||
}
|
||
|
||
/* Local preview identity; this badge does not provide authentication. */
|
||
.auth-user-badge {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 0.5rem;
|
||
padding: 0.5rem 0.75rem;
|
||
background: rgba(59, 130, 246, 0.08);
|
||
border: 1px solid rgba(59, 130, 246, 0.2);
|
||
border-radius: 10px;
|
||
margin-bottom: 0.5rem;
|
||
}
|
||
|
||
.auth-user-badge .user-avatar {
|
||
width: 28px;
|
||
height: 28px;
|
||
border-radius: 50%;
|
||
background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 0.75rem;
|
||
font-weight: 800;
|
||
color: white;
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.auth-user-badge .user-info {
|
||
flex: 1;
|
||
min-width: 0;
|
||
}
|
||
|
||
.auth-user-badge .user-name {
|
||
font-size: 0.82rem;
|
||
font-weight: 700;
|
||
color: var(--text-main);
|
||
white-space: nowrap;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
}
|
||
|
||
.auth-user-badge .user-role {
|
||
font-size: 0.68rem;
|
||
color: var(--text-dim);
|
||
}
|
||
</style>
|
||
</head>
|
||
|
||
<body class="mode-admin">
|
||
<!-- Simulation Mode: persistent top gradient bar (CSS-controlled via .mode-sim) -->
|
||
<div id="sim-mode-topbar"></div>
|
||
<div id="sim-alert" class="sim-overlay">🧪 試算模式中 | 資料不會被儲存,盡情亂改!</div>
|
||
|
||
<div class="app-container">
|
||
<header>
|
||
<div class="logo">
|
||
<img src="2022_Moonshine_Logo_MS_logo_w_EN.png" alt="Moonshine Logo">
|
||
</div>
|
||
|
||
<div class="nav-group sidebar-navigation">
|
||
<div class="nav-item active" id="nav-dashboard" onclick="showView('dashboard')">📊 儀表板</div>
|
||
<div class="nav-item" id="nav-invoice" onclick="showView('invoice')">🧾 年度發票額</div>
|
||
<div class="nav-item" id="nav-personnel" onclick="showHrPersonnelView()">👥 內部人員</div>
|
||
<div class="nav-item" id="nav-contractors" onclick="showPersonnelView('all', 'contractors')">🤝 常態型外包</div>
|
||
<div class="nav-item" id="nav-preview-personnel" onclick="showPersonnelView('all', 'internal', true)">🧮 試算人員(2027)</div>
|
||
<div class="nav-item" id="nav-versions" onclick="showView('versions')">📈 薪資版本與調薪</div>
|
||
|
||
<div class="nav-item" id="nav-org" onclick="showView('org-structure')">🏢 組織架構</div>
|
||
<div class="nav-item" id="nav-params" onclick="showView('params')">⚙️ 核心參數</div>
|
||
<div class="nav-item" id="nav-sales" onclick="showView('sales')">💼 業務管理</div>
|
||
<div class="nav-item" id="nav-artists" onclick="showView('artists')">🎨 藝術家</div>
|
||
<div class="nav-item" id="nav-coda" onclick="showView('coda')">🎯 部門CODA</div>
|
||
<div class="nav-item" id="nav-group" onclick="showView('group')">🏢 組別分析</div>
|
||
</div>
|
||
|
||
<div class="nav-group sidebar-account" style="gap: 0.5rem;">
|
||
<!-- Local preview badge; this is not an authenticated user. -->
|
||
<div id="auth-user-badge" class="auth-user-badge" title="本機預覽,尚未啟用登入或權限控管">
|
||
<div class="user-avatar" id="auth-avatar-initial">?</div>
|
||
<div class="user-info">
|
||
<div class="user-name" id="auth-username-display">未登入</div>
|
||
<div class="user-role" id="auth-role-display">-</div>
|
||
</div>
|
||
</div>
|
||
<form id="company-logout-form" method="post" action="/api/auth/company-logout" style="display:none; margin:0;">
|
||
<button class="btn btn-primary" type="submit" style="width:100%;">登出 MoonShine 公司帳號</button>
|
||
</form>
|
||
<form id="logout-form" method="post" action="/api/auth/logout" style="display:none; margin:0;">
|
||
<button class="btn btn-outline" type="submit" style="width:100%;">只登出本站</button>
|
||
</form>
|
||
<a id="login-link" class="btn btn-outline" href="/api/auth/login">公司帳號登入</a>
|
||
<div id="nav-reset-data" class="btn btn-outline"
|
||
style="text-align: center; color: var(--accent-danger); border-color: rgba(239, 68, 68, 0.3); display:none;"
|
||
onclick="hardReset()">♻️ 重置系統資料</div>
|
||
<div id="mode-toggle" class="btn btn-outline" style="text-align: center; display:none;"
|
||
onclick="toggleMode()">切換至試算模式
|
||
</div>
|
||
<div id="mode-indicator" class="mode-badge">本機預覽模式</div>
|
||
</div>
|
||
</header>
|
||
|
||
<div id="data-source-banner" role="status" style="margin: 0.75rem 1.5rem; padding: 0.65rem 1rem; border: 1px solid rgba(59,130,246,.35); border-radius: 8px; color: var(--text-muted); font-size: .85rem;">
|
||
正在從預覽伺服器載入合成資料…
|
||
</div>
|
||
<main>
|
||
<!-- DASHBOARD VIEW -->
|
||
<div id="dashboard" class="view active">
|
||
<!-- Top Row: Title + Hero Banner -->
|
||
<div class="dashboard-heading">
|
||
<h1 style="margin:0; font-size: 1.3rem; white-space:nowrap;">📊 營運概況 Dashboard</h1>
|
||
<!-- inline hero -->
|
||
<div id="dashboard-invoice-hero"></div>
|
||
</div>
|
||
|
||
<!-- KPI Row -->
|
||
<div class="kpi-grid" id="main-kpis" style="flex-shrink:0;">
|
||
<!-- Dynamic Tiles -->
|
||
</div>
|
||
|
||
<!-- Bottom 3-col grid: fills remaining space -->
|
||
<div class="dashboard-panels">
|
||
<div class="card">
|
||
<h3
|
||
style="margin-bottom: 0.75rem; flex-shrink:0; font-size:0.9rem; text-transform:uppercase; letter-spacing:0.5px; color:var(--text-dim);">
|
||
📈 部門 CODA 成本佔比</h3>
|
||
<div id="dept-bars"
|
||
style="display: flex; flex-direction: column; gap: 0.6rem;">
|
||
<!-- Bars go here -->
|
||
</div>
|
||
</div>
|
||
<div class="card">
|
||
<h3
|
||
style="margin-bottom: 0.75rem; flex-shrink:0; font-size:0.9rem; text-transform:uppercase; letter-spacing:0.5px; color:var(--text-dim);">
|
||
👥 人力分佈</h3>
|
||
<div id="role-stats"></div>
|
||
</div>
|
||
<div class="card">
|
||
<h3
|
||
style="margin-bottom: 0.75rem; flex-shrink:0; font-size:0.9rem; text-transform:uppercase; letter-spacing:0.5px; color:var(--text-dim);">
|
||
🧾 各部門年度發票目標</h3>
|
||
<div id="dept-invoice-targets"></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- INVOICE VIEW -->
|
||
<div id="invoice" class="view">
|
||
</div>
|
||
|
||
<!-- VERSIONS & RAISE VIEW -->
|
||
<div id="versions" class="view">
|
||
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem;">
|
||
<div>
|
||
<h1 style="margin-bottom: 0.5rem;">📈 薪資版本與年度調薪</h1>
|
||
<p style="color: var(--text-dim); font-size: 0.9rem;">管理年度調薪事件,系統會依部門自動結算該年度增額成本。</p>
|
||
<button class="btn btn-outline" style="margin-top:0.5rem; font-size:0.75rem; color:var(--accent-danger); border-color:var(--accent-danger);" onclick="if(confirm('確定要清空所有調薪歷史紀錄嗎?這將修復 undefined 顯示問題。')) { globalParams.raiseEvents = []; saveAndRefresh(); renderVersions(); }">🔧 修復系統:一鍵清除所有異常調薪紀錄</button>
|
||
</div>
|
||
<div style="display: flex; gap: 1rem; align-items: center;">
|
||
<select id="raise-year-filter" class="modal-input" style="padding: 6px 12px; font-size: 1rem; width: auto; font-weight: bold;" onchange="renderVersions()">
|
||
<!-- Generated dynamically -->
|
||
</select>
|
||
<button class="btn btn-primary" onclick="addRaiseEvent()">+ 建立調薪事件</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="raise-kpis">
|
||
<!-- Dynamic Dept Stats injected here -->
|
||
</div>
|
||
|
||
<div class="card">
|
||
<h3 style="margin-bottom: 1.5rem;">📅 年度調薪軌跡 (Raise Events)</h3>
|
||
<div class="table-container">
|
||
<table style="width: 100%;">
|
||
<thead>
|
||
<tr>
|
||
<th>生效日期 (月份)</th>
|
||
<th>事件說明</th>
|
||
<th class="num">受影響人數</th>
|
||
<th>操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="raise-events-table-body">
|
||
<!-- Events injected here -->
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- LIVE HR PERSONNEL IN PM BOARD -->
|
||
<div id="hr-personnel" class="view">
|
||
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem;">
|
||
<div>
|
||
<h1 style="margin-bottom:0.5rem;">👥 內部人員</h1>
|
||
<p style="color:var(--text-muted);">HR 即時在職名冊;部門與組別依 HR 組織層級分類。薪資為目前查詢日的資料。</p>
|
||
</div>
|
||
<button class="btn btn-outline" onclick="loadHrPersonnel(true)">重新讀取 HR</button>
|
||
</div>
|
||
<div id="hr-personnel-status" class="card" role="status">尚未讀取 HR 資料。</div>
|
||
<div class="card" style="margin-bottom:1rem;">
|
||
<div style="display:flex;gap:0.75rem;flex-wrap:wrap;align-items:center;">
|
||
<input id="hr-personnel-search" type="search" placeholder="搜尋工號、姓名或職稱" oninput="filterHrPersonnel()" style="min-width:220px;flex:1;padding:10px 14px;border-radius:8px;border:1px solid var(--border-glass);background:rgba(255,255,255,.04);color:white;">
|
||
<select id="hr-personnel-dept" class="btn btn-outline" onchange="updateHrGroupFilter();filterHrPersonnel()"><option value="">所有部門</option></select>
|
||
<select id="hr-personnel-group" class="btn btn-outline" onchange="filterHrPersonnel()"><option value="">所有組別</option></select>
|
||
</div>
|
||
</div>
|
||
<div class="table-container" style="overflow-x:auto;">
|
||
<table style="width:100%;min-width:900px;">
|
||
<thead><tr><th>工號</th><th>姓名</th><th>部門</th><th>組別</th><th>職稱</th><th>狀態</th><th>薪資</th></tr></thead>
|
||
<tbody id="hr-personnel-body"></tbody>
|
||
</table>
|
||
</div>
|
||
<div id="hr-personnel-pager" style="display:flex;justify-content:flex-end;align-items:center;gap:0.75rem;margin-top:1rem;"></div>
|
||
<p style="color:var(--text-muted);font-size:.85rem;margin-top:1rem;">年度儀表板仍使用合成試算資料;HR 人員的職能及歷史薪資對應完成前,不會將即時薪資當成全年成本。</p>
|
||
</div>
|
||
|
||
<!-- PERSONNEL OVERVIEW (Landing Page) -->
|
||
<div id="personnel-overview" class="view">
|
||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||
<h1>人員概況 - 部門成本分佈</h1>
|
||
<button class="btn btn-primary" onclick="showPersonnelView('all')">查看完整名單</button>
|
||
</div>
|
||
|
||
<div class="card" style="margin-bottom: 2rem;">
|
||
<h3 style="margin-bottom: 1.5rem;">各部門人力預算佔比 (Department Cost % )</h3>
|
||
<div id="dept-cost-stack-chart">
|
||
<!-- Custom Stacked Bar Chart -->
|
||
</div>
|
||
</div>
|
||
|
||
<div class="kpi-grid" id="dept-kpi-grid">
|
||
<!-- Dept Mini Cards -->
|
||
</div>
|
||
</div>
|
||
|
||
<!-- PERSONNEL LIST VIEW -->
|
||
<div id="personnel" class="view">
|
||
<div
|
||
style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1.5rem;">
|
||
<div>
|
||
<h1 id="personnel-view-title" style="margin-bottom: 0.5rem;">人員主表 (全部門)</h1>
|
||
<p id="personnel-source-note" style="color:var(--text-muted); margin-bottom:1rem;"></p>
|
||
<div id="personnel-detail-kpi"
|
||
style="display: flex; gap: 1rem; align-items: center; margin-top: 0.5rem;">
|
||
<!-- KPI cards will be injected here by JS -->
|
||
</div>
|
||
</div>
|
||
<div style="display: flex; gap: 0.75rem; align-items: center;">
|
||
<div class="card"
|
||
style="margin-bottom: 0; display: flex; gap: 1rem; align-items: center; background: rgba(0,0,0,0.2); border-color: rgba(255,255,255,0.05); padding: 0.5rem 1rem;">
|
||
<div style="flex-grow: 1;">
|
||
<input type="text" id="personnel-search" placeholder="搜尋姓名、職稱..."
|
||
style="width: 100%; padding: 10px 16px; border-radius: 99px; border: 1px solid var(--border-glass); background: rgba(255,255,255,0.03); color: white;"
|
||
onkeyup="renderPersonnel()">
|
||
</div>
|
||
<select id="personnel-company-filter" class="btn btn-outline"
|
||
onchange="updateDeptFilter(); updateGroupFilter(); renderPersonnel()"
|
||
style="min-width: 130px; cursor: pointer;">
|
||
<option value="all">所有公司</option>
|
||
</select>
|
||
<select id="personnel-dept-filter" class="btn btn-outline"
|
||
onchange="updateGroupFilter(); renderPersonnel()"
|
||
style="min-width: 130px; cursor: pointer;">
|
||
<option value="all">所有部門</option>
|
||
</select>
|
||
<select id="personnel-group-filter" class="btn btn-outline" onchange="renderPersonnel()"
|
||
style="min-width: 130px; cursor: pointer;">
|
||
<option value="all">所有組別</option>
|
||
</select>
|
||
</div>
|
||
<button class="btn btn-outline" onclick="exportToExcel()" style="border-color: var(--accent-success); color: var(--accent-success); margin-right: 5px;">📊 匯出此類名單</button>
|
||
<button class="btn btn-outline" onclick="importFromExcel()" style="border-color: var(--accent-warning); color: var(--accent-warning);">📥 匯入此類名單</button>
|
||
<input type="file" id="import-excel-input" style="display:none;" accept=".csv, .xlsx, .xls" onchange="handleImportFile(event)">
|
||
<button class="btn btn-outline" onclick="copyDataForSync()" style="font-size:0.75rem; color:var(--text-dim); margin-left: 5px;">📋 複製 JSON 狀態</button>
|
||
<button id="personnel-add-button" class="btn btn-primary" onclick="addPerson()">+ 新增內部人員</button>
|
||
</div>
|
||
</div>
|
||
<div class="table-container">
|
||
<table id="person-table">
|
||
<thead>
|
||
<tr>
|
||
<th class="sortable" onclick="toggleSort('company')">公司 <span id="sort-company"
|
||
class="sort-icon"></span></th>
|
||
<th class="sortable" onclick="toggleSort('name')">姓名 <span id="sort-name"
|
||
class="sort-icon"></span></th>
|
||
<th class="sortable" onclick="toggleSort('title')">職稱 <span id="sort-title"
|
||
class="sort-icon"></span></th>
|
||
<th class="sortable" onclick="toggleSort('dept')">部門 <span id="sort-dept"
|
||
class="sort-icon"></span></th>
|
||
<th class="sortable" onclick="toggleSort('group')">組別 <span id="sort-group"
|
||
class="sort-icon"></span></th>
|
||
<th class="sortable" onclick="toggleSort('role')">職能 <span id="sort-role"
|
||
class="sort-icon"></span></th>
|
||
<th class="sortable" onclick="toggleSort('isManager')">管理職 <span id="sort-isManager"
|
||
class="sort-icon"></span></th>
|
||
<th class="sortable num" onclick="toggleSort('salary')">月/時薪 <span id="sort-salary"
|
||
class="sort-icon"></span></th>
|
||
<th class="num">每週天數</th>
|
||
<th class="num">H1 起</th>
|
||
<th class="num">H1 迄</th>
|
||
<th class="num">H2 起</th>
|
||
<th class="num">H2 迄</th>
|
||
<th>狀態</th>
|
||
<th class="sortable num" onclick="toggleSort('totalCost')">個人總成本 <span
|
||
id="sort-totalCost" class="sort-icon"></span></th>
|
||
<th>操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody></tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- SALES VIEW -->
|
||
<div id="sales" class="view">
|
||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||
<h1>業務管理 - 全體 P 系列預算</h1>
|
||
<div class="card" style="padding: 1rem 2rem;">
|
||
<div class="card-label">P 年度薪資承擔額(依管理/PC比例)</div>
|
||
<div class="card-value" id="sales-grand-total">NT$ 0</div>
|
||
</div>
|
||
</div>
|
||
<div id="sales-content">
|
||
<!-- Dept Tables -->
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ARTISTS VIEW -->
|
||
<div id="artists" class="view">
|
||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||
<h1>藝術家 (四大製作部)</h1>
|
||
<div class="card" style="padding: 1rem 2rem;">
|
||
<div class="card-label">製作部門藝術家成本(含支援分攤)</div>
|
||
<div class="card-value" id="artists-grand-total">NT$ 0</div>
|
||
</div>
|
||
</div>
|
||
<div id="artists-content">
|
||
<!-- Dept Tables -->
|
||
</div>
|
||
</div>
|
||
|
||
<!-- PARAMETERS VIEW -->
|
||
<div id="params" class="view">
|
||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||
<div>
|
||
<h1 style="margin-bottom: 0.5rem;">⚙️ 系統核心參數設定</h1>
|
||
<p style="color: var(--text-muted); font-size: 0.9rem;">調整全公司營運基準、倍率、以及各項自動計算參數。變動將立即影響所有視圖。</p>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="global-params"
|
||
style="display: grid; grid-template-columns: minmax(320px, 1fr) minmax(360px, 1.2fr) minmax(320px, 1fr); gap: 1.5rem; align-items: start;">
|
||
<!-- Cards will be injected here -->
|
||
</div>
|
||
</div>
|
||
|
||
<!-- CODA VIEW -->
|
||
<div id="coda" class="view">
|
||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||
<div>
|
||
<h1>部門 CODA 總覽</h1>
|
||
<p style="color: var(--text-muted); font-size: 0.9rem; margin-top: 0.5rem;">P 系列預算 + A/O
|
||
藝術家預算(含製程部分攤)= 各部門最終 CODA</p>
|
||
</div>
|
||
<div class="card" style="padding: 1rem 2rem;">
|
||
<div class="card-label">全公司總 CODA</div>
|
||
<div class="card-value" id="coda-grand-total">NT$ 0</div>
|
||
</div>
|
||
</div>
|
||
<div id="coda-content">
|
||
<!-- Dept CODA Cards -->
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ORG STRUCTURE VIEW -->
|
||
<div id="org-structure" class="view">
|
||
<div id="org-structure-content">
|
||
<!-- Dynamic Org Chart -->
|
||
</div>
|
||
</div>
|
||
|
||
<!-- GROUP ANALYTICS VIEW -->
|
||
<div id="group" class="view">
|
||
<h1>小組影響力分析</h1>
|
||
<div class="table-container" style="margin-top: 2rem;">
|
||
<table id="group-table">
|
||
<thead>
|
||
<tr>
|
||
<th>部門</th>
|
||
<th>組別</th>
|
||
<th>小組總人數</th>
|
||
<th>小組總成本</th>
|
||
<th>佔部門原始成本(含外包)</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody></tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- VERSIONS VIEW (Batch Raise Events & Snapshots) -->
|
||
<div id="versions" class="view">
|
||
<div
|
||
style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem;">
|
||
<div>
|
||
<h1 style="margin-bottom: 0.5rem;">📈 薪資版本與調薪控制</h1>
|
||
<p style="color: var(--text-muted); font-size: 0.9rem;">建立批次調薪事件,系統將自動於指定月份後採用新薪資疊加計算全年度成本。</p>
|
||
</div>
|
||
<div>
|
||
<button class="btn btn-primary" onclick="openCreateRaiseEventModal()">+ 新增調薪批次</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="table-container" style="margin-bottom: 3rem;">
|
||
<table id="raise-events-table">
|
||
<thead>
|
||
<tr>
|
||
<th>批次名稱</th>
|
||
<th>建立時間</th>
|
||
<th>受影響人數</th>
|
||
<th>操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<!-- Filled by JS -->
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div
|
||
style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem; padding-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05);">
|
||
<div>
|
||
<h2 style="margin-bottom: 0.5rem; font-size: 1.25rem;">📁 歷史快照管理</h2>
|
||
<p style="color: var(--text-muted); font-size: 0.9rem;">保存當下之所有系統狀態(含人員名單與薪資等),以便未來讀取與比對。</p>
|
||
</div>
|
||
<div>
|
||
<button class="btn btn-outline"
|
||
style="border-color: rgba(59, 130, 246, 0.4); color: var(--accent-primary);"
|
||
onclick="createSnapshot()">+ 存為即時快照</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="table-container">
|
||
<table id="snapshots-table">
|
||
<thead>
|
||
<tr>
|
||
<th>快照名稱</th>
|
||
<th>保存時間</th>
|
||
<th>操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<!-- Filled by JS -->
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
|
||
</main>
|
||
</div>
|
||
|
||
<script>
|
||
// --- CONFIGURATION LAYER ---
|
||
window.IS_PUBLIC_VERSION = false;
|
||
let personnelCategory = 'internal';
|
||
function matchesPersonnelCategory(person, category = personnelCategory) {
|
||
const isContractor = (person.role || '').startsWith('O');
|
||
return category === 'contractors' ? isContractor : !isContractor;
|
||
}
|
||
function copyDataForSync() {
|
||
// FULL STATE EXPORT: Everything the AI needs to replicate the current browser state exactly.
|
||
const fullState = {
|
||
baseData: baseData,
|
||
globalParams: globalParams,
|
||
snapshots: snapshots
|
||
};
|
||
const dataStr = JSON.stringify(fullState, null, 2);
|
||
navigator.clipboard.writeText(dataStr).then(() => {
|
||
alert('✅ 全系統狀態已複製到剪貼簿!(包含人員、調薪事件、快照與參數)\n\n請將這串內容貼回給 AI (Antigravity),我會處理後續的「完整連動產出」。');
|
||
}).catch(err => {
|
||
console.log(fullState);
|
||
alert('複製失敗,內容已輸出至 Console,請手動複製 console 內顯示的物件內容。');
|
||
});
|
||
}
|
||
|
||
function exportToExcel() {
|
||
// Generate CSV content from baseData
|
||
const headers = ['姓名', '職稱', '部門', '組別', '職能(Role)', '月薪', '日薪', 'H1開始', 'H1結束', 'H2開始', 'H2結束', '工作率', '年度總成本', '實領薪資總計'];
|
||
const rows = (isSimMode ? simData : baseData).filter(p => matchesPersonnelCategory(p)).map(p => {
|
||
return [
|
||
p.name || '',
|
||
p.title || '',
|
||
p.dept || '',
|
||
p.group || '',
|
||
p.role || '',
|
||
p.salary || 0,
|
||
p.dayrate || 0,
|
||
p.h1Start || '',
|
||
p.h1End || '',
|
||
p.h2Start || '',
|
||
p.h2End || '',
|
||
p.workRateUsed || 1,
|
||
Math.round(p.totalCost || 0),
|
||
Math.round(p.realSalaryTotal || 0)
|
||
];
|
||
});
|
||
|
||
// Convert to CSV string with BOM for Excel UTF-8 support
|
||
let csvContent = "\uFEFF";
|
||
csvContent += headers.join(",") + "\n";
|
||
rows.forEach(row => {
|
||
csvContent += row.map(cell => {
|
||
const str = String(cell).replace(/"/g, '""');
|
||
return `"${str}"`;
|
||
}).join(",") + "\n";
|
||
});
|
||
|
||
// Create download link
|
||
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
||
const url = URL.createObjectURL(blob);
|
||
const link = document.createElement("a");
|
||
const date = new Date().toISOString().split('T')[0];
|
||
link.setAttribute("href", url);
|
||
link.setAttribute("download", `Studio_Personnel_Export_${date}.csv`);
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
document.body.removeChild(link);
|
||
}
|
||
|
||
function importFromExcel() {
|
||
document.getElementById('import-excel-input').click();
|
||
}
|
||
|
||
let pendingImportData = null;
|
||
let pendingImportCategory = 'internal';
|
||
let pendingImportSimulation = false;
|
||
|
||
function handleImportFile(event) {
|
||
const file = event.target.files[0];
|
||
if (!file) return;
|
||
const importCategory = personnelCategory;
|
||
const importSimulation = isSimMode;
|
||
|
||
const reader = new FileReader();
|
||
reader.onload = function(e) {
|
||
const buffer = e.target.result;
|
||
const fileName = file.name.toLowerCase();
|
||
|
||
let importedData = [];
|
||
const map = {
|
||
'姓名': 'name', 'Name': 'name',
|
||
'職稱': 'title', 'Title': 'title',
|
||
'部門': 'dept', 'Dept': 'dept', 'Department': 'dept',
|
||
'組別': 'group', 'Group': 'group',
|
||
'職能(Role)': 'role', 'Role': 'role',
|
||
'月薪': 'salary', 'Salary': 'salary', 'Monthly Salary': 'salary',
|
||
'日薪': 'dayrate', 'Dayrate': 'dayrate', 'Daily Rate': 'dayrate',
|
||
'H1開始': 'h1Start', 'H1開始月': 'h1Start',
|
||
'H1結束': 'h1End', 'H1結束月': 'h1End',
|
||
'H2開始': 'h2Start', 'H2開始月': 'h2Start',
|
||
'H2結束': 'h2End', 'H2結束月': 'h2End',
|
||
'工作率': 'workRateUsed', 'Work Rate': 'workRateUsed', '工作率(Work Rate)': 'workRateUsed'
|
||
};
|
||
|
||
if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) {
|
||
try {
|
||
const data = new Uint8Array(buffer);
|
||
const workbook = XLSX.read(data, { type: 'array' });
|
||
const firstSheetName = workbook.SheetNames[0];
|
||
const worksheet = workbook.Sheets[firstSheetName];
|
||
const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
|
||
|
||
if (json.length < 1) throw new Error("Empty sheet");
|
||
|
||
const headers = json[0].map(h => String(h || '').trim());
|
||
const columnIndices = {};
|
||
headers.forEach((h, idx) => {
|
||
const match = Object.keys(map).find(k => k.toLowerCase() === h.toLowerCase());
|
||
if (match) columnIndices[map[match]] = idx;
|
||
});
|
||
|
||
if (columnIndices['name'] === undefined) {
|
||
alert('❌ 無法在 Excel 標頭中找到「姓名」或 "Name" 欄位。');
|
||
return;
|
||
}
|
||
|
||
for (let i = 1; i < json.length; i++) {
|
||
const row = json[i];
|
||
if (!row || row.length === 0) continue;
|
||
const p = {};
|
||
Object.values(map).forEach(prop => {
|
||
const idx = columnIndices[prop];
|
||
if (idx !== undefined && row[idx] !== undefined) {
|
||
let val = row[idx];
|
||
if (['salary', 'dayrate', 'workRateUsed'].includes(prop)) {
|
||
p[prop] = parseFloat(String(val).replace(/,/g, '')) || 0;
|
||
} else {
|
||
p[prop] = String(val).trim();
|
||
}
|
||
}
|
||
});
|
||
if (p.name) importedData.push(p);
|
||
}
|
||
} catch (err) {
|
||
alert('❌ Excel 解析失敗:' + err.message);
|
||
return;
|
||
}
|
||
} else {
|
||
function tryDecode(encoding) {
|
||
try {
|
||
const decoder = new TextDecoder(encoding);
|
||
const text = decoder.decode(buffer);
|
||
const rawLines = text.split(/\r?\n/).filter(line => line.trim() !== '');
|
||
if (rawLines.length < 1) return null;
|
||
|
||
const firstLine = rawLines[0].replace("\uFEFF", "");
|
||
const commaCount = (firstLine.match(/,/g) || []).length;
|
||
const semiCount = (firstLine.match(/;/g) || []).length;
|
||
const tabCount = (firstLine.match(/\t/g) || []).length;
|
||
|
||
let delimiter = ',';
|
||
if (semiCount > commaCount && semiCount > tabCount) delimiter = ';';
|
||
else if (tabCount > commaCount && tabCount > semiCount) delimiter = '\t';
|
||
|
||
const splitRow = (line) => {
|
||
const parts = [];
|
||
let current = '';
|
||
let inQuotes = false;
|
||
for (let i = 0; i < line.length; i++) {
|
||
const char = line[i];
|
||
if (char === '"') {
|
||
if (inQuotes && line[i+1] === '"') { current += '"'; i++; }
|
||
else inQuotes = !inQuotes;
|
||
} else if (char === delimiter && !inQuotes) {
|
||
parts.push(current.trim());
|
||
current = '';
|
||
} else current += char;
|
||
}
|
||
parts.push(current.trim());
|
||
return parts.map(p => p.replace(/^"|"$/g, '').replace(/""/g, '"'));
|
||
};
|
||
|
||
const headers = splitRow(firstLine);
|
||
return { text, rawLines, headers, delimiter, splitRow };
|
||
} catch(e) { return null; }
|
||
}
|
||
|
||
let result = tryDecode('utf-8');
|
||
let foundName = result && result.headers.some(h => h === '姓名' || h.toLowerCase() === 'name');
|
||
if (!foundName) {
|
||
const big5Result = tryDecode('big5');
|
||
if (big5Result && big5Result.headers.some(h => h === '姓名' || h.toLowerCase() === 'name')) {
|
||
result = big5Result;
|
||
}
|
||
}
|
||
|
||
if (!result || result.rawLines.length < 2) {
|
||
alert('❌ 檔案內容格式不正確或編碼不支援。');
|
||
return;
|
||
}
|
||
|
||
const { rawLines, headers, splitRow } = result;
|
||
const columnIndices = {};
|
||
headers.forEach((h, idx) => {
|
||
const match = Object.keys(map).find(k => k.toLowerCase() === h.toLowerCase());
|
||
if (match) columnIndices[map[match]] = idx;
|
||
});
|
||
|
||
if (columnIndices['name'] === undefined) {
|
||
alert('❌ 無法在 CSV 標頭中找到「姓名」或 "Name" 欄位。');
|
||
return;
|
||
}
|
||
|
||
for (let i = 1; i < rawLines.length; i++) {
|
||
const cells = splitRow(rawLines[i]);
|
||
if (cells.length < 1) continue;
|
||
const p = {};
|
||
Object.values(map).forEach(prop => {
|
||
const idx = columnIndices[prop];
|
||
if (idx !== undefined && cells[idx] !== undefined) {
|
||
let val = cells[idx];
|
||
if (['salary', 'dayrate', 'workRateUsed'].includes(prop)) {
|
||
p[prop] = parseFloat(String(val).replace(/,/g, '')) || 0;
|
||
} else {
|
||
p[prop] = val;
|
||
}
|
||
}
|
||
});
|
||
if (p.name) importedData.push(p);
|
||
}
|
||
}
|
||
|
||
if (importedData.length === 0) {
|
||
alert('❌ 無法從檔案中提取任何有效資料。');
|
||
return;
|
||
}
|
||
|
||
const report = { duplicates: [], updates: [], additions: [], removals: [] };
|
||
const existingMap = new Map();
|
||
if (importedData.some(p => !p.role || !matchesPersonnelCategory(p, importCategory))) {
|
||
alert('請確認職能欄位:內部人員與常態型外包須分別在各自頁面匯入。此次未修改資料。');
|
||
event.target.value = '';
|
||
return;
|
||
}
|
||
(importSimulation ? simData : baseData).filter(p => matchesPersonnelCategory(p, importCategory)).forEach(p => existingMap.set(p.name.trim(), p));
|
||
|
||
const finalImportList = [];
|
||
const importedNamesSet = new Set();
|
||
|
||
importedData.forEach(p => {
|
||
const nameKey = p.name.trim();
|
||
if (importedNamesSet.has(nameKey)) {
|
||
report.duplicates.push(nameKey);
|
||
return;
|
||
}
|
||
importedNamesSet.add(nameKey);
|
||
|
||
const existing = existingMap.get(nameKey);
|
||
if (existing) {
|
||
const merged = { ...existing, ...p };
|
||
const diffs = [];
|
||
['title', 'dept', 'group', 'role', 'salary', 'dayrate', 'h1Start', 'h1End', 'h2Start', 'h2End', 'workRateUsed'].forEach(f => {
|
||
if (String(p[f] || '') !== String(existing[f] || '')) {
|
||
diffs.push({ field: f, old: existing[f], new: p[f] });
|
||
}
|
||
});
|
||
if (diffs.length > 0) report.updates.push({ name: nameKey, diffs });
|
||
finalImportList.push(merged);
|
||
existingMap.delete(nameKey);
|
||
} else {
|
||
report.additions.push(nameKey);
|
||
finalImportList.push(p);
|
||
}
|
||
});
|
||
report.removals = Array.from(existingMap.keys());
|
||
|
||
pendingImportData = finalImportList;
|
||
pendingImportCategory = importCategory;
|
||
pendingImportSimulation = importSimulation;
|
||
showImportReview(report);
|
||
event.target.value = '';
|
||
};
|
||
reader.readAsArrayBuffer(file);
|
||
}
|
||
|
||
function showImportReview(report) {
|
||
const modal = document.getElementById('import-review-modal');
|
||
const summary = document.getElementById('import-summary');
|
||
const details = document.getElementById('import-details');
|
||
|
||
summary.innerHTML = `
|
||
<div style="display:grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 1.5rem;">
|
||
<div class="card" style="margin:0; text-align:center; padding: 10px; border-color: var(--accent-warning);"><div style="font-size:0.7rem; color:var(--text-dim);">重複姓名</div><div style="font-size:1.2rem; font-weight:800; color:var(--accent-warning);">${report.duplicates.length}</div></div>
|
||
<div class="card" style="margin:0; text-align:center; padding: 10px; border-color: var(--accent-primary);"><div style="font-size:0.7rem; color:var(--text-dim);">內容變動</div><div style="font-size:1.2rem; font-weight:800; color:var(--accent-primary);">${report.updates.length}</div></div>
|
||
<div class="card" style="margin:0; text-align:center; padding: 10px; border-color: var(--accent-success);"><div style="font-size:0.7rem; color:var(--text-dim);">新增人員</div><div style="font-size:1.2rem; font-weight:800; color:var(--accent-success);">${report.additions.length}</div></div>
|
||
<div class="card" style="margin:0; text-align:center; padding: 10px; border-color: var(--accent-danger);"><div style="font-size:0.7rem; color:var(--text-dim);">即將移除</div><div style="font-size:1.2rem; font-weight:800; color:var(--accent-danger);">${report.removals.length}</div></div>
|
||
</div>
|
||
`;
|
||
|
||
let html = '<div style="max-height: 400px; overflow-y: auto; font-size: 0.85rem;">';
|
||
|
||
if (report.duplicates.length > 0) {
|
||
html += `<div style="margin-bottom:1rem; padding:10px; background:rgba(245,158,11,0.05); border:1px solid rgba(245,158,11,0.2); border-radius:8px;">
|
||
<strong style="color:var(--accent-warning);">⚠️ CSV 內重複姓名 (請手動檢查檔案):</strong><br>${report.duplicates.join(', ')}
|
||
</div>`;
|
||
}
|
||
|
||
if (report.updates.length > 0) {
|
||
html += `<h3>🔄 資料細節差異 (Different Details):</h3><table style="width:100%; border-collapse:collapse; margin-top:8px;">`;
|
||
report.updates.forEach(u => {
|
||
html += `<tr><td colspan="3" style="padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.05); font-weight:700; color:var(--accent-primary);">${u.name}</td></tr>`;
|
||
u.diffs.forEach(d => {
|
||
html += `<tr style="font-size:0.75rem;"><td style="width:100px; color:var(--text-dim); padding-left:15px;">${d.field}</td><td style="color:var(--text-muted); text-decoration:line-through; opacity:0.6;">${d.old}</td><td style="color:var(--accent-success); font-weight:600;">➔ ${d.new}</td></tr>`;
|
||
});
|
||
});
|
||
html += `</table>`;
|
||
}
|
||
|
||
if (report.additions.length > 0) {
|
||
html += `<h3 style="margin-top:1.5rem; color:var(--accent-success);">➕ 新增人員 (New Additions):</h3><div style="color:var(--text-muted); padding:5px 0;">${report.additions.join(', ')}</div>`;
|
||
}
|
||
|
||
if (report.removals.length > 0) {
|
||
html += `<h3 style="margin-top:1.5rem; color:var(--accent-danger);">🗑️ 即將被移除的人員 (Existing but not in CSV):</h3><div style="color:var(--text-muted); padding:5px 0; opacity:0.6;">${report.removals.join(', ')}</div>`;
|
||
}
|
||
|
||
html += '</div>';
|
||
details.innerHTML = html;
|
||
modal.style.display = 'flex';
|
||
}
|
||
|
||
function confirmImport() {
|
||
if (pendingImportData) {
|
||
const previous = pendingImportSimulation ? simData : baseData;
|
||
let maxRow = -1;
|
||
previous.forEach(p => { if (p.row !== undefined && p.row > maxRow) maxRow = p.row; });
|
||
|
||
const finalData = pendingImportData.map(p => {
|
||
if (p.row === undefined) {
|
||
maxRow++;
|
||
return { ...p, row: maxRow, id: Date.now() + Math.random() };
|
||
}
|
||
return p;
|
||
});
|
||
|
||
const combined = previous.filter(p => !matchesPersonnelCategory(p, pendingImportCategory)).concat(finalData);
|
||
if (pendingImportSimulation) simData = combined;
|
||
else baseData = combined;
|
||
saveAndRefresh();
|
||
closeImportReview();
|
||
alert('✅ 人員資料匯入暨同步完成,已自動連結現有調薪歷史。');
|
||
}
|
||
}
|
||
|
||
function closeImportReview() {
|
||
document.getElementById('import-review-modal').style.display = 'none';
|
||
pendingImportData = null;
|
||
}
|
||
|
||
// --- DATA LAYER ---
|
||
let baseData = []; // Loaded from the server API
|
||
let simData = []; // Current simulation data
|
||
let previewParamsBeforeSimulation = null;
|
||
let isSimMode = false;
|
||
window.IS_PUBLIC_DEPLOY = true; // Security Lock Enabled
|
||
|
||
function formatPct(val) {
|
||
if (isNaN(val) || val === 0) return "0.00";
|
||
return (Math.ceil(val * 100) / 100).toFixed(2);
|
||
}
|
||
|
||
|
||
let globalParams = {}; // Loaded from the server API
|
||
|
||
// --- INIT ORG STRUCTURE ---
|
||
function initOrgStructure() {
|
||
if (!globalParams.orgStructure) {
|
||
globalParams.orgStructure = {};
|
||
|
||
// 1. Enforce specific department order first
|
||
const predefinedOrder = ['前製部', '廣告部', '視效部', '動畫部'];
|
||
predefinedOrder.forEach(d => { globalParams.orgStructure[d] = []; });
|
||
|
||
// 2. Populate groups from data
|
||
baseData.forEach(p => {
|
||
const dept = (p.dept || '').trim();
|
||
if (dept === (globalParams.pcDept || '').trim()) return;
|
||
if (!dept) return;
|
||
|
||
if (!globalParams.orgStructure[dept]) {
|
||
globalParams.orgStructure[dept] = [];
|
||
}
|
||
const group = (p.group || '').trim() || '未分組';
|
||
if (!globalParams.orgStructure[dept].includes(group)) {
|
||
globalParams.orgStructure[dept].push(group);
|
||
}
|
||
});
|
||
|
||
// 3. Remove functionally empty predefined departments if they have no people (optional safety)
|
||
Object.keys(globalParams.orgStructure).forEach(d => {
|
||
if (globalParams.orgStructure[d].length === 0 && predefinedOrder.includes(d)) {
|
||
// We keep it to maintain the visible structure even if empty in the model,
|
||
// but normally we might delete it. For now, leave it to keep the 4 pillars.
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
let currentDeptFilter = 'all';
|
||
let currentGroupFilter = 'all';
|
||
let sortConfig = { field: 'dept', direction: 'asc' };
|
||
|
||
// --- CALCULATION ENGINE ---
|
||
function isCalculationRole(role) {
|
||
return /^(P|A|O)\s*-/.test(String(role || ''));
|
||
}
|
||
|
||
function weekdaysInMonth(year, month) {
|
||
let count = 0;
|
||
const date = new Date(Date.UTC(year, month - 1, 1));
|
||
while (date.getUTCMonth() === month - 1) {
|
||
const weekday = date.getUTCDay();
|
||
if (weekday >= 1 && weekday <= 5) count++;
|
||
date.setUTCDate(date.getUTCDate() + 1);
|
||
}
|
||
return count;
|
||
}
|
||
|
||
function hourlyMonthlyAmount(person, month, hourlyRate) {
|
||
const year = Number(globalParams.reportYear || 2027);
|
||
const weeklyDays = Math.min(5, Math.max(1, Number(person.weeklyWorkDays) || 5));
|
||
return weekdaysInMonth(year, month) * 8 * (Number(hourlyRate) || 0) * (weeklyDays / 5);
|
||
}
|
||
|
||
function calculateAll(data) {
|
||
// 1. Data Migration & Cost Reset
|
||
data.forEach((p, idx) => {
|
||
// Critical: Normalize all metadata immediately to ensure consistent mapping
|
||
if (p.dept) p.dept = p.dept.trim();
|
||
if (p.name) p.name = p.name.trim();
|
||
if (p.group) p.group = p.group.trim();
|
||
|
||
// Migrate old format if necessary
|
||
if (p.start !== undefined && p.h1Start === undefined) {
|
||
const s = parseInt(p.start);
|
||
const e = parseInt(p.end);
|
||
p.h1Start = s <= 6 ? s : "";
|
||
p.h1End = s <= 6 ? Math.min(e, 6) : "";
|
||
p.h2Start = e >= 7 ? Math.max(s, 7) : "";
|
||
p.h2End = e >= 7 ? e : "";
|
||
delete p.start;
|
||
delete p.end;
|
||
}
|
||
|
||
const isOutsource = p.role && p.role.startsWith('O');
|
||
|
||
// HR people remain visible while their P/A classification is waiting for manual review.
|
||
// They must not silently alter CODA or company totals before that review is complete.
|
||
if (p.source === 'hr-sync' && !p.calculationReady) {
|
||
p.realSalaryTotal = 0;
|
||
p.totalCost = 0;
|
||
if (p.row === undefined) p.row = idx;
|
||
return;
|
||
}
|
||
|
||
// NEW: If we are in PUBLIC VERSION and totalCost is already baked, skip expensive calculation
|
||
if (window.IS_PUBLIC_VERSION && p.totalCost !== undefined) {
|
||
p.workRateUsed = p.workRateUsed !== undefined ? p.workRateUsed : (isOutsource ? 1.5 : 1.0);
|
||
// Critical: Ensure row index is assigned if missing even in Public version
|
||
if (p.row === undefined) p.row = idx;
|
||
return;
|
||
}
|
||
|
||
// Critical: Ensure row index is assigned to match Raise Events
|
||
if (p.row === undefined) p.row = idx;
|
||
|
||
// Pre-compute applicable raises for this person from globalParams.raiseEvents
|
||
// Sort by createdAt to ensure chronological overrides
|
||
const raises = (globalParams.raiseEvents || []).slice().sort((a, b) => a.createdAt - b.createdAt);
|
||
|
||
// M & N: Month-by-Month Accumulation
|
||
let accumulatedRealSalary = 0;
|
||
let accumulatedTotalCost = 0;
|
||
|
||
if (p.workRateUsed === undefined || p.workRateUsed === null || p.workRateUsed === "") {
|
||
p.workRateUsed = isOutsource ? 1.5 : 1.0;
|
||
}
|
||
const workRate = parseFloat(p.workRateUsed) || (isOutsource ? 1.5 : 1.0);
|
||
const opMult = isOutsource ? 1.0 : globalParams.opMultiplier;
|
||
const baseSalary = isOutsource ? (parseFloat(p.dayrate) || 0) * globalParams.workingDays : (parseFloat(p.salary) || 0);
|
||
const baseHourlyRate = parseFloat(p.hourlyRate) || 0;
|
||
|
||
for (let m = 1; m <= 12; m++) {
|
||
// Check if person is active in this month
|
||
const inH1 = (p.h1Start && p.h1End && m >= parseInt(p.h1Start) && m <= parseInt(p.h1End));
|
||
const inH2 = (p.h2Start && p.h2End && m >= parseInt(p.h2Start) && m <= parseInt(p.h2End));
|
||
|
||
if (inH1 || inH2) {
|
||
// Determine applicable monthly salary. Start with base.
|
||
let currentMonthSalary = p.salaryType === 'hourly'
|
||
? hourlyMonthlyAmount(p, m, baseHourlyRate)
|
||
: baseSalary;
|
||
|
||
// Apply overrides from raise events
|
||
raises.forEach(evt => {
|
||
if (evt.adjustments) {
|
||
const adj = evt.adjustments.find(a => a.personIdx === p.row);
|
||
const reportYear = Number(globalParams.reportYear || new Date().getFullYear());
|
||
const effectiveYear = Number(adj?.startYear || reportYear);
|
||
if (adj && (effectiveYear < reportYear || (effectiveYear === reportYear && m >= adj.startMonth))) {
|
||
const changedRate = parseFloat(adj.newSalary) || 0;
|
||
currentMonthSalary = isOutsource ? changedRate * globalParams.workingDays
|
||
: p.salaryType === 'hourly' ? hourlyMonthlyAmount(p, m, changedRate)
|
||
: changedRate;
|
||
}
|
||
}
|
||
});
|
||
|
||
accumulatedRealSalary += currentMonthSalary;
|
||
// APPLICATION OF ROLE-SPECIFIC UTILIZATION: Efficiency penalty (divisor) only for in-house staff
|
||
const utilP = globalParams.utilizationP || globalParams.utilization || 1.0;
|
||
const utilA = globalParams.utilizationA || globalParams.utilization || 1.0;
|
||
let util = 1.0;
|
||
if (!isOutsource) {
|
||
util = (p.role && p.role.startsWith('P')) ? utilP : utilA;
|
||
}
|
||
accumulatedTotalCost += (currentMonthSalary * opMult * workRate) / util;
|
||
}
|
||
}
|
||
|
||
p.realSalaryTotal = accumulatedRealSalary;
|
||
p.totalCost = accumulatedTotalCost;
|
||
});
|
||
|
||
// 2. Dept Raw Totals (DT)
|
||
// Use orgStructure to define valid active departments
|
||
initOrgStructure();
|
||
const depts = [...Object.keys(globalParams.orgStructure), globalParams.pcDept]; // Include Support Dept for calculations
|
||
const deptStats = {};
|
||
|
||
depts.forEach(d => {
|
||
const cleanD = (d || '').trim();
|
||
const pInDept = data.filter(p => (p.dept || '').trim() === cleanD);
|
||
// PARADIGM SHIFT: Exclude 'O - 外包' completely from rawDt and dt calculation for CODA purposes
|
||
const rawDt = pInDept.filter(p => isCalculationRole(p.role) && !p.role.startsWith('O')).reduce((acc, p) => acc + (p.totalCost || 0), 0);
|
||
const rawArtistCost = pInDept.filter(p => p.role && p.role.startsWith('A')).reduce((acc, p) => acc + (p.totalCost || 0), 0);
|
||
|
||
// Keep a separate count for raw tracking that includes everything
|
||
const rawDtWithOutsource = pInDept.reduce((acc, p) => acc + (p.totalCost || 0), 0);
|
||
|
||
let dt = rawDt;
|
||
let artistCost = rawArtistCost;
|
||
|
||
// Apply Support Dept Artist Conversion Rate to the Stats (for allocation/dashboard)
|
||
if (d === globalParams.pcDept) {
|
||
const rate = (globalParams.supportConversionRate !== undefined) ? globalParams.supportConversionRate : 0.5;
|
||
// Support Dept 'dt' is literally just its converted artist cost, as P is not allocated.
|
||
dt = rawArtistCost * rate;
|
||
artistCost = rawArtistCost * rate;
|
||
}
|
||
|
||
deptStats[d] = {
|
||
rawDt: rawDtWithOutsource, // Keep all costs for the studio raw total
|
||
dt,
|
||
artistCost,
|
||
personnel: pInDept.length
|
||
};
|
||
});
|
||
|
||
// 3. PC Allocation
|
||
const pcDT = deptStats[globalParams.pcDept]?.dt || 0;
|
||
const businessDepts = Object.keys(globalParams.orgStructure);
|
||
|
||
// Allocation is based ONLY on the non-outsource artist cost (rawArtistCost) ratio
|
||
const totalBusinessArtistCost = businessDepts.reduce((acc, d) => acc + deptStats[d].artistCost, 0);
|
||
|
||
businessDepts.forEach(d => {
|
||
const ratio = totalBusinessArtistCost === 0 ? 0 : (deptStats[d].artistCost / totalBusinessArtistCost);
|
||
deptStats[d].pcAllocation = pcDT * ratio;
|
||
// Final CODA for business dept is its own non-outsource DT (P + A) + allocated PC
|
||
deptStats[d].coda = deptStats[d].dt + deptStats[d].pcAllocation;
|
||
deptStats[d].multiplier = deptStats[d].artistCost === 0 ? 0 : (deptStats[d].coda / deptStats[d].artistCost);
|
||
});
|
||
|
||
return {
|
||
data,
|
||
deptStats,
|
||
studioTotalDT: Object.values(deptStats).reduce((acc, s) => acc + s.dt, 0),
|
||
studioRawTotalDT: Object.values(deptStats).reduce((acc, s) => acc + s.rawDt, 0)
|
||
};
|
||
}
|
||
|
||
// --- UI RENDERING ---
|
||
function calculateInvoiceSummary(current) {
|
||
let totalPA = 0;
|
||
let totalO = 0;
|
||
current.forEach(p => {
|
||
const cost = p.totalCost || 0;
|
||
if (p.role.startsWith('O')) {
|
||
totalO += cost;
|
||
} else {
|
||
totalPA += cost;
|
||
}
|
||
});
|
||
|
||
const extOutsource = globalParams.externalProjectOutsourcing !== undefined ? parseFloat(globalParams.externalProjectOutsourcing) : 30000000;
|
||
const tripInvoices = globalParams.employeeTripInvoices !== undefined ? parseFloat(globalParams.employeeTripInvoices) : 15000000;
|
||
const grossMargin = (globalParams.grossMarginPct !== undefined) ? parseFloat(globalParams.grossMarginPct) : 0.85;
|
||
|
||
const targetRevenue = (totalPA + totalO + extOutsource) / grossMargin;
|
||
const finalInvoiceTotal = targetRevenue + tripInvoices;
|
||
|
||
return { totalPA, totalO, extOutsource, tripInvoices, grossMargin, finalInvoiceTotal };
|
||
}
|
||
|
||
function renderDashboard() {
|
||
const current = isSimMode ? simData : baseData;
|
||
const { deptStats, studioTotalDT, studioRawTotalDT } = calculateAll(current);
|
||
initOrgStructure();
|
||
const businessDepts = Object.keys(globalParams.orgStructure);
|
||
|
||
const invoiceSum = calculateInvoiceSummary(current);
|
||
const finalInvoiceTotal = invoiceSum.finalInvoiceTotal;
|
||
const tripInvoices = invoiceSum.tripInvoices;
|
||
|
||
const opMult = globalParams.opMultiplier || 2.0;
|
||
const deptMultipliersHtml = businessDepts.map(d => {
|
||
const s = deptStats[d];
|
||
if (!s || !s.multiplier) return '';
|
||
return `
|
||
<div style="display:flex; flex-direction:column; align-items:center; gap:2px; padding: 0 4px;">
|
||
<span style="font-size:0.6rem; color:var(--text-dim); text-transform:uppercase;">${d}</span>
|
||
<span style="font-size:0.9rem; font-weight:800; color:var(--accent-warning);">${(s.multiplier * opMult).toFixed(2)}x</span>
|
||
</div>
|
||
`;
|
||
}).filter(Boolean).join('<div style="width:1px; height:20px; background:rgba(255,255,255,0.1); margin:0 4px;"></div>');
|
||
|
||
const dashInvoiceHero = document.getElementById('dashboard-invoice-hero');
|
||
if (dashInvoiceHero) {
|
||
dashInvoiceHero.innerHTML = `
|
||
<div style="background: linear-gradient(90deg, rgba(16,185,129,0.12) 0%, rgba(59,130,246,0.12) 100%); border: 1px solid rgba(16,185,129,0.3); border-radius: 12px; padding: 0.6rem 1.2rem; display:flex; align-items:center; gap:1.2rem;">
|
||
<div style="font-size:0.72rem; color:var(--text-dim); text-transform:uppercase; letter-spacing:1px; white-space:nowrap;">年度發票目標</div>
|
||
<div style="font-size:1.4rem; font-weight:800; color:#10b981; white-space:nowrap;">NT$ ${Math.round(finalInvoiceTotal).toLocaleString()}</div>
|
||
|
||
<div style="margin-left:auto; display:flex; align-items:center; gap:8px;">
|
||
${deptMultipliersHtml}
|
||
<div style="width:1px; height:24px; background:rgba(255,255,255,0.2); margin:0 12px;"></div>
|
||
<a href="#" onclick="showView('invoice'); return false;" style="color:var(--accent-primary); text-decoration:none; font-size:0.75rem; white-space:nowrap;">分配明細 →</a>
|
||
</div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
// Simulation Diff calculation
|
||
let diffHtml = '';
|
||
if (isSimMode) {
|
||
const baseResult = calculateAll(baseData);
|
||
const diff = studioTotalDT - baseResult.studioTotalDT;
|
||
const diffColor = diff > 0 ? 'var(--accent-danger)' : 'var(--accent-success)';
|
||
const diffSign = diff > 0 ? '+' : '';
|
||
diffHtml = `<div class="card-trend" style="color: ${diffColor}; font-weight:700;">${diffSign}${diff.toLocaleString()} (vs 正式)</div>`;
|
||
}
|
||
|
||
const validMultipliers = businessDepts.map(d => deptStats[d].multiplier).filter(m => m > 0);
|
||
const avgMultiplier = validMultipliers.length > 0 ? (validMultipliers.reduce((a, m) => a + m, 0) / validMultipliers.length) : 0;
|
||
const studioTotalCoda = studioTotalDT; // Correct: Sum of all dt is the total studio CODA before distribution
|
||
|
||
// opMult moved up
|
||
const avgMultiplierDisplay = (avgMultiplier * opMult).toFixed(2);
|
||
|
||
// Render KPI Tiles (compact)
|
||
const kpiGrid = document.getElementById('main-kpis');
|
||
if (kpiGrid) {
|
||
kpiGrid.innerHTML = `
|
||
<div class="card">
|
||
<div class="card-label">原始總成本 (Studio DT)</div>
|
||
<div class="card-value" style="font-size: 1.5rem;">NT$ ${studioRawTotalDT.toLocaleString()}</div>
|
||
${diffHtml}
|
||
</div>
|
||
<div class="card primary">
|
||
<div class="card-label">全公司 CODA (含分攤)</div>
|
||
<div class="card-value" style="font-size: 1.8rem; color:var(--accent-success);">NT$ ${Math.round(studioTotalCoda).toLocaleString()}</div>
|
||
</div>
|
||
<div class="card" style="padding: 0.8rem 1.2rem;">
|
||
<div style="font-size:0.75rem; color:var(--text-dim); margin-bottom: 8px;">部門平均倍率</div>
|
||
<div style="font-size: 1.5rem; font-weight: 800; color:var(--accent-warning);">${avgMultiplierDisplay}x</div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
// Render Dept Bars (compact) - Include all departments including support
|
||
const barContainer = document.getElementById('dept-bars');
|
||
if (barContainer) {
|
||
barContainer.innerHTML = '';
|
||
const allDeptsForBars = [...businessDepts, globalParams.pcDept].filter(d => deptStats[d]);
|
||
const maxCoda = Math.max(...allDeptsForBars.map(d => deptStats[d].coda || deptStats[d].dt || 0), 1);
|
||
|
||
allDeptsForBars.forEach((d, i) => {
|
||
const s = deptStats[d];
|
||
const val = (s.coda !== undefined) ? s.coda : (s.dt || 0);
|
||
const pct = (val / maxCoda) * 100;
|
||
const colors = ['var(--accent-primary)', 'var(--accent-secondary)', 'var(--accent-success)', 'var(--accent-warning)', '#ec4899', '#06b6d4'];
|
||
const color = d === globalParams.pcDept ? 'var(--text-muted)' : colors[i % colors.length];
|
||
|
||
const multDisplay = d === globalParams.pcDept ? '' : `<span style="font-size:0.75rem; color:var(--text-dim); margin-left:8px; font-weight:400;">(${(s.multiplier * opMult).toFixed(2)}x)</span>`;
|
||
|
||
barContainer.innerHTML += `
|
||
<div class="dept-invoice-bar-row">
|
||
<div class="dept-invoice-bar-label">
|
||
<span style="font-weight:600; color:${d === globalParams.pcDept ? 'var(--text-dim)' : 'var(--text-main)'};">${d} ${multDisplay}</span>
|
||
<span style="font-weight:700; color:${color};">NT$ ${Math.round(val).toLocaleString()}</span>
|
||
</div>
|
||
<div class="dept-invoice-bar-track">
|
||
<div class="dept-invoice-bar-fill" style="width:${pct}%; background:${color}; opacity:${d === globalParams.pcDept ? '0.5' : '1'};"></div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
}
|
||
|
||
// Render Dept Invoice Targets
|
||
renderDeptInvoiceTargets(current, finalInvoiceTotal, tripInvoices);
|
||
|
||
renderParams();
|
||
renderGroup();
|
||
renderRoleStats(current);
|
||
renderPersonnelOverview();
|
||
}
|
||
|
||
// Calculates and renders per-dept invoice allocation targets in the dashboard
|
||
function renderDeptInvoiceTargets(current, finalInvoiceTotal, tripInvoices) {
|
||
const container = document.getElementById('dept-invoice-targets');
|
||
if (!container) return;
|
||
|
||
const { deptData } = calculateDeptAllocations(current, finalInvoiceTotal);
|
||
const businessDepts = Object.keys(globalParams.orgStructure);
|
||
|
||
let maxTarget = 0;
|
||
businessDepts.forEach(d => {
|
||
const data = deptData[d];
|
||
if (data.invoiceTarget > maxTarget) maxTarget = data.invoiceTarget;
|
||
});
|
||
|
||
const colors = ['var(--accent-primary)', 'var(--accent-secondary)', 'var(--accent-success)', 'var(--accent-warning)', '#ec4899'];
|
||
let html = '';
|
||
businessDepts.forEach((d, i) => {
|
||
const data = deptData[d];
|
||
const barPct = maxTarget > 0 ? (data.invoiceTarget / maxTarget * 100) : 0;
|
||
const color = colors[i % colors.length];
|
||
const isLean = data.surplusP === 0;
|
||
const badge = isLean
|
||
? `<span style="font-size:0.65rem; background:rgba(16,185,129,0.15); color:#10b981; border-radius:4px; padding:1px 5px;">精實</span>`
|
||
: `<span style="font-size:0.65rem; background:rgba(239,68,68,0.15); color:#ef4444; border-radius:4px; padding:1px 5px;">超標</span>`;
|
||
|
||
html += `
|
||
<div class="dept-invoice-bar-row">
|
||
<div class="dept-invoice-bar-label">
|
||
<span style="font-weight:600; color:var(--text-main); display:flex; align-items:center; gap:5px;">${d} ${badge}</span>
|
||
<span style="font-weight:700; color:${color};">NT$ ${Math.round(data.invoiceTarget).toLocaleString()}</span>
|
||
</div>
|
||
<div style="display:flex; align-items:center; gap:6px; margin-bottom:2px;">
|
||
<div class="dept-invoice-bar-track" style="flex:1;">
|
||
<div class="dept-invoice-bar-fill" style="width:${barPct}%; background:${color};"></div>
|
||
</div>
|
||
<span style="font-size:0.7rem; color:var(--text-dim); min-width:38px; text-align:right;">${(data.finalPct * 100).toFixed(1)}%</span>
|
||
</div>
|
||
<div style="font-size:0.67rem; color:var(--text-muted); display:flex; gap:8px;">
|
||
<span>P佔比 ${(data.m1 * 100).toFixed(1)}%</span>
|
||
<span>A佔比 ${(data.m2 * 100).toFixed(1)}%</span>
|
||
<span>H1目標 NT$ ${Math.round(data.invoiceTarget / 2).toLocaleString()}</span>
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
container.innerHTML = html;
|
||
}
|
||
|
||
// Shared function for calculating department allocations (Metric 1, 2, 3 and Final %)
|
||
function calculateDeptAllocations(current, finalInvoiceTotal) {
|
||
const businessDepts = Object.keys(globalParams.orgStructure);
|
||
const wP = Number(globalParams.invoiceWeightP ?? 0.4);
|
||
const wA = Number(globalParams.invoiceWeightA ?? 0.25);
|
||
const wS = Number(globalParams.invoiceWeightSurplus ?? 0.35);
|
||
const idealRatio = parseFloat(globalParams.targetAPRatio) || 6.0;
|
||
|
||
const deptData = {};
|
||
let globalP = 0;
|
||
let globalA = 0;
|
||
businessDepts.forEach(d => {
|
||
deptData[d] = { pCost: 0, aCost: 0, pNum: 0, aNum: 0, surplusP: 0, weight3: 0, m1: 0, m2: 0, m3: 0, finalPct: 0, invoiceTarget: 0 };
|
||
});
|
||
|
||
current.forEach(person => {
|
||
const d = (person.dept || '').trim();
|
||
if (!businessDepts.includes(d)) return;
|
||
const cost = person.totalCost || 0;
|
||
if (person.role.startsWith('P')) {
|
||
deptData[d].pCost += cost;
|
||
deptData[d].pNum += 1;
|
||
globalP += cost;
|
||
} else if (person.role.startsWith('A')) {
|
||
deptData[d].aCost += cost;
|
||
deptData[d].aNum += 1;
|
||
globalA += cost;
|
||
}
|
||
});
|
||
|
||
let totalWeight3 = 0;
|
||
businessDepts.forEach(d => {
|
||
const data = deptData[d];
|
||
data.m1 = globalP > 0 ? (data.pCost / globalP) : 0;
|
||
data.m2 = globalA > 0 ? (data.aCost / globalA) : 0;
|
||
const expectedP = idealRatio > 0 ? (data.aNum / idealRatio) : 0;
|
||
data.surplusP = Math.max(0, data.pNum - expectedP);
|
||
data.weight3 = data.pNum + data.surplusP;
|
||
totalWeight3 += data.weight3;
|
||
});
|
||
|
||
businessDepts.forEach(d => {
|
||
const data = deptData[d];
|
||
data.m3 = totalWeight3 > 0 ? (data.weight3 / totalWeight3) : 0;
|
||
data.finalPct = (data.m1 * wP) + (data.m2 * wA) + (data.m3 * wS);
|
||
data.invoiceTarget = finalInvoiceTotal * data.finalPct;
|
||
});
|
||
|
||
return { deptData, globalP, globalA, totalWeight3, wP, wA, wS };
|
||
}
|
||
|
||
function renderInvoice() {
|
||
const current = isSimMode ? simData : baseData;
|
||
calculateAll(current);
|
||
const res = calculateInvoiceSummary(current);
|
||
const finalInvoiceTotal = res.finalInvoiceTotal;
|
||
const tripInvoices = res.tripInvoices;
|
||
|
||
const { deptData, totalWeight3, wP, wA, wS } = calculateDeptAllocations(current, finalInvoiceTotal);
|
||
const businessDepts = Object.keys(globalParams.orgStructure);
|
||
|
||
const pManagerReductionPct = Number(globalParams.pManagerReductionPct ?? 0.6);
|
||
const pPCReductionPct = Number(globalParams.pPCReductionPct ?? 0.7);
|
||
|
||
const _authUserInv = typeof getCurrentUser === 'function' ? getCurrentUser() : null;
|
||
const _isAdminInv = !_authUserInv || _authUserInv.role === 'admin';
|
||
|
||
const container = document.getElementById('invoice');
|
||
if (!container) return;
|
||
|
||
let tableRowsHtml = '';
|
||
businessDepts.forEach((d, i) => {
|
||
if (!_isAdminInv && _authUserInv.dept && d !== _authUserInv.dept) return;
|
||
|
||
const data = deptData[d];
|
||
data.m3 = totalWeight3 > 0 ? (data.weight3 / totalWeight3) : 0;
|
||
data.finalPct = (data.m1 * wP) + (data.m2 * wA) + (data.m3 * wS);
|
||
data.invoiceTarget = finalInvoiceTotal * data.finalPct;
|
||
|
||
const surplusBadge = data.surplusP > 0
|
||
? `<span style="color:var(--accent-danger); font-size: 0.75rem; background:rgba(239,68,68,0.1); padding:2px 4px; border-radius:4px;">超標 Penalty</span>`
|
||
: `<span style="color:var(--accent-success); font-size: 0.75rem; background:rgba(16,185,129,0.1); padding:2px 4px; border-radius:4px;">精實 Reward</span>`;
|
||
|
||
const tripTargetAnnual = tripInvoices * data.finalPct;
|
||
const tripTargetHalf = tripTargetAnnual / 2;
|
||
|
||
const pPeople = current.filter(p => p.dept === d && p.role.startsWith('P'));
|
||
const pWithEffective = pPeople.map(p => {
|
||
const raw = p.totalCost || 0;
|
||
let disc = 1.0;
|
||
const isPCRole = (p.title || '').toUpperCase().includes('PC') || p.role.toUpperCase().includes('PC');
|
||
if (p.isManager) disc = pManagerReductionPct;
|
||
if (isPCRole) disc = pPCReductionPct;
|
||
return { ...p, effectiveCost: raw * disc, isPCRole };
|
||
});
|
||
|
||
const totalEffectiveP = pWithEffective.reduce((s, p) => s + p.effectiveCost, 0);
|
||
|
||
let pRowsHtml = '';
|
||
pWithEffective.forEach(p => {
|
||
const sharePct = totalEffectiveP > 0 ? (p.effectiveCost / totalEffectiveP) : 0;
|
||
const personalInvoice = data.invoiceTarget * sharePct;
|
||
let discBadge = '';
|
||
let discLabel = '有效比例 (全額承擔)';
|
||
if (p.isPCRole) {
|
||
discBadge = `<span style="background:rgba(16,185,129,0.15); color:var(--accent-success); font-size:0.68rem; padding:1px 6px; border-radius:4px; margin-left:4px;">PC ×${pPCReductionPct}</span>`;
|
||
discLabel = `有效比例 (×${pPCReductionPct} PC承擔)`;
|
||
} else if (p.isManager) {
|
||
discBadge = `<span style="background:rgba(139,92,246,0.15); color:var(--accent-secondary); font-size:0.68rem; padding:1px 6px; border-radius:4px; margin-left:4px;">管理職 ×${pManagerReductionPct}</span>`;
|
||
discLabel = `有效比例 (×${pManagerReductionPct} 主管承擔)`;
|
||
}
|
||
|
||
pRowsHtml += `
|
||
<div class="invoice-allocation-row" style="padding:0.5rem 1.25rem; border-bottom:1px solid rgba(255,255,255,0.04);">
|
||
<div style="display:flex; align-items:center; gap:6px;">
|
||
<span style="font-weight:700; font-size:0.9rem; color:var(--text-main);">${p.name}</span>
|
||
${discBadge}
|
||
<span style="font-size:0.72rem; color:var(--text-dim);">${p.title || ''}</span>
|
||
</div>
|
||
<div></div>
|
||
<div></div>
|
||
<div></div>
|
||
<div style="text-align:center;">
|
||
<div style="font-size:0.95rem; font-weight:700; color:var(--accent-warning);">${(sharePct * 100).toFixed(2)}%</div>
|
||
<div style="font-size:0.68rem; color:var(--text-dim);">${discLabel}</div>
|
||
</div>
|
||
<div style="text-align:right; font-weight:800; color:var(--text-main); font-size:0.95rem;">
|
||
NT$ ${Math.round(personalInvoice).toLocaleString()}
|
||
</div>
|
||
<div style="text-align:right; font-size:0.75rem; color:var(--accent-success);">
|
||
NT$ ${Math.round(tripTargetAnnual * sharePct).toLocaleString()}
|
||
</div>
|
||
<div></div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
const safeDeptId = 'dept_' + i;
|
||
tableRowsHtml += `
|
||
<div style="margin-bottom: 0.75rem; border: 1px solid rgba(255,255,255,0.07); border-radius: 12px; overflow: hidden; background: var(--bg-glass);">
|
||
<div class="invoice-allocation-row" onclick="toggleInvoiceDept('${safeDeptId}')" style="padding: 1rem 1.25rem; cursor:pointer;">
|
||
<div style="font-weight: 700; color:var(--text-main); font-size:1rem; display:flex; align-items:center; gap:6px;">
|
||
<span id="invoice-chevron-${safeDeptId}" style="font-size:0.7rem; color:var(--text-dim);">▶</span>
|
||
${d}
|
||
</div>
|
||
<div style="text-align:center;">
|
||
<div style="font-size:0.9rem; color:var(--accent-secondary); font-weight:700;">${(data.m1 * 100).toFixed(2)}%</div>
|
||
</div>
|
||
<div style="text-align:center;">
|
||
<div style="font-size:0.9rem; color:var(--accent-primary); font-weight:700;">${(data.m2 * 100).toFixed(2)}%</div>
|
||
</div>
|
||
<div style="text-align:center;">${surplusBadge}</div>
|
||
<div style="text-align:center; font-weight:800; color:var(--text-main);">${(data.finalPct * 100).toFixed(2)}%</div>
|
||
<div style="text-align:right; font-weight:800; color:var(--text-main);">NT$ ${Math.round(data.invoiceTarget).toLocaleString()}</div>
|
||
<div style="text-align:right; color:var(--accent-secondary); font-size:0.85rem;">NT$ ${Math.round(tripTargetAnnual).toLocaleString()}</div>
|
||
<div></div>
|
||
</div>
|
||
<div id="invoice-detail-${safeDeptId}" style="display:none; border-top:1px solid rgba(255,255,255,0.06);">
|
||
${pRowsHtml}
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
container.innerHTML = `
|
||
<h1 style="margin-bottom:1rem; font-size:1.3rem;">🧾 年度發票分配</h1>
|
||
<div class="invoice-allocation-scroll">
|
||
<div class="invoice-allocation-table">
|
||
<div class="invoice-allocation-row" id="invoice-allocation-headings" style="padding:0.75rem 1.25rem; margin:0 1px 0.5rem;">
|
||
<div style="font-size:0.72rem; color:var(--text-dim);">部門/人員</div>
|
||
<div style="font-size:0.72rem; color:var(--accent-secondary); text-align:center;">指標1 P佔比<br><span style="opacity:0.7;">權重 ${(wP * 100).toFixed(0)}%</span></div>
|
||
<div style="font-size:0.72rem; color:var(--accent-primary); text-transform:uppercase; letter-spacing:0.5px; text-align:center;">指標2 A佔比<br><span style="opacity:0.7;">權重 ${(wA * 100).toFixed(0)}%</span></div>
|
||
<div style="font-size:0.72rem; color:var(--accent-warning); text-transform:uppercase; letter-spacing:0.5px; text-align:center;">指標3 溢出<br><span style="opacity:0.7;">權重 ${(wS * 100).toFixed(0)}%</span></div>
|
||
<div style="font-size:0.72rem; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.5px; text-align:center;">🏁 最終比例</div>
|
||
<div style="font-size:0.72rem; color:var(--text-dim); text-transform:uppercase; letter-spacing:0.5px; text-align:right;">💰 責任發票額</div>
|
||
<div style="font-size:0.72rem; color:var(--accent-secondary); text-transform:uppercase; letter-spacing:0.5px; text-align:right;">✈️ 員旅配額</div>
|
||
<div></div>
|
||
</div>
|
||
|
||
<!-- Dept Accordion Cards -->
|
||
<div id="invoice-dept-list">
|
||
${tableRowsHtml}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="card" style="margin-top: 2rem; padding: 1rem 1.5rem; background: rgba(139,92,246,0.05); border-color: rgba(139,92,246,0.15); font-size:0.82rem; color:var(--text-dim);">
|
||
<div style="font-weight:700; color:var(--accent-secondary); margin-bottom:0.5rem;">📌 P 人員承擔比計算說明</div>
|
||
<div style="display:flex; gap:2rem; flex-wrap:wrap; line-height:1.8;">
|
||
<span>🔹 一般 P:有效承擔成本 = 全額薪資成本(×100%)</span>
|
||
<span>🔸 P 管理職(isManager):有效承擔成本 × <strong style="color:var(--accent-secondary);">${(pManagerReductionPct * 100).toFixed(0)}%</strong>(釋出 ${((1 - pManagerReductionPct) * 100).toFixed(0)}%)</span>
|
||
<span>🟢 PC 職稱(title/role 含 PC):有效承擔成本 × <strong style="color:var(--accent-success);">${(pPCReductionPct * 100).toFixed(0)}%</strong>(釋出 ${((1 - pPCReductionPct) * 100).toFixed(0)}%)</span>
|
||
<span>🔹 各 P 的個人承擔額 = 部門發票目標 × (個人有效成本 / 部門有效P成本合計)</span>
|
||
</div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
function toggleInvoiceDept(safeDeptId) {
|
||
const panel = document.getElementById('invoice-detail-' + safeDeptId);
|
||
const chevron = document.getElementById('invoice-chevron-' + safeDeptId);
|
||
if (!panel) return;
|
||
const isOpen = panel.style.display !== 'none';
|
||
panel.style.display = isOpen ? 'none' : 'block';
|
||
if (chevron) chevron.style.transform = isOpen ? 'rotate(0deg)' : 'rotate(90deg)';
|
||
}
|
||
|
||
|
||
function renderPersonnelOverview() {
|
||
const current = isSimMode ? simData : baseData;
|
||
const { deptStats, studioRawTotalDT } = calculateAll(current);
|
||
const container = document.getElementById('dept-cost-stack-chart');
|
||
const kpiGrid = document.getElementById('dept-kpi-grid');
|
||
const orderedDepts = [...Object.keys(globalParams.orgStructure), globalParams.pcDept];
|
||
|
||
// Calculate P, A, and O breakdown per department and globally
|
||
const deptBreakdowns = {};
|
||
let globalP = 0;
|
||
let globalA = 0;
|
||
let globalO = 0;
|
||
orderedDepts.forEach(d => { deptBreakdowns[d] = { p: 0, a: 0, o: 0 }; });
|
||
|
||
current.forEach(person => {
|
||
const cost = person.totalCost || 0;
|
||
if (person.role.startsWith('P')) {
|
||
globalP += cost;
|
||
if (deptBreakdowns[person.dept]) deptBreakdowns[person.dept].p += cost;
|
||
} else if (person.role.startsWith('A')) {
|
||
globalA += cost;
|
||
if (deptBreakdowns[person.dept]) deptBreakdowns[person.dept].a += cost;
|
||
} else if (person.role.startsWith('O')) {
|
||
globalO += cost;
|
||
if (deptBreakdowns[person.dept]) deptBreakdowns[person.dept].o += cost;
|
||
}
|
||
});
|
||
|
||
// 1. Render Stacked Bar + Grand Total Header with Global PAO
|
||
let stackHtml = `
|
||
<div style="display:flex; justify-content:space-between; align-items:flex-end; margin-bottom: 0.5rem;">
|
||
<div style="font-size: 0.85rem; color: var(--text-dim); text-transform: uppercase; letter-spacing: 1px;">原始薪資預算總計</div>
|
||
<div style="font-size: 1.5rem; font-weight: 800; color: var(--text-main);">NT$ ${studioRawTotalDT.toLocaleString()}</div>
|
||
</div>
|
||
<div style="display:flex; gap: 1rem; margin-bottom: 1.2rem; font-size: 0.8rem; background: rgba(0,0,0,0.2); padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-glass);">
|
||
<div style="display:flex; align-items:center; gap: 6px;">
|
||
<span style="color:var(--accent-secondary); background:rgba(139,92,246,0.1); padding:2px 6px; border-radius:4px;">全公司 P 總計</span>
|
||
<span style="font-weight:700; color:var(--accent-secondary);">NT$ ${globalP.toLocaleString()}</span>
|
||
</div>
|
||
<div style="display:flex; align-items:center; gap: 6px; border-left: 1px solid var(--border-glass); padding-left: 1rem;">
|
||
<span style="color:var(--accent-primary); background:rgba(59,130,246,0.1); padding:2px 6px; border-radius:4px;">全公司 A 總計</span>
|
||
<span style="font-weight:700; color:var(--accent-primary);">NT$ ${globalA.toLocaleString()}</span>
|
||
</div>
|
||
<div style="display:flex; align-items:center; gap: 6px; border-left: 1px solid var(--border-glass); padding-left: 1rem;">
|
||
<span style="color:var(--accent-warning); background:rgba(245,158,11,0.1); padding:2px 6px; border-radius:4px;">全公司 O 總計</span>
|
||
<span style="font-weight:700; color:var(--accent-warning);">NT$ ${globalO.toLocaleString()}</span>
|
||
</div>
|
||
</div>
|
||
<div class="chart-bar-container">
|
||
`;
|
||
const colors = ['var(--accent-primary)', 'var(--accent-secondary)', 'var(--accent-success)', 'var(--accent-warning)', '#ec4899', '#06b6d4'];
|
||
|
||
// Iterate over ordered departments
|
||
orderedDepts.forEach((d, i) => {
|
||
const s = deptStats[d];
|
||
if (!s) return; // Skip if department has no stats
|
||
const pct = studioRawTotalDT === 0 ? 0 : (s.rawDt / studioRawTotalDT * 100);
|
||
if (pct > 2) {
|
||
stackHtml += `<div class="chart-bar" style="width: ${pct}%; background: ${colors[i % colors.length]}">${d}</div>`;
|
||
}
|
||
});
|
||
stackHtml += '</div>';
|
||
container.innerHTML = stackHtml;
|
||
|
||
// 2. Render KPIs with P, A, and O breakdown
|
||
kpiGrid.innerHTML = '';
|
||
|
||
Object.keys(globalParams.orgStructure).forEach((d, i) => { // Only business departments for this grid
|
||
const s = deptStats[d];
|
||
if (!s) return;
|
||
const parts = deptBreakdowns[d] || { p: 0, a: 0, o: 0 };
|
||
const pct = studioRawTotalDT === 0 ? 0 : (s.rawDt / studioRawTotalDT * 100);
|
||
|
||
const pPct = globalP === 0 ? 0 : (parts.p / globalP * 100);
|
||
const aPct = globalA === 0 ? 0 : (parts.a / globalA * 100);
|
||
|
||
kpiGrid.innerHTML += `
|
||
<div class="card ${i % 2 === 0 ? 'secondary' : 'success'}" style="cursor:pointer; display:flex; flex-direction:column; justify-content:space-between; height: 100%;" onclick="showPersonnelView('${d}')">
|
||
<div>
|
||
<div class="card-label">${d}</div>
|
||
<div class="card-value" style="font-size: 1.25rem;">NT$ ${s.rawDt.toLocaleString()}</div>
|
||
<div class="card-trend">${s.personnel} 人員 | 佔比 ${formatPct(pct)}%</div>
|
||
</div>
|
||
<div style="margin-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 0.5rem; display: flex; gap: 0.25rem; flex-direction: column;">
|
||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 2px;">
|
||
<span style="font-size:0.7rem; color:var(--accent-secondary); background:rgba(139,92,246,0.1); padding:2px 6px; border-radius:4px;">專案 P</span>
|
||
<div style="text-align:right;">
|
||
<span style="font-size:0.8rem; font-weight:700; color:var(--accent-secondary);">NT$ ${parts.p.toLocaleString()}</span>
|
||
<span style="font-size:0.65rem; color:var(--text-dim); margin-left: 4px;">(${formatPct(pPct)}%)</span>
|
||
</div>
|
||
</div>
|
||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 2px;">
|
||
<span style="font-size:0.7rem; color:var(--accent-primary); background:rgba(59,130,246,0.1); padding:2px 6px; border-radius:4px;">內製 A</span>
|
||
<div style="text-align:right;">
|
||
<span style="font-size:0.8rem; font-weight:700; color:var(--accent-primary);">NT$ ${parts.a.toLocaleString()}</span>
|
||
<span style="font-size:0.65rem; color:var(--text-dim); margin-left: 4px;">(${formatPct(aPct)}%)</span>
|
||
</div>
|
||
</div>
|
||
<div style="display:flex; justify-content:space-between; align-items:center;">
|
||
<span style="font-size:0.7rem; color:var(--accent-warning); background:rgba(245,158,11,0.1); padding:2px 6px; border-radius:4px;">外包 O</span>
|
||
<span style="font-size:0.8rem; font-weight:700; color:var(--accent-warning);">NT$ ${parts.o.toLocaleString()}</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
// Add PC Dept to the grid if it exists
|
||
const pcDeptStats = deptStats[globalParams.pcDept];
|
||
if (pcDeptStats) {
|
||
const parts = deptBreakdowns[globalParams.pcDept] || { p: 0, a: 0, o: 0 };
|
||
const pct = studioRawTotalDT === 0 ? 0 : (pcDeptStats.rawDt / studioRawTotalDT * 100);
|
||
const pPct = globalP === 0 ? 0 : (parts.p / globalP * 100);
|
||
const aPct = globalA === 0 ? 0 : (parts.a / globalA * 100);
|
||
|
||
kpiGrid.innerHTML += `
|
||
<div class="card" style="cursor:pointer; display:flex; flex-direction:column; justify-content:space-between; height: 100%; border-style: dashed; opacity: 0.8;" onclick="showPersonnelView('${globalParams.pcDept}')">
|
||
<div>
|
||
<div class="card-label">${globalParams.pcDept}</div>
|
||
<div class="card-value" style="font-size: 1.25rem;">NT$ ${pcDeptStats.rawDt.toLocaleString()}</div>
|
||
<div class="card-trend">${pcDeptStats.personnel} 人員 | 佔比 ${formatPct(pct)}%</div>
|
||
</div>
|
||
<div style="margin-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 0.5rem; display: flex; gap: 0.25rem; flex-direction: column;">
|
||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 2px;">
|
||
<span style="font-size:0.7rem; color:var(--accent-secondary); background:rgba(139,92,246,0.1); padding:2px 6px; border-radius:4px;">專案 P</span>
|
||
<div style="text-align:right;">
|
||
<span style="font-size:0.8rem; font-weight:700; color:var(--accent-secondary);">NT$ ${parts.p.toLocaleString()}</span>
|
||
<span style="font-size:0.65rem; color:var(--text-dim); margin-left: 4px;">(${formatPct(pPct)}%)</span>
|
||
</div>
|
||
</div>
|
||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 2px;">
|
||
<span style="font-size:0.7rem; color:var(--accent-primary); background:rgba(59,130,246,0.1); padding:2px 6px; border-radius:4px;">內製 A</span>
|
||
<div style="text-align:right;">
|
||
<span style="font-size:0.8rem; font-weight:700; color:var(--accent-primary);">NT$ ${parts.a.toLocaleString()}</span>
|
||
<span style="font-size:0.65rem; color:var(--text-dim); margin-left: 4px;">(${formatPct(aPct)}%)</span>
|
||
</div>
|
||
</div>
|
||
<div style="display:flex; justify-content:space-between; align-items:center;">
|
||
<span style="font-size:0.7rem; color:var(--accent-warning); background:rgba(245,158,11,0.1); padding:2px 6px; border-radius:4px;">外包 O</span>
|
||
<span style="font-size:0.8rem; font-weight:700; color:var(--accent-warning);">NT$ ${parts.o.toLocaleString()}</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
}
|
||
}
|
||
|
||
function renderParams() {
|
||
initOrgStructure();
|
||
const container = document.getElementById('global-params');
|
||
if (!container) return;
|
||
|
||
const rdIndivTagsHtml = (globalParams.rdIndividuals || []).map(name => `
|
||
<div class="rd-tag" style="background: rgba(139,92,246,0.15); border: 1px solid rgba(139,92,246,0.3); color: var(--accent-secondary);">
|
||
<span>${name}</span>
|
||
<span class="rd-tag-remove" onclick="removeRDIndivTag('${name}')" style="cursor:pointer; margin-left:6px; opacity:0.6;">×</span>
|
||
</div>
|
||
`).join('');
|
||
|
||
// Card Builder Helper
|
||
const buildParamRow = (label, key, unit = "", isMoney = false, step = "1") => {
|
||
let val = globalParams[key] || 0;
|
||
let onchange = `updateGlobalParam('${key}', this.value)`;
|
||
let displayVal = val;
|
||
|
||
if (unit === '%' || unit === '率') {
|
||
displayVal = Number((val * 100).toFixed(6));
|
||
unit = '%';
|
||
step = String(Number(step) * 100);
|
||
onchange = `updateGlobalParam('${key}', Number(this.value) / 100)`;
|
||
}
|
||
|
||
if (isMoney) {
|
||
displayVal = val.toLocaleString();
|
||
onchange = `updateGlobalParamMoney('${key}', this.value)`;
|
||
}
|
||
|
||
return `
|
||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 0.75rem; gap: 0.5rem;">
|
||
<label style="color: var(--text-muted); font-size: 0.85rem; flex:1; line-height: 1.2;">${label}</label>
|
||
<div style="display:flex; align-items:center; gap:8px;">
|
||
<input type="${isMoney ? 'text' : 'number'}" step="${step}"
|
||
style="width: 115px; text-align:right; font-weight:700; color:var(--text-main); background:rgba(255,255,255,0.05); border-color:rgba(255,255,255,0.1); padding: 4px 8px;"
|
||
value="${displayVal}" onchange="${onchange}">
|
||
<span style="font-size:0.75rem; color:var(--text-dim); min-width:32px; text-align:left;">${unit}</span>
|
||
</div>
|
||
</div>
|
||
`;
|
||
};
|
||
|
||
container.innerHTML = `
|
||
<!-- Column 1: Base Core Params -->
|
||
<div class="card" style="height: 100%; border-top: 3px solid var(--accent-primary); padding: 1.25rem;">
|
||
<h4 style="margin-bottom: 0.5rem; color: var(--text-main); font-size: 1rem; display:flex; align-items:center; gap:8px;">
|
||
<span style="background:rgba(59,130,246,0.1); padding:4px; border-radius:6px;">📋</span> 基本參數
|
||
</h4>
|
||
<p style="color: var(--text-dim); font-size: 0.72rem; margin-bottom: 1rem; line-height: 1.4;">
|
||
調整人薪倍率、年度工作天數與產出率,這些值會直接影響各部門 CODA 的計算基準。
|
||
</p>
|
||
<div style="display:flex; flex-direction:column; gap:0.25rem;">
|
||
${buildParamRow("人薪倍率 (Multiplier)", "opMultiplier", "倍", false, "0.1")}
|
||
${buildParamRow("製程部藝術家轉換率", "supportConversionRate", "率", false, "0.1")}
|
||
${buildParamRow("年度工作天數", "annualWorkDays", "天")}
|
||
${buildParamRow("月平均工作天數", "workingDays", "天")}
|
||
${buildParamRow("P-人員 產出率 (Utilization P)", "utilizationP", "率", false, "0.05")}
|
||
${buildParamRow("A-人員 產出率 (Utilization A)", "utilizationA", "率", false, "0.05")}
|
||
</div>
|
||
<div style="margin-top: 2rem; padding-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05);">
|
||
<p style="color: var(--text-dim); font-size: 0.72rem; line-height:1.4;">
|
||
📌 此處設定為系統計算之基礎基準。<br>
|
||
「製程部」作為支持單位不列入發票牆。
|
||
</p>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Column 2: Invoice & Targets -->
|
||
<div class="card" style="height: 100%; border-top: 3px solid var(--accent-success); padding: 1.25rem;">
|
||
<h4 style="margin-bottom: 0.5rem; color: var(--text-main); font-size: 1rem; display:flex; align-items:center; gap:8px;">
|
||
<span style="background:rgba(16,185,129,0.1); padding:4px; border-radius:6px;">🎯</span> 發票分配與目標
|
||
</h4>
|
||
<p style="color: var(--text-dim); font-size: 0.72rem; margin-bottom: 1rem; line-height: 1.4;">
|
||
設定各項指標權重與年度專案成本,系統將依此自動演算出各部門應達成的發票目標。
|
||
</p>
|
||
<div style="display:flex; flex-direction:column; gap:0.25rem;">
|
||
${buildParamRow("指標1:P成本權重", "invoiceWeightP", "%", false, "0.05")}
|
||
${buildParamRow("指標2:A成本權重", "invoiceWeightA", "%", false, "0.05")}
|
||
${buildParamRow("指標3:溢出(Penalty)", "invoiceWeightSurplus", "%", false, "0.05")}
|
||
${buildParamRow("理想 A/P 比率", "targetAPRatio", ":1", false, "0.5")}
|
||
</div>
|
||
|
||
<div style="margin-top: 1.25rem; padding-top: 1.25rem; border-top: 1px dashed rgba(255,255,255,0.1);">
|
||
<h5 style="margin-bottom:1rem; font-size:0.85rem; color:var(--text-dim); display:flex; align-items:center; gap:6px;">📈 年度目標基準預估</h5>
|
||
${buildParamRow("專案委外費用", "externalProjectOutsourcing", "NT$", true)}
|
||
${buildParamRow("員旅/不計毛利額", "employeeTripInvoices", "NT$", true)}
|
||
${buildParamRow("預計毛利率", "grossMarginPct", "%", false, "0.05")}
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Column 3: RD & Management Reductions -->
|
||
<div style="display: flex; flex-direction: column; gap: 1.25rem;">
|
||
|
||
<!-- Combined RD Block -->
|
||
<div class="card" style="border-top: 3px solid var(--accent-secondary); padding: 1.25rem;">
|
||
<h4 style="margin-bottom: 0.5rem; color: var(--text-main); font-size: 1rem; display:flex; align-items:center; gap:8px;">
|
||
<span style="background:rgba(139,92,246,0.1); padding:4px; border-radius:6px;">🧪</span> 研發參數與標註
|
||
</h4>
|
||
<p style="color: var(--text-dim); font-size: 0.72rem; margin-bottom: 0.75rem; line-height: 1.4;">
|
||
設定研發減免比例,並可手動指派製程部特定的研發人員。
|
||
</p>
|
||
${buildParamRow("部門研發減免%數", "rdReductionPct", "率", false, "0.05")}
|
||
|
||
<div style="margin-top: 1rem; padding-top: 0.75rem; border-top: 1px dashed rgba(255,255,255,0.08);">
|
||
<div class="rd-search-container" style="margin-bottom: 0.75rem;">
|
||
<input type="text" id="rd-indiv-search-input" class="rd-search-input"
|
||
style="width:100%; border-radius:8px; background:rgba(255,255,255,0.03);"
|
||
placeholder="🔍 加入製程部研發人員..." onkeyup="updateRDIndivSuggestions()">
|
||
<div id="rd-indiv-suggestions" class="rd-suggestions"></div>
|
||
</div>
|
||
<div id="rd-indiv-tag-container" class="rd-tag-container" style="max-height: 80px; overflow-y: auto; display:flex; flex-wrap:wrap; gap:6px;">
|
||
${rdIndivTagsHtml}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Management Reductions -->
|
||
<div class="card" style="border-top: 3px solid var(--accent-warning); padding: 1.25rem;">
|
||
<h4 style="margin-bottom: 0.5rem; color: var(--text-main); font-size: 1rem; display:flex; align-items:center; gap:8px;">
|
||
<span style="background:rgba(245,158,11,0.1); padding:4px; border-radius:6px;">⚖️</span> 管理與PC承擔%數
|
||
</h4>
|
||
<p style="color: var(--text-dim); font-size: 0.72rem; margin-bottom: 0.75rem; line-height: 1.4;">
|
||
定義管理職與 PC 職位的成本承擔比例,未承擔的成本將由組員共同分攤。
|
||
</p>
|
||
<div style="display:flex; flex-direction:column; gap:0.15rem;">
|
||
${buildParamRow("管理P承擔%數", "pManagerReductionPct", "率", false, "0.05")}
|
||
${buildParamRow("職稱 PC 承擔P%數", "pPCReductionPct", "率", false, "0.05")}
|
||
${buildParamRow("管理職 Artist 承擔%數", "managerReductionPct", "率", false, "0.05")}
|
||
${buildParamRow("CG Lead 管理承擔%數", "cgLeadReductionPct", "率", false, "0.05")}
|
||
</div>
|
||
</div>
|
||
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
function toggleInvoiceDept(deptId) {
|
||
const panel = document.getElementById(`invoice-detail-${deptId}`);
|
||
const chevron = document.getElementById(`invoice-chevron-${deptId}`);
|
||
if (panel.style.display === 'none') {
|
||
panel.style.display = 'block';
|
||
chevron.style.transform = 'rotate(90deg)';
|
||
chevron.style.color = 'var(--accent-secondary)';
|
||
} else {
|
||
panel.style.display = 'none';
|
||
chevron.style.transform = 'rotate(0deg)';
|
||
chevron.style.color = 'var(--text-dim)';
|
||
}
|
||
}
|
||
|
||
function renderOrgStructure() {
|
||
initOrgStructure();
|
||
const container = document.getElementById('org-structure-content');
|
||
if (!container) return;
|
||
|
||
let html = `
|
||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||
<div>
|
||
<h1 style="margin-bottom: 0.5rem;">🏢 直線職能型組織架構</h1>
|
||
<p style="color: var(--text-muted); font-size: 0.9rem;">圖示化呈現組織結構與流向,結合統壹指揮與職能分工優點</p>
|
||
</div>
|
||
<button class="btn btn-primary" onclick="promptAddDept()">+ 新增部門</button>
|
||
</div>
|
||
|
||
<div class="org-tree-container">
|
||
<div class="org-root-node">夢想動畫管理中心</div>
|
||
|
||
<div class="org-branches-row">
|
||
`;
|
||
|
||
// 1. Business Departments
|
||
Object.keys(globalParams.orgStructure).forEach(dept => {
|
||
const groups = globalParams.orgStructure[dept];
|
||
html += `
|
||
<div class="org-dept-branch">
|
||
<div class="org-dept-card">
|
||
<div class="org-dept-header">
|
||
<h3 style="color: var(--accent-primary); font-size: 1.15rem;">${dept}</h3>
|
||
<span class="btn-icon" style="color: var(--accent-danger); cursor: pointer; opacity: 0.5;" onclick="removeOrgDept('${dept}')">🗑️</span>
|
||
</div>
|
||
<div class="org-group-list-vertical">
|
||
${groups.map(g => {
|
||
const isRD = (globalParams.rdGroups || []).includes(`${dept}|${g}`);
|
||
const isCGLead = (globalParams.cgLeadGroups || []).includes(`${dept}|${g}`);
|
||
return `
|
||
<div class="org-group-item" style="${(isRD || isCGLead) ? 'border-color: var(--accent-secondary); background: rgba(52, 211, 153, 0.05);' : ''}">
|
||
<div style="display: flex; align-items: center; gap: 8px;">
|
||
<div style="display: flex; align-items: center; gap: 4px;">
|
||
<input type="checkbox" ${isRD ? 'checked' : ''} onchange="toggleRDGroup('${dept}', '${g}')" style="cursor: pointer; width: 14px; height: 14px; margin: 0;" title="設定為 RD 研發組">
|
||
<span style="font-size: 0.6rem; color: var(--accent-success); font-weight: 800;">RD</span>
|
||
</div>
|
||
<div style="display: flex; align-items: center; gap: 4px;">
|
||
<input type="checkbox" ${isCGLead ? 'checked' : ''} onchange="toggleCGLeadGroup('${dept}', '${g}')" style="cursor: pointer; width: 14px; height: 14px; margin: 0;" title="設定為 CG Lead 管理組">
|
||
<span style="font-size: 0.6rem; color: var(--accent-primary); font-weight: 800;">CG</span>
|
||
</div>
|
||
<span style="${(isRD || isCGLead) ? 'color: var(--accent-success); font-weight: 600; font-size: 0.8rem;' : ''}">${g}</span>
|
||
</div>
|
||
${g !== '未分組' ? `<span style="cursor: pointer; opacity: 0.3;" onclick="removeOrgGroup('${dept}', '${g}')">✕</span>` : ''}
|
||
</div>
|
||
`;
|
||
}).join('')}
|
||
</div>
|
||
<div class="org-add-btn" onclick="promptAddGroup('${dept}')">
|
||
<span>+ 新增組別</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
// 2. static "製程部" (Support Dept) as a branch
|
||
html += `
|
||
<div class="org-dept-branch">
|
||
<div class="org-dept-card" style="border-style: dashed; opacity: 0.8;">
|
||
<div class="org-dept-header">
|
||
<h3 style="color: var(--text-dim); font-size: 1.15rem;">${globalParams.pcDept}</h3>
|
||
<span style="font-size: 0.6rem; color: var(--text-dim); background: rgba(255,255,255,0.05); padding: 2px 8px; border-radius: 4px;">系統預設支援部</span>
|
||
</div>
|
||
<div class="org-group-list-vertical">
|
||
<div class="org-group-item" style="color: var(--text-dim); border-style: dashed;">
|
||
<span style="font-size: 0.75rem;">(動態連動原始資料)</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
|
||
html += `
|
||
</div>
|
||
</div>
|
||
`;
|
||
container.innerHTML = html;
|
||
}
|
||
|
||
function promptAddDept() {
|
||
const name = prompt("請輸入新部門名稱:");
|
||
if (name && name.trim()) {
|
||
const deptName = name.trim();
|
||
if (!globalParams.orgStructure[deptName] && deptName !== globalParams.pcDept) {
|
||
globalParams.orgStructure[deptName] = ['未分組'];
|
||
saveAndRefresh();
|
||
} else {
|
||
alert("該部門已存在或為預留名稱。");
|
||
}
|
||
}
|
||
}
|
||
|
||
function promptAddGroup(deptName) {
|
||
const name = prompt(`要在「${deptName}」新增什麼組別?`);
|
||
if (name && name.trim()) {
|
||
const groupName = name.trim();
|
||
if (!globalParams.orgStructure[deptName].includes(groupName)) {
|
||
globalParams.orgStructure[deptName].push(groupName);
|
||
saveAndRefresh();
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- ORG STRUCTURE FUNCTIONS ---
|
||
function removeOrgDept(deptName) {
|
||
if (confirm(`確定要移除「${deptName}」及其所有組別設定嗎?(人員資料不會被刪除,但可能無法顯示)`)) {
|
||
delete globalParams.orgStructure[deptName];
|
||
saveAndRefresh();
|
||
}
|
||
}
|
||
|
||
function removeOrgGroup(deptName, groupName) {
|
||
const idx = globalParams.orgStructure[deptName].indexOf(groupName);
|
||
if (idx > -1) {
|
||
globalParams.orgStructure[deptName].splice(idx, 1);
|
||
saveAndRefresh();
|
||
}
|
||
}
|
||
|
||
function updateRDSuggestions(query) {
|
||
const suggestionsEl = document.getElementById('rd-suggestions');
|
||
if (!query && query !== "") {
|
||
suggestionsEl.style.display = 'none';
|
||
return;
|
||
}
|
||
|
||
const current = isSimMode ? simData : baseData;
|
||
const allGroups = [...new Set(current.filter(p => p.dept !== globalParams.pcDept && p.group).map(p => `${p.dept}|${p.group}`))];
|
||
const activeGroups = globalParams.rdGroups || [];
|
||
|
||
const filtered = allGroups.filter(g =>
|
||
!activeGroups.includes(g) &&
|
||
g.toLowerCase().includes(query.toLowerCase())
|
||
).sort();
|
||
|
||
if (filtered.length === 0) {
|
||
suggestionsEl.innerHTML = '<div class="rd-suggestion-item" style="color: var(--text-dim);">無結果</div>';
|
||
suggestionsEl.style.display = 'block';
|
||
return;
|
||
}
|
||
|
||
suggestionsEl.innerHTML = filtered.map(g => `
|
||
<div class="rd-suggestion-item" onclick="addRDTag('${g}')">
|
||
${g.replace('|', ' - ')}
|
||
</div>
|
||
`).join('');
|
||
suggestionsEl.style.display = 'block';
|
||
}
|
||
|
||
function toggleRDGroup(dept, group) {
|
||
const key = `${dept}|${group}`;
|
||
if (!globalParams.rdGroups) globalParams.rdGroups = [];
|
||
const idx = globalParams.rdGroups.indexOf(key);
|
||
if (idx > -1) {
|
||
globalParams.rdGroups.splice(idx, 1);
|
||
} else {
|
||
globalParams.rdGroups.push(key);
|
||
}
|
||
saveAndRefresh();
|
||
}
|
||
|
||
function toggleCGLeadGroup(dept, group) {
|
||
const key = `${dept}|${group}`;
|
||
if (!globalParams.cgLeadGroups) globalParams.cgLeadGroups = [];
|
||
const idx = globalParams.cgLeadGroups.indexOf(key);
|
||
if (idx > -1) {
|
||
globalParams.cgLeadGroups.splice(idx, 1);
|
||
} else {
|
||
globalParams.cgLeadGroups.push(key);
|
||
}
|
||
saveAndRefresh();
|
||
}
|
||
|
||
function removeRDTag(groupKey) {
|
||
if (!globalParams.rdGroups) return;
|
||
globalParams.rdGroups = globalParams.rdGroups.filter(g => g !== groupKey);
|
||
saveAndRefresh();
|
||
}
|
||
|
||
function updateRDIndivSuggestions() {
|
||
const query = document.getElementById('rd-indiv-search-input').value;
|
||
const suggestionsEl = document.getElementById('rd-indiv-suggestions');
|
||
if (!query && query !== "") {
|
||
suggestionsEl.style.display = 'none';
|
||
return;
|
||
}
|
||
|
||
const current = isSimMode ? simData : baseData;
|
||
const allSupportStaff = [...new Set(current.filter(p => p.dept === globalParams.pcDept).map(p => p.name))];
|
||
const activeIndivs = globalParams.rdIndividuals || [];
|
||
|
||
const filtered = allSupportStaff.filter(name =>
|
||
!activeIndivs.includes(name) &&
|
||
name.toLowerCase().includes(query.toLowerCase())
|
||
).sort();
|
||
|
||
if (filtered.length === 0) {
|
||
suggestionsEl.innerHTML = '<div class="rd-suggestion-item" style="color: var(--text-dim);">無法找到相符之製程部人員</div>';
|
||
suggestionsEl.style.display = 'block';
|
||
return;
|
||
}
|
||
|
||
suggestionsEl.innerHTML = filtered.map(name => `
|
||
<div class="rd-suggestion-item" onclick="addRDIndivTag('${name}')">
|
||
${name}
|
||
</div>
|
||
`).join('');
|
||
suggestionsEl.style.display = 'block';
|
||
}
|
||
|
||
function addRDIndivTag(name) {
|
||
if (!globalParams.rdIndividuals) globalParams.rdIndividuals = [];
|
||
if (!globalParams.rdIndividuals.includes(name)) {
|
||
globalParams.rdIndividuals.push(name);
|
||
document.getElementById('rd-indiv-search-input').value = '';
|
||
saveAndRefresh();
|
||
}
|
||
}
|
||
|
||
function updateGlobalParamMoney(key, rawVal) {
|
||
const numStr = String(rawVal).replace(/,/g, '');
|
||
const parsed = parseFloat(numStr);
|
||
if (!isNaN(parsed)) {
|
||
globalParams[key] = parsed;
|
||
saveAndRefresh();
|
||
} else {
|
||
renderParams(); // revert back to original value visually
|
||
}
|
||
}
|
||
|
||
function updateGlobalParam(key, val) {
|
||
const parsed = parseFloat(val);
|
||
if (!isNaN(parsed)) {
|
||
globalParams[key] = parsed;
|
||
document.getElementById('coda-grand-total').innerText = "重新計算中..."; // Placeholder
|
||
saveAndRefresh();
|
||
}
|
||
}
|
||
|
||
function removeRDIndivTag(name) {
|
||
if (!globalParams.rdIndividuals) return;
|
||
globalParams.rdIndividuals = globalParams.rdIndividuals.filter(n => n !== name);
|
||
saveAndRefresh();
|
||
}
|
||
|
||
function renderRoleStats(data) {
|
||
const statsEl = document.getElementById('role-stats');
|
||
if (!statsEl) return;
|
||
|
||
const total = data.length;
|
||
const roles = {
|
||
'🎨 藝術家': { count: 0, color: 'var(--accent-primary)' },
|
||
'💼 專案管理': { count: 0, color: 'var(--accent-secondary)' },
|
||
'🏢 特約外包': { count: 0, color: 'var(--accent-warning)' }
|
||
};
|
||
|
||
const durations = {
|
||
'📅 12個月 (全年度)': { count: 0, color: 'var(--accent-success)' },
|
||
'⏳ 低於 12個月': { count: 0, color: 'var(--accent-warning)' }
|
||
};
|
||
|
||
data.forEach(p => {
|
||
// Role grouping
|
||
if (p.role.startsWith('A')) roles['🎨 藝術家'].count++;
|
||
else if (p.role.startsWith('P')) roles['💼 專案管理'].count++;
|
||
else if (p.role.startsWith('O')) roles['🏢 特約外包'].count++;
|
||
|
||
// Duration grouping
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
const months = m1 + m2;
|
||
|
||
if (months === 12) durations['📅 12個月 (全年度)'].count++;
|
||
else durations['⏳ 低於 12個月'].count++;
|
||
});
|
||
|
||
const renderBarList = (title, items) => {
|
||
let html = `<div style="margin-bottom: 1.5rem;">
|
||
<h4 style="font-size: 0.8rem; color: var(--text-dim); margin-bottom: 1rem; text-transform: uppercase; letter-spacing: 1px;">${title}</h4>`;
|
||
|
||
Object.entries(items).forEach(([label, info]) => {
|
||
const pct = total === 0 ? 0 : (info.count / total * 100);
|
||
html += `
|
||
<div style="margin-bottom: 0.75rem;">
|
||
<div style="display:flex; justify-content:space-between; margin-bottom: 4px; font-size: 0.8rem;">
|
||
<span style="color: var(--text-main);">${label}</span>
|
||
<span style="color: var(--text-muted);">${info.count} 人 (${formatPct(pct)}%)</span>
|
||
</div>
|
||
<div style="height: 5px; background: rgba(255,255,255,0.03); border-radius: 3px; overflow:hidden;">
|
||
<div style="width: ${pct}%; height:100%; background: ${info.color};"></div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
html += '</div>';
|
||
return html;
|
||
};
|
||
|
||
statsEl.innerHTML = renderBarList('職能類別 (Role)', roles) + renderBarList('合約期間 (Duration)', durations);
|
||
}
|
||
|
||
function renderGroup() {
|
||
const current = isSimMode ? simData : baseData;
|
||
const { deptStats } = calculateAll(current);
|
||
const tbody = document.querySelector('#group-table tbody');
|
||
tbody.innerHTML = '';
|
||
|
||
// Group by Dept + Group Name
|
||
const groups = {};
|
||
current.forEach(p => {
|
||
const key = `${p.dept}|${p.group || '未分組'}`;
|
||
if (!groups[key]) groups[key] = { dept: p.dept, group: p.group || '未分組', personnel: 0, cost: 0 };
|
||
groups[key].personnel++;
|
||
groups[key].cost += (p.totalCost || 0);
|
||
});
|
||
|
||
Object.values(groups).sort((a, b) => b.cost - a.cost).forEach(g => {
|
||
const deptCoda = deptStats[g.dept]?.rawDt || 0;
|
||
const impact = deptCoda === 0 ? 0 : (g.cost / deptCoda * 100);
|
||
tbody.innerHTML += `
|
||
<tr>
|
||
<td>${g.dept}</td>
|
||
<td>${g.group}</td>
|
||
<td>${g.personnel} 人</td>
|
||
<td style="color: var(--accent-primary); font-weight:700;">$${g.cost.toLocaleString()}</td>
|
||
<td>
|
||
<div style="display:flex; align-items:center; gap: 10px;">
|
||
<div style="flex-grow:1; height:6px; background:rgba(255,255,255,0.05); border-radius:3px;">
|
||
<div style="width:${impact}%; height:100%; background:var(--accent-secondary);"></div>
|
||
</div>
|
||
<span style="font-size:0.8rem; min-width:40px;">${formatPct(impact)}%</span>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
`;
|
||
});
|
||
}
|
||
|
||
function renderSales() {
|
||
initOrgStructure();
|
||
const current = isSimMode ? simData : baseData;
|
||
calculateAll(current);
|
||
const container = document.getElementById('sales-content');
|
||
|
||
// 1. Filter: Role starts with P, Exclude pcDept, and Must be in valid Business Depts
|
||
const targetDepts = Object.keys(globalParams.orgStructure);
|
||
const pPeople = current.filter(p => p.role.startsWith('P') && targetDepts.includes(p.dept));
|
||
|
||
// 2. Calculations
|
||
let grandTotal = 0;
|
||
const depts = {};
|
||
|
||
const processed = pPeople.map(p => {
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
const months = m1 + m2;
|
||
const salary = parseFloat(p.salary) || 0;
|
||
|
||
let workRate = 1.0;
|
||
const isPC = p.title.includes('PC');
|
||
|
||
if (p.isManager) {
|
||
// Manager rate overrides (or applies as) the main factor
|
||
workRate = globalParams.pManagerReductionPct !== undefined ? globalParams.pManagerReductionPct : 0.6;
|
||
} else if (isPC) {
|
||
workRate = globalParams.pPCReductionPct !== undefined ? globalParams.pPCReductionPct : 0.7; // PC fixed rate
|
||
}
|
||
|
||
const yearlyCost = p.realSalaryTotal * workRate;
|
||
|
||
grandTotal += yearlyCost;
|
||
|
||
const groupName = p.group || '未分組';
|
||
|
||
// Check if group is valid in orgStructure
|
||
const isValidGroup = globalParams.orgStructure[p.dept]?.includes(groupName);
|
||
const assignedGroup = isValidGroup ? groupName : '未分組 (需由管理清單指派)';
|
||
|
||
if (!depts[p.dept]) depts[p.dept] = { name: p.dept, total: 0, groups: {} };
|
||
if (!depts[p.dept].groups[assignedGroup]) {
|
||
depts[p.dept].groups[assignedGroup] = { name: assignedGroup, total: 0, people: [] };
|
||
}
|
||
|
||
depts[p.dept].total += yearlyCost;
|
||
depts[p.dept].groups[assignedGroup].total += yearlyCost;
|
||
|
||
const processedPerson = { ...p, yearlyCost, workRate };
|
||
depts[p.dept].groups[assignedGroup].people.push(processedPerson);
|
||
|
||
return processedPerson;
|
||
});
|
||
|
||
// Update Grand Total UI
|
||
document.getElementById('sales-grand-total').innerText = `NT$ ${grandTotal.toLocaleString()}`;
|
||
|
||
// 3. Render Tables Grouped by Dept
|
||
container.innerHTML = '';
|
||
Object.keys(globalParams.orgStructure).forEach(deptName => { // Iterate over predefined order
|
||
const dept = depts[deptName];
|
||
if (!dept) return; // Skip if department has no P people
|
||
|
||
const deptPct = grandTotal === 0 ? 0 : (dept.total / grandTotal * 100);
|
||
const safeDeptId = dept.name.replace(/\s+/g, '-');
|
||
const totalPeople = Object.values(dept.groups).reduce((acc, g) => acc + g.people.length, 0);
|
||
|
||
let deptHtml = `
|
||
<div class="card" style="margin-bottom: 1.5rem; padding: 0;">
|
||
<!-- Clikable Header -->
|
||
<div onclick="toggleSalesDept('${safeDeptId}')" style="cursor: pointer; padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; transition: background 0.2s;" onmouseover="this.style.background='var(--bg-glass)'" onmouseout="this.style.background='transparent'">
|
||
<div style="display: flex; align-items: center; gap: 2rem; flex-grow: 1;">
|
||
<h3 style="color: var(--accent-secondary); margin: 0; min-width: 200px;">${dept.name}</h3>
|
||
<div style="min-width: 80px; text-align: left;">
|
||
<span style="font-size: 0.85rem; color: var(--text-muted); background: rgba(255,255,255,0.05); padding: 4px 10px; border-radius: 99px;">${totalPeople} 人</span>
|
||
</div>
|
||
<div style="display: flex; flex-direction: column; min-width: 300px; text-align: left;">
|
||
<div style="font-size: 1.1rem; font-weight: 700; color: var(--text-main);">
|
||
NT$ ${dept.total.toLocaleString()}
|
||
</div>
|
||
<div style="font-size: 0.85rem; color: var(--accent-warning);">
|
||
佔總 P 預算 ${formatPct(deptPct)}%
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div id="sales-chevron-${safeDeptId}" style="color: var(--text-muted); transition: transform 0.3s;">▼</div>
|
||
</div>
|
||
|
||
<!-- Togglable Detail Table -->
|
||
<div id="sales-detail-${safeDeptId}" style="display: none; padding: 0 0 1.5rem 0; border-top: 1px solid var(--border-glass); margin-top: 0.5rem; animation: fadeIn 0.3s ease-out;">
|
||
<div style="padding-top: 1rem; margin-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05); padding-left: 1.5rem; padding-right: 1.5rem;">
|
||
`;
|
||
|
||
// Render Groups within the Department
|
||
Object.values(dept.groups).sort((a, b) => b.total - a.total).forEach(group => {
|
||
const safeGroupId = 'sales-group-' + dept.name.replace(/\s+/g, '-') + '-' + group.name.replace(/\s+/g, '-');
|
||
const groupPct = dept.total === 0 ? 0 : (group.total / dept.total * 100);
|
||
|
||
deptHtml += `
|
||
<div class="card" style="margin-bottom: 1rem; padding: 0; background: rgba(0,0,0,0.2); border-color: rgba(255,255,255,0.05); border-radius: 0; border-left: none; border-right: none;">
|
||
<!-- Clikable Group Header -->
|
||
<div onclick="toggleSalesGroup('${safeGroupId}')" style="cursor: pointer; padding: 1rem 1.5rem; display: flex; justify-content: space-between; align-items: center; transition: background 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.05)'" onmouseout="this.style.background='transparent'">
|
||
<div style="display: flex; align-items: center; gap: 2rem; flex-grow: 1;">
|
||
<h4 style="color: var(--text-main); margin: 0; min-width: 200px;">${group.name}</h4>
|
||
<div style="min-width: 80px; text-align: left;">
|
||
<span style="font-size: 0.8rem; color: var(--text-dim); background: rgba(255,255,255,0.03); padding: 2px 8px; border-radius: 99px;">${group.people.length} 人</span>
|
||
</div>
|
||
<div style="display: flex; flex-direction: column; min-width: 300px; text-align: left;">
|
||
<div style="font-size: 1rem; font-weight: 700; color: var(--accent-warning);">
|
||
NT$ ${group.total.toLocaleString()}
|
||
</div>
|
||
<div style="font-size: 0.85rem; color: var(--accent-warning);">
|
||
佔部總額 ${formatPct(groupPct)}%
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div id="sales-group-chevron-${safeGroupId}" style="color: var(--text-dim); transition: transform 0.3s; font-size: 0.8rem;">▼</div>
|
||
</div>
|
||
|
||
<!-- Togglable Group Detail Table -->
|
||
<div id="sales-group-detail-${safeGroupId}" style="display: none; padding: 0 1.5rem 1.5rem 1.5rem;">
|
||
<div class="table-container" style="border: none; margin-top: 0;">
|
||
<table style="background: transparent;">
|
||
<thead>
|
||
<tr>
|
||
<th>姓名</th>
|
||
<th>職稱</th>
|
||
<th>職能</th>
|
||
<th class="num">月薪</th>
|
||
<th class="num">H1 起</th>
|
||
<th class="num">H1 迄</th>
|
||
<th class="num">H2 起</th>
|
||
<th class="num">H2 迄</th>
|
||
<th class="num">管理率</th>
|
||
<th>狀態</th>
|
||
<th class="num">年度預算估計</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
`;
|
||
|
||
// Sort people in group by yearlyCost desc
|
||
group.people.sort((a, b) => (b.yearlyCost || 0) - (a.yearlyCost || 0)).forEach(p => {
|
||
const nameDisplay = p.isManager
|
||
? `${p.name} <span style="font-size:0.7rem; color:var(--accent-warning); font-weight:700; background:rgba(245,158,11,0.1); padding:2px 4px; border-radius:4px; margin-left:4px;">主管</span>`
|
||
: p.name;
|
||
|
||
deptHtml += `
|
||
<tr>
|
||
<td>${nameDisplay}</td>
|
||
<td>${p.title || ''}</td>
|
||
<td><span class="role-pill role-p">${p.role.split(' - ')[0]}</span></td>
|
||
<td class="num">$${(parseFloat(p.salary) || 0).toLocaleString()}</td>
|
||
<td class="num">${p.h1Start || '-'}</td>
|
||
<td class="num">${p.h1End || '-'}</td>
|
||
<td class="num">${p.h2Start || '-'}</td>
|
||
<td class="num">${p.h2End || '-'}</td>
|
||
<td class="num" style="${p.workRate !== 1.0 ? 'color: var(--accent-warning); font-weight: 700;' : ''}">${p.workRate.toFixed(2)}</td>
|
||
<td class="num">${getStatusBadge(p)}</td>
|
||
<td class="num" style="color: var(--accent-primary); font-weight: 700;">$${p.yearlyCost.toLocaleString()}</td>
|
||
</tr>
|
||
`;
|
||
});
|
||
|
||
deptHtml += `
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
deptHtml += `
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
container.innerHTML += deptHtml;
|
||
});
|
||
}
|
||
|
||
function toggleSalesDept(deptId) {
|
||
const detailView = document.getElementById(`sales-detail-${deptId}`);
|
||
const chevron = document.getElementById(`sales-chevron-${deptId}`);
|
||
|
||
if (detailView.style.display === 'none') {
|
||
detailView.style.display = 'block';
|
||
chevron.style.transform = 'rotate(180deg)';
|
||
chevron.style.color = 'var(--accent-primary)';
|
||
} else {
|
||
detailView.style.display = 'none';
|
||
chevron.style.transform = 'rotate(0deg)';
|
||
chevron.style.color = 'var(--text-muted)';
|
||
}
|
||
}
|
||
|
||
function toggleSalesGroup(groupId) {
|
||
const detailView = document.getElementById(`sales-group-detail-${groupId}`);
|
||
const chevron = document.getElementById(`sales-group-chevron-${groupId}`);
|
||
|
||
if (detailView.style.display === 'none') {
|
||
detailView.style.display = 'block';
|
||
chevron.style.transform = 'rotate(180deg)';
|
||
} else {
|
||
detailView.style.display = 'none';
|
||
chevron.style.transform = 'rotate(0deg)';
|
||
}
|
||
}
|
||
|
||
|
||
function renderArtists() {
|
||
initOrgStructure();
|
||
const current = isSimMode ? simData : baseData;
|
||
calculateAll(current);
|
||
const container = document.getElementById('artists-content');
|
||
|
||
// 1. Filter: Valid Depts from OrgStructure + Role A or O
|
||
const targetDepts = Object.keys(globalParams.orgStructure);
|
||
const targetPeople = current.filter(p =>
|
||
targetDepts.includes(p.dept) &&
|
||
(p.role.startsWith('A') || p.role.startsWith('O'))
|
||
);
|
||
|
||
// 2. Calculations
|
||
let grandTotal = 0; // Raw in-house artist total for business depts
|
||
let grandOutsourceTotal = 0;
|
||
const depts = {};
|
||
|
||
targetPeople.forEach(p => {
|
||
const cost = p.totalCost || 0;
|
||
const isOutsource = p.role.startsWith('O');
|
||
const deptName = p.dept;
|
||
const groupName = p.group || '未分組';
|
||
|
||
// Check if group is valid in orgStructure
|
||
const isValidGroup = globalParams.orgStructure[deptName]?.includes(groupName);
|
||
const assignedGroup = isValidGroup ? groupName : '未分組 (需由管理清單指派)';
|
||
|
||
if (!depts[deptName]) depts[deptName] = { name: deptName, total: 0, outsourceTotal: 0, groups: {} };
|
||
if (!depts[deptName].groups[assignedGroup]) {
|
||
depts[deptName].groups[assignedGroup] = { name: assignedGroup, total: 0, outsourceTotal: 0, people: [] };
|
||
}
|
||
|
||
if (!isOutsource) {
|
||
grandTotal += cost;
|
||
depts[deptName].total += cost;
|
||
depts[deptName].groups[assignedGroup].total += cost;
|
||
} else {
|
||
grandOutsourceTotal += cost;
|
||
depts[deptName].outsourceTotal += cost;
|
||
depts[deptName].groups[assignedGroup].outsourceTotal += cost;
|
||
}
|
||
depts[deptName].groups[assignedGroup].people.push(p);
|
||
});
|
||
|
||
// Get PC Adjusted Total from stats
|
||
const { deptStats } = calculateAll(current);
|
||
const pcAdjustedTotal = deptStats[globalParams.pcDept]?.dt || 0;
|
||
|
||
// Update Grand Total UI
|
||
document.getElementById('artists-grand-total').innerHTML = `
|
||
NT$ ${Math.ceil(grandTotal + pcAdjustedTotal).toLocaleString()}
|
||
${grandOutsourceTotal > 0 ? `<br><span style="font-size: 0.5em; color: var(--accent-warning);font-weight: 500;">+ 外包 NT$ ${grandOutsourceTotal.toLocaleString()}</span>` : ''}
|
||
`;
|
||
|
||
// 3. Render
|
||
container.innerHTML = '';
|
||
Object.keys(globalParams.orgStructure).forEach(deptName => { // Iterate over predefined order
|
||
const dept = depts[deptName];
|
||
if (!dept) return; // Skip if department has no A/O people
|
||
|
||
const safeDeptId = 'artist-' + dept.name.replace(/\s+/g, '-');
|
||
const totalPeople = Object.values(dept.groups).reduce((acc, g) => acc + g.people.length, 0);
|
||
const deptPct = grandTotal === 0 ? 0 : (dept.total / grandTotal);
|
||
const deptAllocation = pcAdjustedTotal * deptPct;
|
||
const deptCombined = dept.total + deptAllocation;
|
||
|
||
// --- R&D Redistribution Logic ---
|
||
const rdReductionPct = globalParams.rdReductionPct ?? 0.35;
|
||
const rdGroups = globalParams.rdGroups || [];
|
||
|
||
// Calculate temporary combined totals for each group within this dept
|
||
const groupProcessed = Object.values(dept.groups).map(g => {
|
||
const groupPctOfGrand = grandTotal === 0 ? 0 : (g.total / grandTotal);
|
||
const groupCombined = g.total + (pcAdjustedTotal * groupPctOfGrand);
|
||
const isRD = rdGroups.includes(`${dept.name}|${g.name}`);
|
||
return { ...g, combined: groupCombined, isRD };
|
||
});
|
||
|
||
const totalRDTax = groupProcessed.filter(g => g.isRD).reduce((acc, g) => acc + (g.combined * rdReductionPct), 0);
|
||
const normalGroupsTotal = groupProcessed.filter(g => !g.isRD).reduce((acc, g) => acc + g.combined, 0);
|
||
|
||
groupProcessed.forEach(g => {
|
||
if (g.isRD) {
|
||
g.finalCombined = g.combined * (1 - rdReductionPct);
|
||
g.rdNote = `研發釋出 -${formatPct(rdReductionPct * 100)}%`;
|
||
} else {
|
||
const shareOfNormal = normalGroupsTotal === 0 ? 0 : (g.combined / normalGroupsTotal);
|
||
g.finalCombined = g.combined + (totalRDTax * shareOfNormal);
|
||
if (totalRDTax > 0) g.rdNote = `分攤研製預算`;
|
||
}
|
||
});
|
||
|
||
let deptHtml = `
|
||
<div class="card" style="margin-bottom: 2rem; padding: 0;">
|
||
<!-- Clikable Header -->
|
||
<div onclick="toggleArtistsDept('${safeDeptId}')" style="cursor: pointer; padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; transition: background 0.2s;" onmouseover="this.style.background='var(--bg-glass)'" onmouseout="this.style.background='transparent'">
|
||
<div style="display: flex; align-items: center; gap: 2rem; flex-grow: 1;">
|
||
<h3 style="color: var(--accent-primary); margin: 0; min-width: 200px; text-align: left;">${dept.name}</h3>
|
||
<div style="min-width: 80px; text-align: left;">
|
||
<span style="font-size: 0.85rem; color: var(--text-muted); background: rgba(255,255,255,0.05); padding: 4px 12px; border-radius: 99px;">${totalPeople} 人</span>
|
||
</div>
|
||
<div style="display: flex; flex-direction: column; min-width: 300px; text-align: left;">
|
||
<div style="font-size: 1.25rem; font-weight: 800; color: var(--text-main);">
|
||
NT$ ${Math.ceil(deptCombined).toLocaleString()}
|
||
<span style="font-size: 0.9rem; color: var(--accent-success); font-weight: 600; margin-left: 10px;">
|
||
(佔比 ${formatPct(deptPct * 100)}%)
|
||
</span>
|
||
</div>
|
||
<div style="font-size: 0.85rem; color: var(--text-dim); font-weight: 400;">
|
||
原始加總:NT$ ${dept.total.toLocaleString()} (未分攤)
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div style="display: flex; align-items: center; gap: 1rem;">
|
||
${dept.outsourceTotal > 0 ? `<div style="font-size: 0.85rem; color: var(--accent-warning); font-weight: 600;">+ 外包 NT$ ${dept.outsourceTotal.toLocaleString()}</div>` : ''}
|
||
<div id="artists-chevron-${safeDeptId}" style="color: var(--text-muted); transition: transform 0.3s;">▼</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Togglable Detail Table -->
|
||
<div id="artists-detail-${safeDeptId}" style="display: none; padding: 0 0 1.5rem 0; border-top: 1px solid var(--border-glass); margin-top: 0.5rem; animation: fadeIn 0.3s ease-out;">
|
||
<div style="padding-top: 1rem; margin-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05); padding-left: 1.5rem; padding-right: 1.5rem;">
|
||
`;
|
||
|
||
// Render Groups within the Department
|
||
groupProcessed.sort((a, b) => b.finalCombined - a.finalCombined).forEach(group => {
|
||
const safeGroupId = 'artist-group-' + dept.name.replace(/\s+/g, '-') + '-' + group.name.replace(/\s+/g, '-');
|
||
const groupPctOfGrand = grandTotal === 0 ? 0 : (group.total / grandTotal);
|
||
|
||
deptHtml += `
|
||
<div class="card" style="margin-bottom: 1rem; padding: 0; background: rgba(0,0,0,0.2); border-color: rgba(255,255,255,0.05); border-radius: 0; border-left: none; border-right: none;">
|
||
<!-- Clikable Group Header -->
|
||
<div onclick="toggleArtistsGroup('${safeGroupId}')" style="cursor: pointer; padding: 1rem 1.5rem; display: flex; justify-content: space-between; align-items: center; transition: background 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.05)'" onmouseout="this.style.background='transparent'">
|
||
<div style="display: flex; align-items: center; gap: 2rem; flex-grow: 1;">
|
||
<h4 style="color: var(--text-main); margin: 0; min-width: 200px; text-align: left;">${group.name}</h4>
|
||
<div style="min-width: 80px; text-align: left;">
|
||
<span style="font-size: 0.8rem; color: var(--text-dim); background: rgba(255,255,255,0.03); padding: 2px 8px; border-radius: 99px;">${group.people.length} 人</span>
|
||
</div>
|
||
<div style="display:flex; flex-direction:column; min-width: 300px; text-align: left;">
|
||
<div style="font-size: 1.15rem; font-weight: 800; color: var(--accent-success);">
|
||
NT$ ${Math.ceil(group.finalCombined).toLocaleString()}
|
||
<span style="font-size: 0.8rem; color: var(--accent-success); opacity: 0.7; font-weight: 400; margin-left: 8px;">
|
||
(佔比 ${formatPct(groupPctOfGrand * 100)}%)
|
||
</span>
|
||
</div>
|
||
<div style="font-size: 0.8rem; color: var(--text-dim); font-weight: 400; display: flex; gap: 10px; align-items: center;">
|
||
<span>原始加總:NT$ ${group.total.toLocaleString()}</span>
|
||
${group.rdNote ? `<span style="background: ${group.isRD ? 'var(--accent-danger)' : 'var(--accent-primary)'}; color: white; padding: 0 6px; border-radius: 4px; font-size: 0.7rem;">${group.rdNote}</span>` : ''}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div style="display: flex; align-items: center; gap: 1rem;">
|
||
${group.outsourceTotal > 0 ? `<div style="font-size: 0.8rem; color: var(--accent-warning); font-weight: 600;">+ 外包 NT$ ${group.outsourceTotal.toLocaleString()}</div>` : ''}
|
||
<div id="artists-group-chevron-${safeGroupId}" style="color: var(--text-dim); transition: transform 0.3s; font-size: 0.8rem;">▼</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Togglable Group Detail Table -->
|
||
<div id="artists-group-detail-${safeGroupId}" style="display: none; padding: 0 1.5rem 1.5rem 1.5rem;">
|
||
<div class="table-container" style="border: none; margin-top: 0;">
|
||
<table style="background: transparent; table-layout: fixed; width: 100%;">
|
||
<colgroup>
|
||
<col style="width:90px">
|
||
<col style="width:100px">
|
||
<col style="width:60px">
|
||
<col style="width:90px">
|
||
<col style="width:52px">
|
||
<col style="width:52px">
|
||
<col style="width:52px">
|
||
<col style="width:52px">
|
||
<col style="width:55px">
|
||
<col style="width:100px">
|
||
<col style="width:120px">
|
||
</colgroup>
|
||
<thead>
|
||
<tr>
|
||
<th style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">姓名</th>
|
||
<th style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">職稱</th>
|
||
<th>職能</th>
|
||
<th class="num">月/日薪</th>
|
||
<th class="num">H1 起</th>
|
||
<th class="num">H1 迄</th>
|
||
<th class="num">H2 起</th>
|
||
<th class="num">H2 迄</th>
|
||
<th class="num">工作率</th>
|
||
<th class="num">狀態</th>
|
||
<th class="num">年度總成本</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
`;
|
||
|
||
// Sort people in group by TotalCost desc
|
||
group.people.sort((a, b) => (b.totalCost || 0) - (a.totalCost || 0)).forEach(p => {
|
||
const isOutsource = p.role.includes('O');
|
||
const salaryPrefix = isOutsource ? '日 $' : '$';
|
||
const salaryVal = isOutsource ? p.dayrate : p.salary;
|
||
|
||
deptHtml += `
|
||
<tr>
|
||
<td style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${p.name}">${p.name}</td>
|
||
<td style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${p.title || ''}">${p.title || ''}</td>
|
||
<td><span class="role-pill ${isOutsource ? 'role-o' : 'role-a'}" style="font-size:0.7rem;padding:2px 6px;">${p.role.split(' - ')[0]}</span></td>
|
||
<td class="num" style="color:var(--text-muted); font-size:0.8rem;">${salaryPrefix}${(parseFloat(salaryVal) || 0).toLocaleString()}</td>
|
||
<td class="num">${p.h1Start || '-'}</td>
|
||
<td class="num">${p.h1End || '-'}</td>
|
||
<td class="num">${p.h2Start || '-'}</td>
|
||
<td class="num">${p.h2End || '-'}</td>
|
||
<td class="num">${p.workRateUsed || 1}</td>
|
||
<td class="num">${getStatusBadge(p)}</td>
|
||
<td class="num" style="color: var(--accent-primary); font-weight: 700;">$${(p.totalCost || 0).toLocaleString()}</td>
|
||
</tr>
|
||
`;
|
||
});
|
||
|
||
deptHtml += `
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
deptHtml += `
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
container.innerHTML += deptHtml;
|
||
});
|
||
|
||
// 4. Render Isolated "製程部" (Support Dept) at the bottom
|
||
const supportPeople = current.filter(p =>
|
||
p.dept === globalParams.pcDept &&
|
||
(p.role.startsWith('A') || p.role.startsWith('O'))
|
||
);
|
||
|
||
if (supportPeople.length > 0) {
|
||
let supportRawTotal = 0;
|
||
let supportOutsourceTotal = 0;
|
||
const supportGroups = {};
|
||
|
||
supportPeople.forEach(p => {
|
||
const cost = p.totalCost || 0;
|
||
const isOutsource = p.role.startsWith('O');
|
||
const groupName = p.group || '未分組';
|
||
|
||
if (!supportGroups[groupName]) {
|
||
supportGroups[groupName] = { name: groupName, rawTotal: 0, total: 0, outsourceTotal: 0, people: [] };
|
||
}
|
||
|
||
if (!isOutsource) {
|
||
supportRawTotal += cost;
|
||
supportGroups[groupName].rawTotal += cost;
|
||
} else {
|
||
supportOutsourceTotal += cost;
|
||
supportGroups[groupName].outsourceTotal += cost;
|
||
}
|
||
|
||
supportGroups[groupName].people.push(p);
|
||
});
|
||
|
||
const rate = (globalParams.supportConversionRate !== undefined) ? globalParams.supportConversionRate : 0.5;
|
||
const supportTotal = supportRawTotal * rate;
|
||
Object.values(supportGroups).forEach(g => {
|
||
g.total = g.rawTotal * rate;
|
||
});
|
||
|
||
const safeSupportId = 'artist-support';
|
||
|
||
let supportHtml = `
|
||
<div style="margin: 3rem 0 1.5rem 0; display: flex; align-items: center; gap: 1rem;">
|
||
<div style="flex-grow: 1; height: 1px; background: var(--border-glass);"></div>
|
||
<span style="color: var(--text-muted); font-size: 0.85rem; font-weight: 600;">支援成本明細(已分攤至上方部門,不重複加總)</span>
|
||
<div style="flex-grow: 1; height: 1px; background: var(--border-glass);"></div>
|
||
</div>
|
||
|
||
<div class="card" style="margin-bottom: 1.5rem; padding: 0; border-color: rgba(255,255,255,0.2);">
|
||
<!-- Clikable Header -->
|
||
<div onclick="toggleArtistsDept('${safeSupportId}')" style="cursor: pointer; padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; transition: background 0.2s;" onmouseover="this.style.background='var(--bg-glass)'" onmouseout="this.style.background='transparent'">
|
||
<div style="display: flex; align-items: center; gap: 2rem; flex-grow: 1;">
|
||
<h3 style="color: var(--text-muted); margin: 0; min-width: 200px; text-align: left;">${globalParams.pcDept}</h3>
|
||
<div style="min-width: 80px; text-align: left;">
|
||
<span style="font-size: 0.85rem; color: var(--text-dim); background: rgba(255,255,255,0.05); padding: 4px 12px; border-radius: 99px;">${supportPeople.length} 人</span>
|
||
</div>
|
||
<div style="display: flex; flex-direction: column; min-width: 300px; text-align: left;">
|
||
<div style="font-size: 1.1rem; font-weight: 700; color: var(--text-main);">
|
||
<span style="font-size: 0.8rem; color: var(--text-dim); font-weight: 400;">NT$ ${supportRawTotal.toLocaleString()} × ${rate} =</span>
|
||
NT$ ${supportTotal.toLocaleString()}
|
||
</div>
|
||
<div style="font-size: 0.85rem; color: var(--text-dim);">
|
||
部門藝術家年度總額
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div style="display: flex; align-items: center; gap: 1rem;">
|
||
${supportOutsourceTotal > 0 ? `<div style="font-size: 0.85rem; color: var(--accent-warning); font-weight: 600;">+ 外包 NT$ ${supportOutsourceTotal.toLocaleString()}</div>` : ''}
|
||
<div id="artists-chevron-${safeSupportId}" style="color: var(--text-dim); transition: transform 0.3s;">▼</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Togglable Detail Table -->
|
||
<div id="artists-detail-${safeSupportId}" style="display: none; padding: 0 0 1.5rem 0; border-top: 1px solid var(--border-glass); margin-top: 0.5rem; animation: fadeIn 0.3s ease-out;">
|
||
<div style="padding-top: 1rem; margin-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05); padding-left: 1.5rem; padding-right: 1.5rem;">
|
||
`;
|
||
|
||
// Render Groups within Support Dept
|
||
Object.values(supportGroups).sort((a, b) => b.total - a.total).forEach(group => {
|
||
const safeGroupId = 'artist-support-group-' + group.name.replace(/\s+/g, '-');
|
||
const groupPct = supportTotal === 0 ? 0 : (group.total / supportTotal * 100);
|
||
|
||
supportHtml += `
|
||
<div class="card" style="margin-bottom: 1rem; padding: 0; background: rgba(0,0,0,0.2); border-color: rgba(255,255,255,0.05); border-radius: 0; border-left: none; border-right: none;">
|
||
<!-- Clikable Group Header -->
|
||
<div onclick="toggleArtistsGroup('${safeGroupId}')" style="cursor: pointer; padding: 1rem 1.5rem; display: flex; justify-content: space-between; align-items: center; transition: background 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.05)'" onmouseout="this.style.background='transparent'">
|
||
<div style="display: flex; align-items: center; gap: 2rem; flex-grow: 1;">
|
||
<h4 style="color: var(--text-dim); margin: 0; min-width: 200px; text-align: left;">${group.name}</h4>
|
||
<div style="min-width: 80px; text-align: left;">
|
||
<span style="font-size: 0.8rem; color: var(--text-dim); background: rgba(255,255,255,0.03); padding: 2px 8px; border-radius: 99px;">${group.people.length} 人</span>
|
||
</div>
|
||
<div style="display: flex; flex-direction: column; min-width: 300px; text-align: left;">
|
||
<div style="font-size: 1rem; font-weight: 700; color: var(--text-main);">
|
||
<span style="font-size: 0.75rem; color: var(--text-dim); font-weight: 400;">$${group.rawTotal.toLocaleString()} × ${rate} =</span>
|
||
NT$ ${group.total.toLocaleString()}
|
||
</div>
|
||
<div style="font-size: 0.85rem; color: var(--text-dim);">
|
||
佔部總額 ${formatPct(groupPct)}%
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div style="display: flex; align-items: center; gap: 1rem;">
|
||
${group.outsourceTotal > 0 ? `<div style="font-size: 0.8rem; color: var(--accent-warning); font-weight: 600;">+ 外包 NT$ ${group.outsourceTotal.toLocaleString()}</div>` : ''}
|
||
<div id="artists-group-chevron-${safeGroupId}" style="color: var(--text-dim); transition: transform 0.3s; font-size: 0.8rem;">▼</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Togglable Group Detail Table -->
|
||
<div id="artists-group-detail-${safeGroupId}" style="display: none; padding: 0 1.5rem 1.5rem 1.5rem;">
|
||
<div class="table-container" style="border: none; margin-top: 0;">
|
||
<table style="background: transparent; table-layout: fixed; width: 100%;">
|
||
<colgroup>
|
||
<col style="width:90px">
|
||
<col style="width:100px">
|
||
<col style="width:60px">
|
||
<col style="width:90px">
|
||
<col style="width:52px">
|
||
<col style="width:52px">
|
||
<col style="width:52px">
|
||
<col style="width:52px">
|
||
<col style="width:55px">
|
||
<col style="width:100px">
|
||
<col style="width:120px">
|
||
</colgroup>
|
||
<thead>
|
||
<tr>
|
||
<th style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">姓名</th>
|
||
<th style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">職稱</th>
|
||
<th>職能</th>
|
||
<th class="num">月/日薪</th>
|
||
<th class="num">H1 起</th>
|
||
<th class="num">H1 迄</th>
|
||
<th class="num">H2 起</th>
|
||
<th class="num">H2 迄</th>
|
||
<th class="num">工作率</th>
|
||
<th class="num">狀態</th>
|
||
<th class="num">年度總成本</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
`;
|
||
|
||
group.people.sort((a, b) => (b.totalCost || 0) - (a.totalCost || 0)).forEach(p => {
|
||
const isOutsource = p.role.includes('O');
|
||
const salaryPrefix = isOutsource ? '日 $' : '$';
|
||
const salaryVal = isOutsource ? p.dayrate : p.salary;
|
||
|
||
supportHtml += `
|
||
<tr>
|
||
<td style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${p.name}">${p.name}</td>
|
||
<td style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${p.title || ''}">${p.title || ''}</td>
|
||
<td><span class="role-pill ${isOutsource ? 'role-o' : 'role-a'}" style="font-size:0.7rem;padding:2px 6px;">${p.role.split(' - ')[0]}</span></td>
|
||
<td class="num" style="color:var(--text-muted); font-size:0.8rem;">${salaryPrefix}${(parseFloat(salaryVal) || 0).toLocaleString()}</td>
|
||
<td class="num">${p.h1Start || '-'}</td>
|
||
<td class="num">${p.h1End || '-'}</td>
|
||
<td class="num">${p.h2Start || '-'}</td>
|
||
<td class="num">${p.h2End || '-'}</td>
|
||
<td class="num">${p.workRateUsed || 1}</td>
|
||
<td class="num">${getStatusBadge(p)}</td>
|
||
<td class="num" style="color: var(--accent-primary); font-weight: 700;">$${(p.totalCost || 0).toLocaleString()}</td>
|
||
</tr>
|
||
`;
|
||
});
|
||
|
||
supportHtml += `
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
supportHtml += `
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
container.innerHTML += supportHtml;
|
||
}
|
||
}
|
||
|
||
function toggleArtistsDept(deptId) {
|
||
const detailView = document.getElementById(`artists-detail-${deptId}`);
|
||
const chevron = document.getElementById(`artists-chevron-${deptId}`);
|
||
|
||
if (detailView.style.display === 'none') {
|
||
detailView.style.display = 'block';
|
||
chevron.style.transform = 'rotate(180deg)';
|
||
chevron.style.color = 'var(--accent-primary)';
|
||
} else {
|
||
detailView.style.display = 'none';
|
||
chevron.style.transform = 'rotate(0deg)';
|
||
chevron.style.color = 'var(--text-muted)';
|
||
}
|
||
}
|
||
|
||
function toggleArtistsGroup(groupId) {
|
||
const detailView = document.getElementById(`artists-group-detail-${groupId}`);
|
||
const chevron = document.getElementById(`artists-group-chevron-${groupId}`);
|
||
|
||
if (detailView.style.display === 'none') {
|
||
detailView.style.display = 'block';
|
||
chevron.style.transform = 'rotate(180deg)';
|
||
} else {
|
||
detailView.style.display = 'none';
|
||
chevron.style.transform = 'rotate(0deg)';
|
||
}
|
||
}
|
||
|
||
function updateGlobalParam(key, val) {
|
||
const parsed = Number(val);
|
||
if (!Number.isFinite(parsed) || parsed < 0 ||
|
||
(['grossMarginPct', 'utilizationP', 'utilizationA', 'annualWorkDays', 'workingDays'].includes(key) && parsed === 0)) {
|
||
alert('請輸入有效數值;工作天數、產出率與毛利率必須大於零。');
|
||
renderParams();
|
||
return;
|
||
}
|
||
globalParams[key] = parsed;
|
||
saveAndRefresh();
|
||
}
|
||
|
||
function getStatusBadge(p) {
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
const months = m1 + m2;
|
||
|
||
if (months === 12) {
|
||
return '<span class="status-pill status-active">在職 (12m)</span>';
|
||
} else if (months === 0) {
|
||
return '<span class="status-pill status-resign">未安排 (0m)</span>';
|
||
} else {
|
||
return `<span class="status-pill status-temp">非滿年度 (${months}m)</span>`;
|
||
}
|
||
}
|
||
|
||
function renderPersonnel() {
|
||
initOrgStructure(); // Ensure org structure is initialized
|
||
const currentRaw = isSimMode ? simData : baseData;
|
||
const tbody = document.querySelector('#person-table tbody');
|
||
const searchQuery = document.getElementById('personnel-search').value.toLowerCase();
|
||
const deptFilter = document.getElementById('personnel-dept-filter').value;
|
||
const groupFilter = document.getElementById('personnel-group-filter').value;
|
||
populateCompanyFilter({ keepSelection: true });
|
||
const companyFilter = document.getElementById('personnel-company-filter')?.value || 'all';
|
||
|
||
// Update Sort Icons
|
||
document.querySelectorAll('.sort-icon').forEach(el => {
|
||
const field = el.id.replace('sort-', '');
|
||
if (field === sortConfig.field) {
|
||
el.innerText = sortConfig.direction === 'asc' ? '▲' : '▼';
|
||
el.parentElement.classList.add('active-sort');
|
||
} else {
|
||
el.innerText = '';
|
||
el.parentElement.classList.remove('active-sort');
|
||
}
|
||
});
|
||
|
||
// 1. Filter
|
||
let filtered = currentRaw.filter(p => {
|
||
const matchesSearch = p.name.toLowerCase().includes(searchQuery) || (p.title || '').toLowerCase().includes(searchQuery);
|
||
const matchesDept = deptFilter === 'all' || p.dept === deptFilter || (deptFilter === '其他' && !Object.keys(globalParams.orgStructure).includes(p.dept) && p.dept !== globalParams.pcDept);
|
||
const matchesGroup = groupFilter === 'all' || p.group === groupFilter || (groupFilter === '未分組' && !p.group);
|
||
return matchesPersonnelCategory(p) && matchesSearch && matchesCompany(p, companyFilter) && matchesDept && matchesGroup;
|
||
});
|
||
|
||
// 2. Sort
|
||
filtered.sort((a, b) => {
|
||
let valA = a[sortConfig.field];
|
||
let valB = b[sortConfig.field];
|
||
|
||
// Handle numbers
|
||
if (['salary', 'dayrate', 'h1Start', 'h1End', 'totalCost'].includes(sortConfig.field)) {
|
||
valA = parseFloat(valA) || 0;
|
||
valB = parseFloat(valB) || 0;
|
||
// salary logic: if role is outsource, use dayrate
|
||
if (sortConfig.field === 'salary') {
|
||
valA = a.role.includes('O') ? parseFloat(a.dayrate || 0) : parseFloat(a.salary || 0);
|
||
valB = b.role.includes('O') ? parseFloat(b.dayrate || 0) : parseFloat(b.salary || 0);
|
||
}
|
||
} else {
|
||
valA = (valA || "").toString().toLowerCase();
|
||
valB = (valB || "").toString().toLowerCase();
|
||
}
|
||
|
||
if (valA < valB) return sortConfig.direction === 'asc' ? -1 : 1;
|
||
if (valA > valB) return sortConfig.direction === 'asc' ? 1 : -1;
|
||
return 0;
|
||
});
|
||
|
||
tbody.innerHTML = '';
|
||
if (!filtered.length) tbody.innerHTML = '<tr><td colspan="16" style="text-align:center; padding:2rem;">沒有符合條件的人員,可調整篩選或新增。</td></tr>';
|
||
|
||
let totalCosts = { pa: 0, o: 0, all: 0 };
|
||
|
||
filtered.forEach((p) => {
|
||
// Find original index in currentRaw for updates/deletes
|
||
const origIdx = currentRaw.indexOf(p);
|
||
const roleClass = p.role.includes('A') ? 'role-a' : (p.role.includes('P') ? 'role-p' : 'role-o');
|
||
const isOutsource = p.role.includes('O');
|
||
|
||
// Track costs for KPI
|
||
const pCost = p.totalCost || 0;
|
||
totalCosts.all += pCost;
|
||
if (isOutsource) totalCosts.o += pCost;
|
||
else totalCosts.pa += pCost;
|
||
|
||
const isHourly = p.salaryType === 'hourly';
|
||
const salaryField = isOutsource ? 'dayrate' : 'salary';
|
||
const salaryPrefix = isOutsource ? '日 $' : isHourly ? '時 $' : '$';
|
||
const salaryVal = isOutsource ? p.dayrate : isHourly ? p.hourlyRate : p.salary;
|
||
const isHrPerson = p.source === 'hr-sync';
|
||
const safeName = escapeHtml(p.name);
|
||
const safeTitle = escapeHtml(p.title || '');
|
||
const safeDept = escapeHtml(p.dept || '');
|
||
const safeGroup = escapeHtml(p.group || '');
|
||
const classification = isHrPerson && !p.calculationReady
|
||
? `<div style="font-size:.72rem;color:var(--accent-warning);margin-top:.35rem;white-space:nowrap;">${escapeHtml(p.calculationIssue || '待確認')}</div>` : '';
|
||
const roleInput = isHrPerson ? `<select onchange="updatePerson(${origIdx}, 'role', this.value)" style="width:90px;">
|
||
<option value="" ${!isCalculationRole(p.role) ? 'selected' : ''}>待分類</option>
|
||
<option value="P - 製作" ${p.role === 'P - 製作' ? 'selected' : ''}>P</option>
|
||
<option value="A - 藝術家" ${p.role === 'A - 藝術家' ? 'selected' : ''}>A</option>
|
||
</select>` : `<span class="role-pill ${roleClass}">${escapeHtml((p.role || '').split(' - ')[0])}</span>`;
|
||
const salaryControl = isHrPerson
|
||
? `<span title="由 HR Sync 提供,目前不可在試算頁覆寫">${salaryPrefix}${(parseFloat(salaryVal) || 0).toLocaleString()}</span>`
|
||
: `<div style="display:flex; align-items:center; justify-content: flex-end;"><span style="font-size:0.75rem; color:var(--text-dim); margin-right:2px;">${salaryPrefix}</span><input type="number" style="text-align:right; width: 85px;" value="${salaryVal}" onchange="updatePerson(${origIdx}, '${salaryField}', this.value)"></div>`;
|
||
const weeklyDays = isHrPerson && isHourly
|
||
? `<input type="number" min="1" max="5" value="${Math.min(5, Math.max(1, Number(p.weeklyWorkDays) || 5))}" onchange="updatePerson(${origIdx}, 'weeklyWorkDays', this.value)" class="input-mini" style="width:38px;">`
|
||
: '—';
|
||
|
||
const statusHtml = getStatusBadge(p);
|
||
|
||
tbody.innerHTML += `
|
||
<tr>
|
||
<td style="white-space:nowrap;" title="${escapeHtml(p.company || '')}">${escapeHtml(shortCompanyName(p.company)) || '<span style="color:var(--text-dim);">未指定</span>'}</td>
|
||
<td>${isHrPerson ? safeName : `<input value="${safeName}" onchange="updatePerson(${origIdx}, 'name', this.value)" style="width: 75px;">`}</td>
|
||
<td>${isHrPerson ? safeTitle : `<input value="${safeTitle}" onchange="updatePerson(${origIdx}, 'title', this.value)" style="width: 85px;">`}</td>
|
||
<td><input value="${safeDept}" onchange="updatePerson(${origIdx}, 'dept', this.value)" style="width: 65px;"><br>${isHrPerson ? `<button class="link-button" onclick="clearHrOverride(${origIdx}, 'dept')">跟隨 HR</button>` : ''}</td>
|
||
<td><input value="${safeGroup}" onchange="updatePerson(${origIdx}, 'group', this.value)" style="width: 135px;" title="${safeGroup}"><br>${isHrPerson ? `<button class="link-button" onclick="clearHrOverride(${origIdx}, 'group')">跟隨 HR</button>` : ''}</td>
|
||
<td>${roleInput}${classification}</td>
|
||
<td style="text-align:center;"><input type="checkbox" ${p.isManager ? 'checked' : ''} onchange="updatePerson(${origIdx}, 'isManager', this.checked)" style="cursor: pointer; width: 14px; height: 14px; margin: 0; background: transparent;" title="${p.managerClassification === 'pending' ? '尚未確認是否為管理職' : '已人工確認'}">${isHrPerson && p.managerClassification === 'pending' ? '<div style="font-size:.68rem;color:var(--accent-warning);margin-top:.25rem;white-space:nowrap;">待確認</div>' : ''}</td>
|
||
<td class="num">${salaryControl}</td>
|
||
<td class="num">${weeklyDays}</td>
|
||
<td class="num"><input type="number" min="1" max="6" value="${p.h1Start || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h1Start', this.value)" class="input-mini" style="width: 38px;"></td>
|
||
<td class="num"><input type="number" min="1" max="6" value="${p.h1End || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h1End', this.value)" class="input-mini" style="width: 38px;"></td>
|
||
<td class="num"><input type="number" min="7" max="12" value="${p.h2Start || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h2Start', this.value)" class="input-mini" style="width: 38px;"></td>
|
||
<td class="num"><input type="number" min="7" max="12" value="${p.h2End || ''}" placeholder="-" onchange="updatePerson(${origIdx}, 'h2End', this.value)" class="input-mini" style="width: 38px;"></td>
|
||
<td class="num" style="text-align:center;">${isHrPerson && !p.calculationReady ? '<span class="status-pill status-temp">待確認</span>' : statusHtml}</td>
|
||
<td class="num" style="color: var(--accent-success); font-weight:700;">$${(p.totalCost || 0).toLocaleString()}</td>
|
||
<td>${isHrPerson ? '<span style="color:var(--text-dim);font-size:.8rem;">HR 同步</span>' : `<button onclick="removePerson(${origIdx})" style="background:none; border:none; color:var(--accent-danger); cursor:pointer;">刪除</button>`}</td>
|
||
</tr>
|
||
`;
|
||
});
|
||
|
||
// Update KPI Banner
|
||
const kpiContainer = document.getElementById('personnel-detail-kpi');
|
||
if (kpiContainer) {
|
||
kpiContainer.innerHTML = `
|
||
<div style="background: rgba(255,255,255,0.05); border: 1px solid var(--border-glass); border-radius: 8px; padding: 4px 12px; display: flex; align-items: center; gap: 8px;">
|
||
<span style="font-size: 0.75rem; color: var(--text-dim);">篩選總額</span>
|
||
<span style="font-size: 1.05rem; font-weight: 800; color: var(--text-main);">NT$ ${totalCosts.all.toLocaleString()}</span>
|
||
</div>
|
||
<div style="background: rgba(255,255,255,0.02); border: 1px solid var(--border-glass); border-radius: 8px; padding: 4px 12px; display: flex; align-items: center; gap: 8px;">
|
||
<span style="font-size: 0.75rem; color: var(--text-dim);">${personnelCategory === 'contractors' ? '常態型外包' : '內部人員'}</span>
|
||
<span style="font-size: 0.95rem; font-weight: 700; color: var(--text-main);">${filtered.length} 人</span>
|
||
</div>
|
||
`;
|
||
}
|
||
}
|
||
|
||
function toggleSort(field) {
|
||
if (sortConfig.field === field) {
|
||
sortConfig.direction = sortConfig.direction === 'asc' ? 'desc' : 'asc';
|
||
} else {
|
||
sortConfig.field = field;
|
||
sortConfig.direction = 'asc';
|
||
}
|
||
renderPersonnel();
|
||
}
|
||
|
||
// --- FUNCTIONS ---
|
||
function updatePerson(idx, field, val) {
|
||
const target = isSimMode ? simData : baseData;
|
||
target[idx][field] = val;
|
||
if (target[idx].source === 'hr-sync') {
|
||
const person = target[idx];
|
||
if (field === 'isManager') person.managerClassification = 'confirmed';
|
||
person.calculationReady = Boolean((parseFloat(person.salary) || parseFloat(person.hourlyRate)) && isCalculationRole(person.role));
|
||
person.calculationIssue = person.calculationReady ? '' : (!isCalculationRole(person.role) ? '待設定 P/A 職能' : 'HR 尚未提供可用薪資');
|
||
if (!isSimMode) saveHrCostOverride(person, field, val);
|
||
}
|
||
saveAndRefresh();
|
||
}
|
||
|
||
function escapeHtml(value) {
|
||
return String(value == null ? '' : value).replace(/[&<>\"']/g, char => ({ '&': '&', '<': '<', '>': '>', '\"': '"', "'": ''' })[char]);
|
||
}
|
||
|
||
async function saveHrCostOverride(person, field, value) {
|
||
try {
|
||
const response = await fetch(`/api/hr/cost-model/employees/${encodeURIComponent(person.employeeNumber)}`, {
|
||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ field, value }),
|
||
});
|
||
if (!response.ok) throw new Error('儲存失敗');
|
||
} catch (error) {
|
||
console.error('Unable to save HR cost override', error);
|
||
document.getElementById('data-source-banner').textContent = 'HR 試算資料更新失敗,請重新整理後再試。';
|
||
document.getElementById('data-source-banner').style.color = 'var(--accent-danger)';
|
||
}
|
||
}
|
||
|
||
async function clearHrOverride(idx, field) {
|
||
if (isSimMode) return;
|
||
const person = baseData[idx];
|
||
try {
|
||
const response = await fetch(`/api/hr/cost-model/employees/${encodeURIComponent(person.employeeNumber)}/overrides/${encodeURIComponent(field)}`, { method: 'DELETE' });
|
||
if (!response.ok) throw new Error('還原失敗');
|
||
await loadBootstrapData();
|
||
saveAndRefresh();
|
||
renderPersonnel();
|
||
} catch (error) {
|
||
document.getElementById('data-source-banner').textContent = '無法恢復 HR 原始資料,請重新整理後再試。';
|
||
document.getElementById('data-source-banner').style.color = 'var(--accent-danger)';
|
||
}
|
||
}
|
||
|
||
// --- ADD PERSON MODAL FUNCTIONS ---
|
||
function addPerson() { openAddPersonModal(); } // keep backward compat with existing button
|
||
|
||
function openAddPersonModal() {
|
||
initOrgStructure();
|
||
const modal = document.getElementById('add-person-modal');
|
||
|
||
// Populate dept dropdown from orgStructure + pcDept
|
||
const allDepts = [...Object.keys(globalParams.orgStructure), globalParams.pcDept];
|
||
const deptSel = document.getElementById('modal-dept');
|
||
deptSel.innerHTML = allDepts.map(d => `<option value="${d}">${d}</option>`).join('');
|
||
deptSel.value = allDepts[0] || '';
|
||
|
||
// Populate groups for initial dept
|
||
addPersonModalUpdateGroups();
|
||
|
||
// Reset form fields
|
||
document.getElementById('modal-name').value = '';
|
||
document.getElementById('modal-title-field').value = '';
|
||
const roleSelect = document.getElementById('modal-role');
|
||
for (const option of roleSelect.options) {
|
||
option.disabled = option.hidden = personnelCategory === 'contractors' ? !option.value.startsWith('O') : option.value.startsWith('O');
|
||
}
|
||
roleSelect.value = personnelCategory === 'contractors' ? 'O - 外包' : 'A - 藝術家';
|
||
roleSelect.disabled = personnelCategory === 'contractors';
|
||
document.getElementById('modal-title').textContent = personnelCategory === 'contractors' ? '新增常態型外包' : '新增內部人員';
|
||
document.getElementById('modal-is-manager').checked = false;
|
||
document.getElementById('modal-salary').value = '';
|
||
document.getElementById('modal-h1s').value = '1';
|
||
document.getElementById('modal-h1e').value = '6';
|
||
document.getElementById('modal-h2s').value = '7';
|
||
document.getElementById('modal-h2e').value = '12';
|
||
addPersonModalUpdateSalaryLabel();
|
||
|
||
// Open with animation
|
||
modal.classList.add('open');
|
||
setTimeout(() => document.getElementById('modal-name').focus(), 50);
|
||
}
|
||
|
||
function closeAddPersonModal() {
|
||
document.getElementById('add-person-modal').classList.remove('open');
|
||
}
|
||
|
||
function addPersonModalUpdateGroups() {
|
||
initOrgStructure();
|
||
const dept = document.getElementById('modal-dept').value;
|
||
const groupSel = document.getElementById('modal-group');
|
||
const groups = (globalParams.orgStructure[dept]) || [];
|
||
|
||
// Use current data to find actual groups in this dept
|
||
const current = isSimMode ? simData : baseData;
|
||
const liveGroups = [...new Set(current.filter(p => p.dept === dept && p.group).map(p => p.group))].sort();
|
||
const allGroups = [...new Set([...groups, ...liveGroups])];
|
||
|
||
if (allGroups.length === 0) {
|
||
groupSel.innerHTML = '<option value="">— 未分組</option>';
|
||
} else {
|
||
groupSel.innerHTML = '<option value="">— 未分組</option>' + allGroups.map(g => `<option value="${g}">${g}</option>`).join('');
|
||
}
|
||
}
|
||
|
||
function addPersonModalUpdateSalaryLabel() {
|
||
const role = document.getElementById('modal-role').value;
|
||
const isOutsource = role.startsWith('O');
|
||
document.getElementById('modal-salary-label').textContent = isOutsource ? '日薪 Daily Rate' : '月薪 Monthly Salary';
|
||
document.getElementById('modal-salary-prefix').textContent = isOutsource ? 'NT$ / 日' : 'NT$ / 月';
|
||
}
|
||
|
||
function confirmAddPerson() {
|
||
const name = document.getElementById('modal-name').value.trim();
|
||
if (!name) {
|
||
document.getElementById('modal-name').focus();
|
||
document.getElementById('modal-name').style.borderColor = 'var(--accent-danger)';
|
||
setTimeout(() => document.getElementById('modal-name').style.borderColor = '', 1500);
|
||
return;
|
||
}
|
||
|
||
const role = document.getElementById('modal-role').value;
|
||
const isOutsource = role.startsWith('O');
|
||
|
||
const newPerson = {
|
||
name: name,
|
||
title: document.getElementById('modal-title-field').value.trim(),
|
||
dept: document.getElementById('modal-dept').value,
|
||
group: document.getElementById('modal-group').value || '',
|
||
role: role,
|
||
isManager: document.getElementById('modal-is-manager').checked,
|
||
salary: isOutsource ? '' : (document.getElementById('modal-salary').value || '0'),
|
||
dayrate: isOutsource ? (document.getElementById('modal-salary').value || '0') : '',
|
||
h1Start: document.getElementById('modal-h1s').value,
|
||
h1End: document.getElementById('modal-h1e').value,
|
||
h2Start: document.getElementById('modal-h2s').value,
|
||
h2End: document.getElementById('modal-h2e').value,
|
||
};
|
||
|
||
let maxRow = -1;
|
||
[...baseData, ...(simData || [])].forEach(p => { if (p.row !== undefined && p.row > maxRow) maxRow = p.row; });
|
||
newPerson.row = maxRow + 1;
|
||
|
||
const target = isSimMode ? simData : baseData;
|
||
target.unshift(newPerson);
|
||
|
||
// Force orgStructure rebuild & reset filters so new person is immediately visible
|
||
globalParams.orgStructure = null;
|
||
const deptFilterEl = document.getElementById('personnel-dept-filter');
|
||
const groupFilterEl = document.getElementById('personnel-group-filter');
|
||
const companyFilterEl = document.getElementById('personnel-company-filter');
|
||
if (companyFilterEl) companyFilterEl.value = 'all';
|
||
if (deptFilterEl) deptFilterEl.value = 'all';
|
||
if (groupFilterEl) groupFilterEl.value = 'all';
|
||
|
||
closeAddPersonModal();
|
||
saveAndRefresh();
|
||
}
|
||
|
||
// Escape key closes modal
|
||
document.addEventListener('keydown', e => {
|
||
if (e.key === 'Escape') closeAddPersonModal();
|
||
if (e.key === 'Enter' && document.getElementById('add-person-modal').classList.contains('open')) {
|
||
e.preventDefault();
|
||
confirmAddPerson();
|
||
}
|
||
});
|
||
|
||
|
||
function removePerson(idx) {
|
||
const target = isSimMode ? simData : baseData;
|
||
target.splice(idx, 1);
|
||
saveAndRefresh();
|
||
}
|
||
|
||
function toggleMode() {
|
||
isSimMode = !isSimMode;
|
||
document.body.className = isSimMode ? 'mode-sim' : 'mode-admin';
|
||
const alertEl = document.getElementById('sim-alert');
|
||
alertEl.style.display = isSimMode ? 'block' : 'none';
|
||
document.getElementById('mode-indicator').innerText = isSimMode ? '🧪 試算模式' : '本機預覽模式';
|
||
document.getElementById('mode-toggle').innerText = isSimMode ? '⬅ 返回預覽模式' : '🧪 切換至試算模式';
|
||
|
||
if (isSimMode) {
|
||
// Clone base data for simulation
|
||
simData = JSON.parse(JSON.stringify(baseData));
|
||
previewParamsBeforeSimulation = structuredClone(globalParams);
|
||
globalParams = structuredClone(globalParams);
|
||
} else if (previewParamsBeforeSimulation) {
|
||
globalParams = previewParamsBeforeSimulation;
|
||
previewParamsBeforeSimulation = null;
|
||
}
|
||
saveAndRefresh();
|
||
if (document.querySelector('.view.active')?.id === 'params') renderParams();
|
||
}
|
||
|
||
function showView(viewId) {
|
||
if (typeof getCurrentUser === 'function') {
|
||
const user = getCurrentUser();
|
||
if (!user) return;
|
||
|
||
// Route protection
|
||
if (user.role === 'group_head' && viewId !== 'coda' && viewId !== 'personnel' && viewId !== 'dashboard' && viewId !== 'personnel-overview') return;
|
||
if (user.role === 'dept_head' && viewId !== 'coda' && viewId !== 'invoice' && viewId !== 'personnel' && viewId !== 'dashboard' && viewId !== 'personnel-overview') return;
|
||
// Admin can access all
|
||
}
|
||
|
||
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
|
||
document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
|
||
|
||
const targetView = document.getElementById(viewId);
|
||
if (targetView) targetView.classList.add('active');
|
||
|
||
// Determine the main nav item to activate
|
||
let navId;
|
||
if (viewId === 'hr-personnel') {
|
||
navId = 'nav-personnel';
|
||
} else if (viewId.startsWith('personnel')) {
|
||
navId = viewId === 'personnel' && personnelCategory === 'contractors' ? 'nav-contractors' : 'nav-preview-personnel';
|
||
} else if (viewId === 'org-structure') {
|
||
navId = 'nav-org';
|
||
} else {
|
||
navId = 'nav-' + viewId;
|
||
}
|
||
|
||
const targetNav = document.getElementById(navId);
|
||
if (targetNav) targetNav.classList.add('active');
|
||
|
||
|
||
if (viewId === 'dashboard') renderDashboard();
|
||
if (viewId === 'personnel-overview') renderPersonnelOverview();
|
||
if (viewId === 'invoice') renderInvoice();
|
||
if (viewId === 'params') renderParams();
|
||
if (viewId === 'sales') renderSales();
|
||
if (viewId === 'artists') renderArtists();
|
||
if (viewId === 'coda') renderCoda();
|
||
if (viewId === 'group') renderGroup();
|
||
if (viewId === 'org-structure') renderOrgStructure();
|
||
if (viewId === 'versions') renderVersions();
|
||
document.querySelector('main').scrollTo({ top: 0, left: 0, behavior: 'instant' });
|
||
}
|
||
|
||
const hrPersonnelState = { people: [], filtered: [], page: 0, loaded: false, loading: null, requestedDept: '', salaries: new Map() };
|
||
|
||
function hrCell(row, value) {
|
||
const td = document.createElement('td');
|
||
td.textContent = value == null || value === '' ? '—' : String(value);
|
||
row.append(td);
|
||
return td;
|
||
}
|
||
|
||
function showHrPersonnelView(dept = 'all') {
|
||
hrPersonnelState.requestedDept = dept === 'all' ? '' : dept;
|
||
showView('hr-personnel');
|
||
if (!hrPersonnelState.loaded) loadHrPersonnel();
|
||
else {
|
||
document.getElementById('hr-personnel-dept').value = hrPersonnelState.requestedDept;
|
||
updateHrGroupFilter();
|
||
filterHrPersonnel();
|
||
}
|
||
}
|
||
|
||
async function loadHrPersonnel(force = false) {
|
||
if (hrPersonnelState.loading) return hrPersonnelState.loading;
|
||
const status = document.getElementById('hr-personnel-status');
|
||
status.textContent = '正在讀取 HR 在職名冊與組織分類…';
|
||
hrPersonnelState.loading = (async () => {
|
||
try {
|
||
const response = await fetch('/api/hr/employees', { cache: 'no-store' });
|
||
const payload = await response.json().catch(() => ({}));
|
||
if (!response.ok) {
|
||
const labels = {
|
||
access_denied: '本機預覽無法讀取 HR;請在已登入的 PM Board 正式站查看。',
|
||
hr_not_configured: '本站尚未取得 HR Sync 設定。',
|
||
hr_exchange_denied: '目前登入帳號沒有 HR 名冊權限。',
|
||
hr_endpoint_forbidden: 'HR Sync 拒絕名冊查詢。',
|
||
reauthentication_required: '登入已過期,請重新登入。',
|
||
hr_unavailable: 'HR Sync 暫時無法回應。'
|
||
};
|
||
throw new Error(labels[payload.error] || `HR 名冊讀取失敗(HTTP ${response.status})`);
|
||
}
|
||
if (!Array.isArray(payload.employees)) throw new Error('HR 名冊格式不符。');
|
||
hrPersonnelState.people = payload.employees;
|
||
hrPersonnelState.loaded = true;
|
||
if (force) hrPersonnelState.salaries.clear();
|
||
status.style.color = '';
|
||
const deptSelect = document.getElementById('hr-personnel-dept');
|
||
deptSelect.replaceChildren(new Option('所有部門', ''));
|
||
for (const name of [...new Set(payload.employees.map(p => p.departmentName).filter(Boolean))].sort((a, b) => a.localeCompare(b, 'zh-Hant'))) {
|
||
deptSelect.add(new Option(name, name));
|
||
}
|
||
deptSelect.value = hrPersonnelState.requestedDept;
|
||
updateHrGroupFilter();
|
||
filterHrPersonnel();
|
||
const unknown = payload.employees.filter(p => !p.departmentName && !p.groupName).length;
|
||
status.textContent = `已連上 HR Sync:${payload.employees.length} 位在職人員。${unknown ? `其中 ${unknown} 位尚無可辨識的部/組層級,已保留空白供核對。` : ''}`;
|
||
} catch (error) {
|
||
hrPersonnelState.loaded = false;
|
||
hrPersonnelState.people = [];
|
||
hrPersonnelState.filtered = [];
|
||
hrPersonnelState.salaries.clear();
|
||
status.textContent = error.message;
|
||
status.style.color = 'var(--accent-danger)';
|
||
document.getElementById('hr-personnel-body').replaceChildren();
|
||
document.getElementById('hr-personnel-pager').replaceChildren();
|
||
}
|
||
})().finally(() => { hrPersonnelState.loading = null; });
|
||
return hrPersonnelState.loading;
|
||
}
|
||
|
||
function updateHrGroupFilter() {
|
||
const dept = document.getElementById('hr-personnel-dept').value;
|
||
const groupSelect = document.getElementById('hr-personnel-group');
|
||
const previous = groupSelect.value;
|
||
groupSelect.replaceChildren(new Option('所有組別', ''));
|
||
const groups = new Set(hrPersonnelState.people.filter(p => !dept || p.departmentName === dept).map(p => p.groupName).filter(Boolean));
|
||
for (const name of [...groups].sort((a, b) => a.localeCompare(b, 'zh-Hant'))) groupSelect.add(new Option(name, name));
|
||
groupSelect.value = previous;
|
||
}
|
||
|
||
function filterHrPersonnel() {
|
||
const query = document.getElementById('hr-personnel-search').value.trim().toLocaleLowerCase();
|
||
const dept = document.getElementById('hr-personnel-dept').value;
|
||
const group = document.getElementById('hr-personnel-group').value;
|
||
hrPersonnelState.filtered = hrPersonnelState.people.filter(p =>
|
||
(!dept || p.departmentName === dept) && (!group || p.groupName === group) &&
|
||
(!query || [p.employeeNumber, p.name, p.positionName].some(value => String(value || '').toLocaleLowerCase().includes(query))));
|
||
hrPersonnelState.page = 0;
|
||
renderHrPersonnel();
|
||
}
|
||
|
||
function renderHrPersonnel() {
|
||
const body = document.getElementById('hr-personnel-body');
|
||
body.replaceChildren();
|
||
const start = hrPersonnelState.page * 25;
|
||
const current = hrPersonnelState.filtered.slice(start, start + 25);
|
||
const salaryJobs = [];
|
||
for (const person of current) {
|
||
const row = document.createElement('tr');
|
||
hrCell(row, person.employeeNumber);
|
||
hrCell(row, person.name);
|
||
hrCell(row, person.departmentName);
|
||
hrCell(row, person.groupName);
|
||
hrCell(row, person.positionName);
|
||
hrCell(row, '在職');
|
||
const salary = hrCell(row, '載入中…');
|
||
body.append(row);
|
||
salaryJobs.push(async () => {
|
||
try {
|
||
let record = hrPersonnelState.salaries.get(person.employeeNumber);
|
||
if (!record) {
|
||
const response = await fetch(`/api/hr/employees/${encodeURIComponent(person.employeeNumber)}/salary`, { cache: 'no-store' });
|
||
const payload = await response.json().catch(() => ({}));
|
||
if (!response.ok) {
|
||
const errors = {
|
||
hr_exchange_denied: '薪資授權未通過', hr_endpoint_forbidden: '無薪資查詢權限',
|
||
hr_not_found: '無薪資資料', reauthentication_required: '請重新登入'
|
||
};
|
||
throw new Error(errors[payload.error] || `薪資查詢失敗(${response.status})`);
|
||
}
|
||
record = payload.salary;
|
||
hrPersonnelState.salaries.set(person.employeeNumber, record);
|
||
}
|
||
salary.textContent = record?.amount == null ? '沒有金額' :
|
||
`${new Intl.NumberFormat('zh-TW').format(record.amount)} 元/${{ monthly: '月', hourly: '小時' }[record.salaryType] || '單位未標明'}`;
|
||
} catch (error) {
|
||
salary.textContent = error.message;
|
||
salary.style.color = 'var(--accent-danger)';
|
||
}
|
||
});
|
||
}
|
||
if (!current.length) {
|
||
const row = document.createElement('tr');
|
||
const empty = hrCell(row, '沒有符合條件的在職人員。');
|
||
empty.colSpan = 7;
|
||
body.append(row);
|
||
}
|
||
const pager = document.getElementById('hr-personnel-pager');
|
||
pager.replaceChildren();
|
||
const prev = document.createElement('button');
|
||
prev.className = 'btn btn-outline';
|
||
prev.textContent = '上一頁';
|
||
prev.disabled = hrPersonnelState.page === 0;
|
||
prev.onclick = () => { hrPersonnelState.page--; renderHrPersonnel(); };
|
||
const label = document.createElement('span');
|
||
label.textContent = `第 ${hrPersonnelState.page + 1} 頁,共 ${hrPersonnelState.filtered.length} 位`;
|
||
const next = document.createElement('button');
|
||
next.className = 'btn btn-outline';
|
||
next.textContent = '下一頁';
|
||
next.disabled = start + 25 >= hrPersonnelState.filtered.length;
|
||
next.onclick = () => { hrPersonnelState.page++; renderHrPersonnel(); };
|
||
pager.append(prev, label, next);
|
||
let index = 0;
|
||
Promise.all(Array.from({ length: Math.min(4, salaryJobs.length) }, async () => {
|
||
while (index < salaryJobs.length) await salaryJobs[index++]();
|
||
}));
|
||
}
|
||
|
||
function showPersonnelView(dept, category = 'internal', synthetic = false) {
|
||
if (category === 'internal' && !synthetic) {
|
||
showHrPersonnelView(dept);
|
||
return;
|
||
}
|
||
personnelCategory = category;
|
||
if (dept === 'overview') {
|
||
showView('personnel-overview');
|
||
} else {
|
||
// Populate company and department filters
|
||
initOrgStructure();
|
||
populateCompanyFilter();
|
||
updateDeptFilter();
|
||
const deptFilterEl = document.getElementById('personnel-dept-filter');
|
||
deptFilterEl.value = [...deptFilterEl.options].some(option => option.value === dept) ? dept : 'all';
|
||
const label = category === 'contractors' ? '常態型外包' : '試算人員';
|
||
document.getElementById('personnel-view-title').innerText = `${label}(${dept === 'all' ? '全部門' : dept})`;
|
||
document.getElementById('personnel-source-note').textContent = category === 'contractors'
|
||
? '常態型外包不在 HR 系統內,在此獨立維護日薪、合約月份與部門/組別;新增、修改、刪除會自動儲存在本站。'
|
||
: '2027 HR 試算名單。姓名、職稱、部門/組別與薪資來自 HR;P/A、管理職及未辨識部/組可在此補齊。未完成 P/A 的人會列出,但不納入正式總額。';
|
||
document.getElementById('personnel-add-button').textContent = `+ 新增${label}`;
|
||
document.getElementById('personnel-search').value = '';
|
||
|
||
updateGroupFilter(); // Update group filter based on selected department
|
||
showView('personnel');
|
||
renderPersonnel();
|
||
}
|
||
}
|
||
|
||
// Company comes from HR's organization tree (corporationName). Long legal names are
|
||
// shortened for display only; filtering always uses the full name.
|
||
function shortCompanyName(name) {
|
||
return String(name || '').replace(/股份有限公司$|有限公司$/, '');
|
||
}
|
||
|
||
function matchesCompany(p, companyFilter) {
|
||
if (companyFilter === 'all') return true;
|
||
if (companyFilter === '未指定') return !p.company;
|
||
return p.company === companyFilter;
|
||
}
|
||
|
||
function companyScopedData() {
|
||
const companyFilter = document.getElementById('personnel-company-filter')?.value || 'all';
|
||
const current = isSimMode ? simData : baseData;
|
||
return current.filter(p => matchesPersonnelCategory(p) && matchesCompany(p, companyFilter));
|
||
}
|
||
|
||
function populateCompanyFilter({ keepSelection = false } = {}) {
|
||
const companyFilterEl = document.getElementById('personnel-company-filter');
|
||
if (!companyFilterEl) return false;
|
||
const current = (isSimMode ? simData : baseData).filter(p => matchesPersonnelCategory(p));
|
||
const companies = [...new Set(current.map(p => p.company).filter(Boolean))].sort();
|
||
if (current.some(p => !p.company)) companies.push('未指定');
|
||
const existing = [...companyFilterEl.options].slice(1).map(option => option.value);
|
||
if (keepSelection && existing.join('\n') === companies.join('\n')) return false;
|
||
const selected = companyFilterEl.value;
|
||
companyFilterEl.replaceChildren(new Option('所有公司', 'all'),
|
||
...companies.map(name => new Option(name === '未指定' ? name : shortCompanyName(name), name)));
|
||
companyFilterEl.value = keepSelection && companies.includes(selected) ? selected : 'all';
|
||
return true;
|
||
}
|
||
|
||
function updateDeptFilter() {
|
||
initOrgStructure();
|
||
const deptFilterEl = document.getElementById('personnel-dept-filter');
|
||
const companyFilter = document.getElementById('personnel-company-filter')?.value || 'all';
|
||
// The legacy support department (pcDept, 製程部) is a calculation setting, not an HR
|
||
// unit: list it only when someone is actually assigned to it.
|
||
const hasSupportDeptPeople = companyScopedData().some(p => p.dept && p.dept === globalParams.pcDept);
|
||
const activeDepts = companyFilter === 'all'
|
||
? [...Object.keys(globalParams.orgStructure), ...(hasSupportDeptPeople ? [globalParams.pcDept] : [])]
|
||
: [...new Set(companyScopedData().map(p => p.dept).filter(Boolean))];
|
||
deptFilterEl.replaceChildren(new Option('所有部門', 'all'),
|
||
...[...new Set(activeDepts.filter(Boolean))].sort().map(d => new Option(d, d)),
|
||
new Option('其他 (未定義)', '其他'));
|
||
deptFilterEl.value = 'all';
|
||
}
|
||
|
||
function updateGroupFilter() {
|
||
const deptFilterEl = document.getElementById('personnel-dept-filter');
|
||
const groupFilterEl = document.getElementById('personnel-group-filter');
|
||
const selectedDept = deptFilterEl.value;
|
||
const companySelected = (document.getElementById('personnel-company-filter')?.value || 'all') !== 'all';
|
||
|
||
let groupOptionsHtml = '<option value="all">所有組別</option>';
|
||
const collectedGroups = new Set(); // Track to avoid duplicates
|
||
|
||
if (selectedDept === 'all') {
|
||
// Show all groups from all departments (within the selected company)
|
||
const current = companyScopedData();
|
||
current.forEach(p => {
|
||
if (p.group) collectedGroups.add(p.group);
|
||
});
|
||
[...collectedGroups].sort().forEach(g => {
|
||
groupOptionsHtml += `<option value="${g}">${g}</option>`;
|
||
});
|
||
} else if (selectedDept === '其他') {
|
||
// Show groups for people in '其他' departments
|
||
const current = companyScopedData();
|
||
current.filter(p => !Object.keys(globalParams.orgStructure).includes(p.dept) && p.dept !== globalParams.pcDept).forEach(p => {
|
||
if (p.group) collectedGroups.add(p.group);
|
||
});
|
||
[...collectedGroups].sort().forEach(g => {
|
||
groupOptionsHtml += `<option value="${g}">${g}</option>`;
|
||
});
|
||
} else {
|
||
// Use orgStructure for specific department, or scan data if not defined
|
||
const targetDeptGroups = globalParams.orgStructure[selectedDept];
|
||
if (!companySelected && targetDeptGroups && targetDeptGroups.length > 0) {
|
||
targetDeptGroups.sort().forEach(g => {
|
||
collectedGroups.add(g);
|
||
groupOptionsHtml += `<option value="${g}">${g}</option>`;
|
||
});
|
||
} else {
|
||
// Fallback: scan data for groups in this specific department
|
||
const current = companyScopedData();
|
||
const pInDept = current.filter(p => p.dept === selectedDept);
|
||
[...new Set(pInDept.map(p => p.group || '未分組'))].sort().forEach(g => {
|
||
collectedGroups.add(g);
|
||
groupOptionsHtml += `<option value="${g}">${g}</option>`;
|
||
});
|
||
}
|
||
}
|
||
|
||
// Append 未分組 only if not already in the list
|
||
if (!collectedGroups.has('未分組')) {
|
||
groupOptionsHtml += `<option value="未分組">未分組</option>`;
|
||
}
|
||
|
||
groupFilterEl.innerHTML = groupOptionsHtml;
|
||
groupFilterEl.value = 'all'; // Reset group filter to 'all' when department changes
|
||
}
|
||
|
||
function renderCoda() {
|
||
initOrgStructure();
|
||
const current = isSimMode ? simData : baseData;
|
||
const container = document.getElementById('coda-content');
|
||
if (!container) return;
|
||
|
||
// --- 1. P-budget per dept (from Sales logic) ---
|
||
const targetDepts = Object.keys(globalParams.orgStructure);
|
||
const pBudgetByDept = {};
|
||
targetDepts.forEach(d => pBudgetByDept[d] = 0);
|
||
current.filter(p => p.role.startsWith('P') && targetDepts.includes(p.dept)).forEach(p => {
|
||
pBudgetByDept[p.dept] += (p.totalCost || 0);
|
||
});
|
||
|
||
// --- 2. Run calculateAll for PC allocation ---
|
||
const { deptStats } = calculateAll(current);
|
||
const pcAdjustedTotal = deptStats[globalParams.pcDept]?.dt || 0;
|
||
|
||
// --- 3. Build per-dept A/O artist data (grouped) ---
|
||
let grandArtistTotal = 0;
|
||
current.filter(p => targetDepts.includes(p.dept) && p.role.startsWith('A')).forEach(p => grandArtistTotal += (p.totalCost || 0));
|
||
|
||
// deptData: { dept -> { groups: { groupName -> [people] }, rawA, rawO } }
|
||
const deptData = {};
|
||
targetDepts.forEach(d => { deptData[d] = { rawA: 0, rawO: 0, groups: {} }; });
|
||
|
||
current.filter(p => targetDepts.includes(p.dept) && (p.role.startsWith('A') || p.role.startsWith('O'))).forEach(p => {
|
||
const d = p.dept;
|
||
const gName = p.group || '未分組';
|
||
if (!deptData[d].groups[gName]) deptData[d].groups[gName] = { people: [], rawA: 0, rawO: 0 };
|
||
const cost = p.totalCost || 0;
|
||
if (p.role.startsWith('A')) { deptData[d].rawA += cost; deptData[d].groups[gName].rawA += cost; }
|
||
else { deptData[d].rawO += cost; deptData[d].groups[gName].rawO += cost; }
|
||
deptData[d].groups[gName].people.push(p);
|
||
});
|
||
|
||
// --- 4. Compute final dept budgets (aBudget includes PC allocation) ---
|
||
let grandCoda = 0;
|
||
const codaRows = targetDepts.map(d => {
|
||
const pBudget = pBudgetByDept[d] || 0;
|
||
const deptPct = grandArtistTotal === 0 ? 0 : (deptData[d].rawA / grandArtistTotal);
|
||
const aBudget = deptData[d].rawA + (pcAdjustedTotal * deptPct); // with PC allocation
|
||
const oBudget = deptData[d].rawO;
|
||
|
||
// PARADIGM SHIFT: Outsource (O) is NO LONGER part of the CODA target
|
||
const totalCoda = pBudget + aBudget;
|
||
grandCoda += totalCoda;
|
||
|
||
return { dept: d, pBudget, aBudget, oBudget, rawA: deptData[d].rawA, rawO: deptData[d].rawO, totalCoda, groups: deptData[d].groups };
|
||
});
|
||
|
||
// --- 5. Support Dept ---
|
||
const pcDept = globalParams.pcDept;
|
||
const rate = (globalParams.supportConversionRate !== undefined) ? globalParams.supportConversionRate : 0.5;
|
||
let supportRawA = 0, supportRawO = 0;
|
||
const supportGroups = {};
|
||
current.filter(p => p.dept === pcDept && (p.role.startsWith('A') || p.role.startsWith('O'))).forEach(p => {
|
||
const gName = p.group || '未分組';
|
||
if (!supportGroups[gName]) supportGroups[gName] = { people: [], rawA: 0, rawO: 0 };
|
||
const cost = p.totalCost || 0;
|
||
if (p.role.startsWith('A')) { supportRawA += cost; supportGroups[gName].rawA += cost; }
|
||
else { supportRawO += cost; supportGroups[gName].rawO += cost; }
|
||
supportGroups[gName].people.push(p);
|
||
});
|
||
const supportArtistBudget = supportRawA * rate;
|
||
const supportOutsource = supportRawO;
|
||
|
||
// PARADIGM SHIFT: Outsource (O) is NO LONGER part of the CODA target
|
||
const supportCoda = supportArtistBudget;
|
||
// Note: We DO NOT add supportCoda to grandCoda here, because support costs are already
|
||
// distributed into the aBudget of the business departments. Adding it again double-counts it!
|
||
// Support costs are shown separately for reference, already allocated above.
|
||
|
||
// --- 6. Update grand total ---
|
||
document.getElementById('coda-grand-total').innerHTML = `<div class='currency-wrap' style='--symbol-width: 50px; --symbol-gap: 1.5rem; min-width: 220px; width: 100%;'><span>NT$</span><span>${Math.round(grandCoda).toLocaleString()}</span></div>`;
|
||
|
||
// Helper: CODA breakdown badge row (fixed grid for alignment)
|
||
function budgetBadges(pBudget, aBudget, isSupport = false) {
|
||
return `
|
||
<div style="display:grid; grid-template-columns: 160px 1fr; gap: 4px 10px; align-items:center;">
|
||
<span style="font-size:0.78rem; color:var(--accent-secondary); background:rgba(139,92,246,0.1); padding:2px 10px; border-radius:99px; text-align:center; white-space:nowrap;">
|
||
P 預算
|
||
</span>
|
||
<span style="font-weight:700; color:${isSupport ? 'var(--text-dim)' : 'var(--accent-secondary)'}; text-align:right;">
|
||
${isSupport ? 'N/A(無業務P)' : `<div class='currency-wrap' style='--symbol-width: 40px; --symbol-gap: 0.5rem; min-width: 120px;'><span>NT$</span><span>${Math.round(pBudget).toLocaleString()}</span></div>`}
|
||
</span>
|
||
<span style="font-size:0.78rem; color:var(--accent-primary); background:rgba(59,130,246,0.1); padding:2px 10px; border-radius:99px; text-align:center; white-space:nowrap;">
|
||
${isSupport ? 'A 預算 × ' + rate : 'A 預算(含分攤)'}
|
||
</span>
|
||
<span style="font-weight:700; color:var(--accent-primary); text-align:right;"><div class='currency-wrap' style='--symbol-width: 40px; --symbol-gap: 0.5rem; min-width: 120px;'><span>NT$</span><span>${Math.round(aBudget).toLocaleString()}</span></div></span>
|
||
</div>`;
|
||
}
|
||
|
||
// Helper: build group + artist table for a dept
|
||
function buildArtistTable(deptName, groups, deptTotalCoda, deptAOraw, safeDeptId, visibleGroupsArray = null) {
|
||
let html = `<div id="coda-detail-${safeDeptId}" style="display:none; border-top:1px solid var(--border-glass); padding:1.5rem;"><div style="display:flex; flex-direction:column; gap:1rem;">`;
|
||
|
||
const isSupportDept = deptName === globalParams.pcDept;
|
||
const supportConversionRate = (globalParams.supportConversionRate !== undefined) ? globalParams.supportConversionRate : 0.5;
|
||
|
||
const sortedGroups = Object.entries(groups).map(([gName, gData]) => {
|
||
const gRaw = gData.rawA + gData.rawO;
|
||
// Support Dept group initial coda separates converted A. Business Dept distributes by A ratio only.
|
||
// PARADIGM SHIFT: O costs are no longer factors in CODA aggregation
|
||
const groupA = gData.rawA;
|
||
const deptA = deptName === pcDept ? supportRawA : Object.values(groups).reduce((acc, g) => acc + g.rawA, 0);
|
||
|
||
let groupNonRd_A = groupA;
|
||
let deptNonRd_A = deptA;
|
||
|
||
if (isSupportDept) {
|
||
groupNonRd_A = gData.people.filter(p => !p.role.startsWith('O') && !(globalParams.rdIndividuals || []).includes(p.name))
|
||
.reduce((acc, p) => acc + (p.totalCost || 0), 0);
|
||
|
||
let tempDeptNonRDA = 0;
|
||
Object.values(groups).forEach(g => {
|
||
g.people.forEach(p => {
|
||
if (!p.role.startsWith('O') && !(globalParams.rdIndividuals || []).includes(p.name)) {
|
||
tempDeptNonRDA += (p.totalCost || 0);
|
||
}
|
||
});
|
||
});
|
||
deptNonRd_A = tempDeptNonRDA;
|
||
}
|
||
|
||
const initialCoda = isSupportDept ?
|
||
(deptNonRd_A === 0 ? 0 : deptTotalCoda * (groupNonRd_A / deptNonRd_A)) :
|
||
(deptA === 0 ? 0 : deptTotalCoda * (groupA / deptA));
|
||
|
||
const isRD = (globalParams.rdGroups || []).includes(`${deptName}|${gName}`);
|
||
const isCGLead = (globalParams.cgLeadGroups || []).includes(`${deptName}|${gName}`);
|
||
|
||
// Calculate Total FTE for the group to correctly derive Average Daily CODA
|
||
const groupFTE = gData.people.reduce((acc, p) => {
|
||
const isRDIndiv = isSupportDept && (globalParams.rdIndividuals || []).includes(p.name);
|
||
if (p.role.startsWith('O') || isRDIndiv) return acc; // O and RD individuals do not count towards FTE for group CODA average
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
return acc + ((m1 + m2) / 12);
|
||
}, 0);
|
||
|
||
return { gName, gData, gRaw, groupA, groupNonRd_A, initialCoda, isRD, isCGLead, groupFTE };
|
||
});
|
||
|
||
const rdReductionPct = globalParams.rdReductionPct ?? 0.35;
|
||
const cgLeadReductionPct = globalParams.cgLeadReductionPct ?? 0.85; // 承擔 85%
|
||
|
||
// Calculate Total Redistribution Pool from RD and CG Lead
|
||
const totalRDTax = sortedGroups.filter(g => g.isRD).reduce((acc, g) => acc + (g.initialCoda * rdReductionPct), 0);
|
||
const totalCGLeadTax = sortedGroups.filter(g => g.isCGLead).reduce((acc, g) => acc + (g.initialCoda * (1 - cgLeadReductionPct)), 0);
|
||
|
||
// Final pool to redistribute to NORMAL groups (Non-RD AND Non-CGLead)
|
||
const totalRedistributionPool = totalRDTax + totalCGLeadTax;
|
||
const normalGroupsInitialCodaTotal = sortedGroups.filter(g => !g.isRD && !g.isCGLead).reduce((acc, g) => acc + g.initialCoda, 0);
|
||
|
||
sortedGroups.forEach(g => {
|
||
if (g.isRD) {
|
||
g.finalCoda = g.initialCoda * (1 - rdReductionPct);
|
||
g.rdNote = `研發減免 -${formatPct(rdReductionPct * 100)}%`;
|
||
} else if (g.isCGLead) {
|
||
g.finalCoda = g.initialCoda * cgLeadReductionPct;
|
||
g.rdNote = `CG Lead 承擔 -${formatPct((1 - cgLeadReductionPct) * 100)}%`;
|
||
} else {
|
||
const shareOfNormal = normalGroupsInitialCodaTotal === 0 ? 0 : (g.initialCoda / normalGroupsInitialCodaTotal);
|
||
g.finalCoda = g.initialCoda + (totalRedistributionPool * shareOfNormal);
|
||
if (totalRedistributionPool > 0) g.rdNote = `分攤研製及管理 CODA`;
|
||
}
|
||
});
|
||
|
||
sortedGroups.sort((a, b) => b.gRaw - a.gRaw).forEach(groupObj => {
|
||
const { gName, gData, gRaw, groupA, groupNonRd_A, initialCoda, finalCoda, rdNote, groupFTE } = groupObj;
|
||
|
||
// Auth filter: skip rendering if not in visible list
|
||
if (visibleGroupsArray && !visibleGroupsArray.includes(gName)) return;
|
||
|
||
const gPctOfDept = deptAOraw === 0 ? 0 : (gRaw / deptAOraw * 100);
|
||
const safeGrp = (safeDeptId + '-' + gName).replace(/\s+/g, '-');
|
||
const annualWorkDays = globalParams.annualWorkDays || 255;
|
||
const managerReductionPct = globalParams.managerReductionPct !== undefined ? parseFloat(globalParams.managerReductionPct) : 0.6;
|
||
|
||
const groupAvgDailyCoda = groupFTE === 0 ? 0 : (finalCoda / annualWorkDays) / groupFTE;
|
||
|
||
// Manager Reduction Logic Pre-calculation
|
||
let totalManagerReductionPool = 0;
|
||
let nonManagerCostSum = 0;
|
||
|
||
// First pass: identify pure raw targets and manager reduced sums
|
||
const pRawCodaMap = new Map();
|
||
gData.people.forEach(p => {
|
||
const pCost = p.totalCost || 0;
|
||
const isO = p.role.startsWith('O');
|
||
const isRDIndiv = isSupportDept && (globalParams.rdIndividuals || []).includes(p.name);
|
||
const isAManager = p.role.startsWith('A') && p.isManager;
|
||
|
||
let baseRawCoda = 0;
|
||
if (isO || isRDIndiv) {
|
||
baseRawCoda = 0;
|
||
} else if (isSupportDept) {
|
||
baseRawCoda = groupNonRd_A === 0 ? 0 : initialCoda * (pCost / groupNonRd_A);
|
||
} else {
|
||
baseRawCoda = groupA === 0 ? 0 : initialCoda * (pCost / groupA);
|
||
}
|
||
|
||
let targetRawCoda = baseRawCoda;
|
||
if (isAManager && !isRDIndiv) {
|
||
const reduction = baseRawCoda * managerReductionPct;
|
||
totalManagerReductionPool += reduction;
|
||
targetRawCoda = baseRawCoda - reduction;
|
||
} else if (!isO && !isRDIndiv && !isAManager) {
|
||
nonManagerCostSum += pCost;
|
||
}
|
||
|
||
pRawCodaMap.set(p, { baseRawCoda, targetRawCoda });
|
||
});
|
||
|
||
// Second pass: distribute the pool to non-managers
|
||
gData.people.forEach(p => {
|
||
const state = pRawCodaMap.get(p);
|
||
const isO = p.role.startsWith('O');
|
||
const isRDIndiv = isSupportDept && (globalParams.rdIndividuals || []).includes(p.name);
|
||
const isAManager = p.role.startsWith('A') && p.isManager;
|
||
|
||
if (!isO && !isRDIndiv && !isAManager && nonManagerCostSum > 0) {
|
||
const pCost = p.totalCost || 0;
|
||
const share = pCost / nonManagerCostSum;
|
||
state.targetRawCoda += totalManagerReductionPool * share;
|
||
}
|
||
});
|
||
|
||
html += `
|
||
<div style="background:rgba(255,255,255,0.02); border:1px solid var(--border-glass); border-radius:12px; overflow:hidden;">
|
||
<div onclick="toggleCodaGroup('${safeGrp}')" style="cursor:pointer; padding:0.75rem 1rem; display:flex; justify-content:space-between; align-items:center;" onmouseover="this.style.background='rgba(255,255,255,0.04)'" onmouseout="this.style.background='transparent'">
|
||
<div style="display:flex; align-items:center; gap:1.5rem; flex-grow:1;">
|
||
<h4 style="margin:0; font-size:0.9rem; color:var(--text-main); min-width:160px;">${gName}</h4>
|
||
<span style="font-size:0.78rem; color:var(--text-dim); background:rgba(255,255,255,0.04); padding:2px 8px; border-radius:99px;">${gData.people.length} 人</span>
|
||
<div style="display:flex; flex-direction:column;">
|
||
<div style="display:flex; align-items:center; gap:10px;">
|
||
<span style="font-size:0.95rem; font-weight:700; color:var(--accent-success);">CODA NT$ ${Math.round(finalCoda).toLocaleString()}</span>
|
||
${rdNote ? `<span style="background:${groupObj.isRD ? 'var(--accent-danger)' : 'var(--accent-primary)'}; color:white; padding:0 6px; border-radius:4px; font-size:0.65rem;">${rdNote}</span>` : ''}
|
||
${(totalManagerReductionPool > 0 || totalCGLeadTax > 0) ? `<span style="background:var(--accent-warning); color:black; padding:0 6px; border-radius:4px; font-size:0.65rem;">含主管及 CG Lead 承擔分攤</span>` : ''}
|
||
</div>
|
||
<span style="font-size:0.75rem; color:var(--text-dim);">佔部門總成本 ${formatPct(gPctOfDept)}%${window.IS_PUBLIC_VERSION ? '' : ` (組內 P+A: NT$ ${Math.round(groupA).toLocaleString()} / O外包: NT$ ${Math.round(gData.rawO).toLocaleString()})`}</span>
|
||
</div>
|
||
<div style="margin-left: auto; text-align:right; min-width:120px; display:flex; flex-direction:column;">
|
||
<span style="font-size:0.7rem; color:var(--text-dim); text-transform:uppercase;">平均日工作 CODA<span style="font-size:0.6rem;opacity:0.6;"> (不含O)</span></span>
|
||
<span style="font-size:0.9rem; font-weight:700; color:var(--text-main);">NT$ ${Math.round(groupAvgDailyCoda).toLocaleString()}</span>
|
||
</div>
|
||
</div>
|
||
<div id="coda-group-chevron-${safeGrp}" style="color:var(--text-dim); font-size:0.8rem; margin-left: 1rem;">▼</div>
|
||
</div>
|
||
<div id="coda-group-detail-${safeGrp}" style="display:none; padding:0 1rem 1rem 1rem;">
|
||
<table style="width:100%; table-layout:fixed; background:transparent; font-size:0.82rem;">
|
||
<colgroup>
|
||
<col style="width:90px"><col style="width:100px"><col style="width:60px">
|
||
<col style="width:65px"><col style="width:65px"><col style="min-width:130px; width:auto">
|
||
<col style="min-width:130px; width:auto"><col style="min-width:130px; width:auto">
|
||
</colgroup>
|
||
<thead>
|
||
<tr>
|
||
<th style="overflow:hidden;">姓名</th>
|
||
<th style="overflow:hidden;">職稱</th>
|
||
<th>職能</th>
|
||
<th class="num" style="white-space:nowrap;">總月份</th>
|
||
<th class="num" style="white-space:nowrap;">工作率</th>
|
||
<th class="num">${window.IS_PUBLIC_VERSION ? '組內佔比' : '年度總成本(組內佔比)'}</th>
|
||
<th class="num" style="color:var(--accent-success);">應負責 CODA</th>
|
||
<th class="num" style="color:var(--accent-warning);">日工作 CODA</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
`;
|
||
|
||
gData.people.sort((a, b) => (b.totalCost || 0) - (a.totalCost || 0)).forEach(p => {
|
||
const pCost = p.totalCost || 0;
|
||
const pPctInGroup = gRaw === 0 ? 0 : (pCost / gRaw * 100);
|
||
const isO = p.role.startsWith('O');
|
||
const isRDIndiv = isSupportDept && (globalParams.rdIndividuals || []).includes(p.name);
|
||
const isAManager = p.role.startsWith('A') && p.isManager;
|
||
|
||
const state = pRawCodaMap.get(p);
|
||
let pRawCoda = state ? state.targetRawCoda : 0;
|
||
|
||
// Apply RD proportional adjustment based on final target sum
|
||
const pCoda = initialCoda === 0 ? 0 : pRawCoda * (finalCoda / initialCoda);
|
||
|
||
// Calculate working days to derive Day Rate (Prorated)
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
const pDays = annualWorkDays * ((m1 + m2) / 12);
|
||
const pDailyCoda = (isO || isRDIndiv) ? 0 : (pDays > 0 ? (pCoda / pDays) : 0);
|
||
|
||
let codaNoteHtml = '';
|
||
if (isO) codaNoteHtml = '<span style="font-size:0.75rem;">[不負責業績]</span>';
|
||
else if (isRDIndiv) codaNoteHtml = '<span style="font-size:0.75rem;">[獨立研發免責]</span>';
|
||
else {
|
||
let mgrNote = '';
|
||
if (isAManager) mgrNote = `<span style="font-size:0.7rem; color:var(--accent-warning); margin-right:4px;">[主管僅承擔 -${formatPct(managerReductionPct * 100)}%]</span>`;
|
||
codaNoteHtml = `${mgrNote}<div class='currency-wrap' style='--symbol-width: 35px; --symbol-gap: 0.5rem; min-width: 100px;'><span>NT$</span><span>${Math.round(pCoda).toLocaleString()}</span></div>`;
|
||
}
|
||
|
||
html += `
|
||
<tr>
|
||
<td style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${p.name}">${p.name}</td>
|
||
<td style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${p.title || ''}">${p.title || ''}</td>
|
||
<td><span class="role-pill ${isO ? 'role-o' : 'role-a'}" style="font-size:0.68rem;padding:2px 5px;">${p.role.split(' - ')[0]}</span></td>
|
||
<td class="num">${m1 + m2}</td>
|
||
<td class="num">${p.workRateUsed || 1}</td>
|
||
<td class='num'>${window.IS_PUBLIC_VERSION ? '' : `<div class='currency-wrap' style='--symbol-width: 35px; --symbol-gap: 0.5rem; min-width: 100px;'><span>NT$</span><span>${Math.round(pCost).toLocaleString()}</span></div> `}<span style="color:var(--text-dim);font-size:0.75rem;">(${formatPct(pPctInGroup)}%)</span></td>
|
||
<td class="num" style="color:${(isO || isRDIndiv) ? 'var(--text-muted)' : 'var(--accent-success)'}; font-weight:${(isO || isRDIndiv) ? '400' : '700'};">${codaNoteHtml}</td>
|
||
<td class="num" style="color:${(isO || isRDIndiv) ? 'var(--text-muted)' : 'var(--accent-warning)'}; font-weight:${(isO || isRDIndiv) ? '400' : '700'};">${(isO || isRDIndiv) ? '<span style="font-size:0.75rem;">-</span>' : `<div class='currency-wrap' style='--symbol-width: 35px; --symbol-gap: 0.5rem; min-width: 100px;'><span>NT$</span><span>${Math.round(pDailyCoda).toLocaleString()}</span></div>`}</td>
|
||
</tr>`;
|
||
});
|
||
|
||
html += `</tbody></table></div></div>`;
|
||
});
|
||
|
||
html += `</div></div>`;
|
||
return html;
|
||
}
|
||
|
||
// Helper to compute Department FTE for accurate standard daily average
|
||
function extractDeptFTE(groups) {
|
||
return Object.values(groups).reduce((acc, g) => {
|
||
return acc + g.people.reduce((acc2, p) => {
|
||
const m1 = (p.h1Start && p.h1End) ? Math.max(0, parseInt(p.h1End) - parseInt(p.h1Start) + 1) : 0;
|
||
const m2 = (p.h2Start && p.h2End) ? Math.max(0, parseInt(p.h2End) - parseInt(p.h2Start) + 1) : 0;
|
||
return acc2 + ((m1 + m2) / 12);
|
||
}, 0);
|
||
}, 0);
|
||
}
|
||
|
||
// --- 7. Render dept cards ---
|
||
// Auth: resolve current user scope for content filtering
|
||
const _authUserCoda = typeof getCurrentUser === 'function' ? getCurrentUser() : null;
|
||
const _isAdminCoda = !_authUserCoda || _authUserCoda.role === 'admin';
|
||
|
||
const colors = ['var(--accent-primary)', 'var(--accent-secondary)', 'var(--accent-success)', 'var(--accent-warning)', '#ec4899'];
|
||
container.innerHTML = '';
|
||
|
||
// Privacy Hint for Managers
|
||
if (!_isAdminCoda) {
|
||
container.innerHTML = `
|
||
<div style="margin-bottom: 2rem; padding: 1rem 1.5rem; background: rgba(139, 92, 246, 0.1); border: 1px solid rgba(139, 92, 246, 0.3); border-radius: 12px; font-size: 0.88rem; color: var(--text-main);">
|
||
💡 您目前以<strong>${_authUserCoda.role === 'dept_head' ? '部長' : '組長'}</strong>身份登入,以下僅顯示您所屬部門 (${_authUserCoda.dept || '—'}) 的成本組成與細節,全公司總 CODA 仍維持整體規模呈現。
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
Object.keys(globalParams.orgStructure).forEach((deptName, i) => {
|
||
const row = codaRows.find(r => r.dept === deptName);
|
||
if (!row) return; // Skip if this department has no data
|
||
|
||
// Auth filter: non-admin users only see their authorized dept
|
||
if (!_isAdminCoda && _authUserCoda.dept && deptName !== _authUserCoda.dept) return;
|
||
|
||
const codaPct = grandCoda === 0 ? 0 : (row.totalCoda / grandCoda * 100);
|
||
const accentColor = colors[i % colors.length];
|
||
const safeDeptId = 'coda-dept-' + row.dept.replace(/\s+/g, '-');
|
||
const deptAOraw = row.rawA + row.rawO;
|
||
|
||
// Auth filter: group_head users only see their authorized group's artist data
|
||
let authorizedGroups = null;
|
||
if (!_isAdminCoda && _authUserCoda.role === 'group_head' && _authUserCoda.group) {
|
||
authorizedGroups = [_authUserCoda.group];
|
||
}
|
||
|
||
const deptFTE = extractDeptFTE(row.groups);
|
||
const annualWorkDays = globalParams.annualWorkDays || 255;
|
||
const deptAvgDailyCoda = deptFTE === 0 ? 0 : (row.totalCoda / annualWorkDays) / deptFTE;
|
||
|
||
container.innerHTML += `
|
||
<div class="card" style="margin-bottom:1.5rem; border-color:${accentColor}22; padding:0;">
|
||
<div onclick="toggleCodaDept('${safeDeptId}')" style="cursor:pointer; padding:1.5rem; display:flex; justify-content:space-between; align-items:center;" onmouseover="this.style.background='var(--bg-glass)'" onmouseout="this.style.background='transparent'">
|
||
<div style="flex-grow:1;">
|
||
<h3 style="color:${accentColor}; font-size:1.15rem; margin-bottom:0.4rem;">${row.dept}</h3>
|
||
<div style="display:flex; align-items:baseline; gap:1.5rem; flex-wrap:wrap;">
|
||
<div style="font-size:1.8rem; font-weight:800; color:var(--text-main); text-shadow:0 0 20px ${accentColor}44;"><div class='currency-wrap' style='--symbol-width: 60px; --symbol-gap: 1.5rem; min-width: 250px;'><span>NT$</span><span>${Math.round(row.totalCoda).toLocaleString()}</span></div></div>
|
||
${row.oBudget > 0 ? `
|
||
<div style="font-size:0.8rem; color:var(--accent-warning); background:rgba(245,158,11,0.08); padding:4px 10px; border-radius:6px; border:1px dashed rgba(245,158,11,0.3);">
|
||
⚠️ 須另行負擔之外包成本: <strong>NT$ ${Math.round(row.oBudget).toLocaleString()}</strong>
|
||
</div>` : ''}
|
||
</div>
|
||
<div style="color:var(--text-dim); font-size:0.8rem; margin-top:0.4rem;">佔全公司 ${formatPct(codaPct)}%</div>
|
||
<div style="height:6px; background:rgba(255,255,255,0.05); border-radius:4px; overflow:hidden; margin-top:0.75rem; max-width:300px;">
|
||
<div style="width:${codaPct}%; height:100%; background:linear-gradient(90deg,${accentColor},${accentColor}88);"></div>
|
||
</div>
|
||
</div>
|
||
<div style="display:flex; align-items:center; gap:2rem;">
|
||
<div>
|
||
<div style="font-size:0.72rem; color:var(--text-dim); text-transform:uppercase; letter-spacing:1px; margin-bottom:0.5rem;">CODA 組成 (純內製 P+A)</div>
|
||
${budgetBadges(row.pBudget, row.aBudget)}
|
||
</div>
|
||
<div style="text-align:right;">
|
||
<div style="font-size:0.72rem; color:var(--text-dim); text-transform:uppercase; letter-spacing:1px; margin-bottom:0.5rem;">部門平均日工作 CODA</div>
|
||
<div style="font-size:1.1rem; font-weight:700; color:var(--text-main);"><div class='currency-wrap' style='--symbol-width: 45px; --symbol-gap: 1rem; min-width: 160px;'><span>NT$</span><span>${Math.round(deptAvgDailyCoda).toLocaleString()}</span></div></div>
|
||
</div>
|
||
<div id="coda-chevron-${safeDeptId}" style="color:var(--text-muted); transition:transform 0.3s; margin-left: 0.5rem;">▼</div>
|
||
</div>
|
||
</div>
|
||
${buildArtistTable(row.dept, row.groups, row.totalCoda, deptAOraw, safeDeptId, authorizedGroups)}
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
// --- 8. Render isolated pcDept ("製程部") ---
|
||
// Auth filter: non-admin only sees pcDept card if their dept is pcDept
|
||
if (_isAdminCoda || (_authUserCoda && _authUserCoda.dept === pcDept)) {
|
||
const supportPct = grandCoda === 0 ? 0 : (supportCoda / grandCoda * 100);
|
||
const safeSupportId = 'coda-dept-support';
|
||
const supportAOraw = supportRawA + supportRawO;
|
||
|
||
// Auth filter: group_head in pcDept only sees their group
|
||
let authorizedSupportGroups = null;
|
||
if (!_isAdminCoda && _authUserCoda.role === 'group_head' && _authUserCoda.group) {
|
||
authorizedSupportGroups = [_authUserCoda.group];
|
||
}
|
||
|
||
const supportFTE = extractDeptFTE(supportGroups);
|
||
const annualWorkDaysSupport = globalParams.annualWorkDays || 255;
|
||
const supportAvgDailyCoda = supportFTE === 0 ? 0 : (supportCoda / annualWorkDaysSupport) / supportFTE;
|
||
|
||
container.innerHTML += `
|
||
<div style="margin:2rem 0 1rem 0; display:flex; align-items:center; gap:1rem;">
|
||
<div style="flex-grow:1; height:1px; background:var(--border-glass);"></div>
|
||
<span style="color:var(--text-muted); font-size:0.85rem; font-weight:600;">支援成本明細(已分攤,不重複加總)</span>
|
||
<div style="flex-grow:1; height:1px; background:var(--border-glass);"></div>
|
||
</div>
|
||
<div class="card" style="margin-bottom:1.5rem; border-style:dashed; opacity:0.9; padding:0;">
|
||
<div onclick="toggleCodaDept('${safeSupportId}')" style="cursor:pointer; padding:1.5rem; display:flex; justify-content:space-between; align-items:center;" onmouseover="this.style.background='var(--bg-glass)'" onmouseout="this.style.background='transparent'">
|
||
<div style="flex-grow:1;">
|
||
<h3 style="color:var(--text-muted); font-size:1.15rem; margin-bottom:0.4rem;">${pcDept}</h3>
|
||
<div style="display:flex; align-items:baseline; gap:1.5rem; flex-wrap:wrap;">
|
||
<div style="font-size:1.8rem; font-weight:800; color:var(--text-main);"><div class='currency-wrap' style='--symbol-width: 60px; --symbol-gap: 1.5rem; min-width: 250px;'><span>NT$</span><span>${Math.round(supportCoda).toLocaleString()}</span></div></div>
|
||
${supportOutsource > 0 ? `
|
||
<div style="font-size:0.8rem; color:var(--accent-warning); background:rgba(245,158,11,0.08); padding:4px 10px; border-radius:6px; border:1px dashed rgba(245,158,11,0.3);">
|
||
⚠️ 須另行負擔之外包成本: <strong>NT$ ${Math.round(supportOutsource).toLocaleString()}</strong>
|
||
</div>` : ''}
|
||
</div>
|
||
<div style="color:var(--text-dim); font-size:0.8rem; margin-top:0.4rem;">相當於全公司目標的 ${formatPct(supportPct)}%</div>
|
||
<div style="height:6px; background:rgba(255,255,255,0.05); border-radius:4px; overflow:hidden; margin-top:0.75rem; max-width:300px;">
|
||
<div style="width:${supportPct}%; height:100%; background:linear-gradient(90deg,var(--text-muted),var(--text-dim));"></div>
|
||
</div>
|
||
</div>
|
||
<div style="display:flex; align-items:center; gap:2rem;">
|
||
<div>
|
||
<div style="font-size:0.72rem; color:var(--text-dim); text-transform:uppercase; letter-spacing:1px; margin-bottom:0.5rem;">CODA 組成 (純內製 P+A)</div>
|
||
${budgetBadges(0, supportArtistBudget, true)}
|
||
</div>
|
||
<div style="text-align:right;">
|
||
<div style="font-size:0.72rem; color:var(--text-dim); text-transform:uppercase; letter-spacing:1px; margin-bottom:0.5rem;">部門平均日工作 CODA</div>
|
||
<div style="font-size:1.1rem; font-weight:700; color:var(--text-main);"><div class='currency-wrap' style='--symbol-width: 45px; --symbol-gap: 1rem; min-width: 160px;'><span>NT$</span><span>${Math.round(supportAvgDailyCoda).toLocaleString()}</span></div></div>
|
||
</div>
|
||
<div id="coda-chevron-${safeSupportId}" style="color:var(--text-muted); transition:transform 0.3s; margin-left: 0.5rem;">▼</div>
|
||
</div>
|
||
</div>
|
||
${buildArtistTable(pcDept, supportGroups, supportCoda, supportAOraw, safeSupportId, authorizedSupportGroups)}
|
||
</div>
|
||
`;
|
||
}
|
||
} // end renderCoda()
|
||
|
||
function toggleCodaDept(id) {
|
||
const detail = document.getElementById('coda-detail-' + id);
|
||
const chevron = document.getElementById('coda-chevron-' + id);
|
||
if (!detail) return;
|
||
const isOpen = detail.style.display !== 'none';
|
||
detail.style.display = isOpen ? 'none' : 'block';
|
||
if (chevron) { chevron.style.transform = isOpen ? 'rotate(0deg)' : 'rotate(180deg)'; chevron.style.color = isOpen ? 'var(--text-muted)' : 'var(--accent-primary)'; }
|
||
}
|
||
|
||
function toggleCodaGroup(id) {
|
||
const detail = document.getElementById('coda-group-detail-' + id);
|
||
const chevron = document.getElementById('coda-group-chevron-' + id);
|
||
if (!detail) return;
|
||
const isOpen = detail.style.display !== 'none';
|
||
detail.style.display = isOpen ? 'none' : 'block';
|
||
if (chevron) chevron.style.transform = isOpen ? 'rotate(0deg)' : 'rotate(180deg)';
|
||
}
|
||
|
||
// --- Regular contractors are saved on the server (not in HR, not in Git) ---
|
||
let contractorSignature = null;
|
||
let contractorSaveTimer = null;
|
||
|
||
function contractorPayload() {
|
||
return baseData.filter(p => (p.role || '').startsWith('O')).map(p => ({
|
||
row: p.row, name: p.name, title: p.title, company: p.company, dept: p.dept, group: p.group,
|
||
dayrate: p.dayrate, h1Start: p.h1Start, h1End: p.h1End, h2Start: p.h2Start, h2End: p.h2End,
|
||
workRateUsed: p.workRateUsed,
|
||
}));
|
||
}
|
||
|
||
function scheduleContractorSave() {
|
||
if (isSimMode || contractorSignature === null) return;
|
||
const signature = JSON.stringify(contractorPayload());
|
||
if (signature === contractorSignature) return;
|
||
clearTimeout(contractorSaveTimer);
|
||
contractorSaveTimer = setTimeout(() => saveContractorsToServer(signature), 600);
|
||
}
|
||
|
||
async function saveContractorsToServer(signature) {
|
||
const banner = document.getElementById('data-source-banner');
|
||
try {
|
||
const response = await fetch('/api/cost-model/contractors', {
|
||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ contractors: JSON.parse(signature) }),
|
||
});
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
contractorSignature = signature;
|
||
} catch (error) {
|
||
console.error('Unable to save contractors', error);
|
||
banner.textContent = '常態型外包儲存失敗,請重新整理後再試;剛才的外包修改尚未保存。';
|
||
banner.style.color = 'var(--accent-danger)';
|
||
}
|
||
}
|
||
|
||
function saveAndRefresh() {
|
||
scheduleContractorSave();
|
||
globalParams.orgStructure = null; // Force rebuild with correct order and fresh data
|
||
renderDashboard();
|
||
renderPersonnel();
|
||
renderSales();
|
||
renderArtists();
|
||
renderCoda();
|
||
renderVersions();
|
||
const activeView = document.querySelector('.view.active')?.id;
|
||
if (activeView === 'invoice') renderInvoice();
|
||
if (activeView === 'personnel-overview') renderPersonnelOverview();
|
||
if (activeView === 'group') renderGroup();
|
||
}
|
||
|
||
function hardReset() {
|
||
if (confirm('重新載入伺服器提供的合成預覽資料?目前頁面工作階段的修改將會消失。')) {
|
||
location.reload();
|
||
}
|
||
}
|
||
|
||
// --- INIT ---
|
||
// Initial boot handled by the preview-mode window.onload below.
|
||
// --- VERSIONS & RAISE EVENTS LOGIC ---
|
||
function renderVersions() {
|
||
renderRaiseEventsTable();
|
||
renderSnapshotsTable();
|
||
}
|
||
|
||
function renderRaiseEventsTable() {
|
||
const tbody = document.querySelector('#raise-events-table tbody');
|
||
if (!globalParams.raiseEvents || globalParams.raiseEvents.length === 0) {
|
||
tbody.innerHTML = '<tr><td colspan="4" style="text-align:center; color:var(--text-dim); padding:2rem;">目前沒有任何調薪批次</td></tr>';
|
||
return;
|
||
}
|
||
|
||
// Descending order by createdAt
|
||
const events = [...globalParams.raiseEvents].sort((a, b) => b.createdAt - a.createdAt);
|
||
|
||
tbody.innerHTML = events.map(evt => {
|
||
const dateStr = new Date(evt.createdAt).toLocaleString('zh-TW', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||
const count = evt.adjustments ? evt.adjustments.length : 0;
|
||
return `
|
||
<tr>
|
||
<td><div style="font-weight:700; color:var(--text-main);">${evt.name}</div></td>
|
||
<td style="color:var(--text-muted); font-size:0.8rem;">${dateStr}</td>
|
||
<td class="num"><span class="status-pill status-active" style="background:rgba(59,130,246,0.1); color:var(--accent-primary); border:none;">${count} 人</span></td>
|
||
<td>
|
||
<button class="btn btn-outline" onclick="deleteRaiseEvent('${evt.id}')" style="padding: 4px 8px; font-size: 0.75rem; color: var(--accent-danger); border-color: rgba(239,68,68,0.3);">刪除</button>
|
||
</td>
|
||
</tr>
|
||
`;
|
||
}).join('');
|
||
}
|
||
|
||
function addRaiseAdjustmentRow(initData = null) {
|
||
const container = document.getElementById('raise-adjustments-container');
|
||
const rowId = 'adj-row-' + Date.now() + Math.floor(Math.random() * 1000);
|
||
|
||
const current = isSimMode ? simData : baseData;
|
||
// Sorting by department then name
|
||
const personnelOptions = [...current].sort((a, b) => a.dept.localeCompare(b.dept) || a.name.localeCompare(b.name)).map(p => {
|
||
const label = (p.role && p.role.startsWith('O')) ? '日' : '月';
|
||
const selected = (initData && initData.personIdx === p.row) ? 'selected' : '';
|
||
return `<option value="${p.row}" ${selected}>[${p.dept}] ${p.name} (${label}: ${p.salary || p.dayrate})</option>`;
|
||
}).join('');
|
||
|
||
const currentYear = new Date().getFullYear();
|
||
const yearVal = (initData && initData.startYear) ? initData.startYear : currentYear;
|
||
const years = [currentYear - 2, currentYear - 1, currentYear, currentYear + 1, currentYear + 2];
|
||
const yearOptions = years.map(y => {
|
||
const selected = (y == yearVal) ? 'selected' : '';
|
||
return `<option value="${y}" ${selected}>${y}年</option>`;
|
||
}).join('');
|
||
|
||
const months = [3, 4, 9, 10, 1, 2, 5, 6, 7, 8, 11, 12];
|
||
const monthOptions = months.map(m => {
|
||
const selected = (initData && initData.startMonth == m) ? 'selected' : '';
|
||
return `<option value="${m}" ${selected}>${m}月生效</option>`;
|
||
}).join('');
|
||
|
||
const salaryVal = initData ? initData.newSalary : '';
|
||
|
||
const html = `
|
||
<div id="${rowId}" class="adj-row" style="display: grid; grid-template-columns: 2.2fr 80px 1fr 1.2fr auto; gap: 0.5rem; align-items: center; background: rgba(255,255,255,0.03); padding: 0.6rem; border-radius: 8px; border: 1px solid rgba(255,255,255,0.06); margin-bottom: 0.4rem;">
|
||
<select class="modal-input adj-person" style="padding: 6px 10px; font-size: 0.85rem;">
|
||
${personnelOptions}
|
||
</select>
|
||
<select class="modal-input adj-year" style="padding: 6px 5px; font-size: 0.85rem;">
|
||
${yearOptions}
|
||
</select>
|
||
<select class="modal-input adj-month" style="padding: 6px 10px; font-size: 0.85rem;">
|
||
${monthOptions}
|
||
</select>
|
||
<input type="number" class="modal-input adj-salary" value="${salaryVal}" placeholder="💰 新薪資" style="padding: 6px 10px; font-size: 0.85rem;" />
|
||
<button class="btn btn-outline" onclick="document.getElementById('${rowId}').remove()" style="padding: 4px; border: none; font-size: 1.1rem; color: var(--text-dim);">×</button>
|
||
</div>
|
||
`;
|
||
container.insertAdjacentHTML('beforeend', html);
|
||
}
|
||
|
||
function addRaiseEvent() {
|
||
window.editingRaiseEventIdx = undefined;
|
||
document.getElementById('modal-raise-event-name').value = '';
|
||
document.getElementById('raise-adjustments-container').innerHTML = '';
|
||
addRaiseAdjustmentRow();
|
||
|
||
const modal = document.getElementById('create-raise-event-modal');
|
||
if (modal) modal.classList.add('open');
|
||
document.getElementById('modal-raise-event-name').focus();
|
||
}
|
||
|
||
function editRaiseEvent(idx) {
|
||
window.editingRaiseEventIdx = idx;
|
||
const ev = globalParams.raiseEvents[idx];
|
||
document.getElementById('modal-raise-event-name').value = ev.name || ev.description || '未命名事件';
|
||
document.getElementById('raise-adjustments-container').innerHTML = '';
|
||
|
||
if (ev.adjustments && ev.adjustments.length > 0) {
|
||
ev.adjustments.forEach(adj => addRaiseAdjustmentRow(adj));
|
||
} else {
|
||
addRaiseAdjustmentRow();
|
||
}
|
||
|
||
const modal = document.getElementById('create-raise-event-modal');
|
||
if (modal) modal.classList.add('open');
|
||
document.getElementById('modal-raise-event-name').focus();
|
||
}
|
||
|
||
function closeCreateRaiseEventModal() {
|
||
const modal = document.getElementById('create-raise-event-modal');
|
||
if (modal) modal.classList.remove('open');
|
||
}
|
||
|
||
function renderVersions() {
|
||
const container = document.getElementById('raise-events-table-body');
|
||
const kpiGrid = document.getElementById('raise-kpis');
|
||
if (!container) return;
|
||
|
||
const events = globalParams.raiseEvents || [];
|
||
|
||
// 1. Populate Year Filter if empty
|
||
const yearFilterEl = document.getElementById('raise-year-filter');
|
||
const currentY = new Date().getFullYear();
|
||
if (yearFilterEl && yearFilterEl.options.length === 0) {
|
||
let availableYears = new Set([currentY]);
|
||
events.forEach(ev => {
|
||
if(ev.effectiveYear) availableYears.add(ev.effectiveYear);
|
||
if(ev.adjustments) ev.adjustments.forEach(a => availableYears.add(a.startYear || currentY));
|
||
});
|
||
const sortedYears = Array.from(availableYears).sort((a,b)=>b-a);
|
||
yearFilterEl.innerHTML = sortedYears.map(y => `<option value="${y}">${y} 年度調薪</option>`).join('');
|
||
yearFilterEl.value = currentY;
|
||
}
|
||
|
||
const targetYear = yearFilterEl ? parseInt(yearFilterEl.value) : currentY;
|
||
|
||
container.innerHTML = '';
|
||
|
||
let totalAnnualImpact = 0;
|
||
let totalAffectedPeople = 0;
|
||
let deptStats = {}; // { [dept]: { count: 0, cost: 0 } }
|
||
|
||
events.forEach((ev, idx) => {
|
||
const evName = ev.name || ev.description || '未命名事件';
|
||
const adjList = ev.adjustments || [];
|
||
|
||
let hasValidAdjForYear = false;
|
||
let evAnnualImpact = 0;
|
||
let evPersonCount = 0;
|
||
let affectedNames = [];
|
||
|
||
if (ev.monthlyImpact && !adjList.length) {
|
||
// Legacy total impact calculation (Assumed current year)
|
||
let firstMonth = ev.effectiveMonth || 4;
|
||
if (targetYear === currentY) {
|
||
evAnnualImpact = ev.monthlyImpact * (13 - (parseInt(firstMonth) || 4));
|
||
evPersonCount = ev.targetCount || 0;
|
||
hasValidAdjForYear = true;
|
||
|
||
if(!deptStats['舊紀錄未分類']) deptStats['舊紀錄未分類'] = { count: 0, cost: 0 };
|
||
deptStats['舊紀錄未分類'].count += evPersonCount;
|
||
deptStats['舊紀錄未分類'].cost += evAnnualImpact;
|
||
}
|
||
} else {
|
||
// New adjustment-based calculation
|
||
adjList.forEach(adj => {
|
||
const adjYear = adj.startYear || (ev.createdAt ? new Date(ev.createdAt).getFullYear() : currentY);
|
||
if (adjYear !== targetYear) return;
|
||
|
||
hasValidAdjForYear = true;
|
||
const m = parseInt(adj.startMonth) || 4;
|
||
const monthsActive = 13 - m;
|
||
let oldS = adj.oldSalary !== undefined ? adj.oldSalary : parseFloat(baseData.find(b => b.row === adj.personIdx)?.salary || 40000);
|
||
const costDiff = (adj.newSalary - oldS) * monthsActive;
|
||
|
||
evAnnualImpact += costDiff;
|
||
evPersonCount += 1;
|
||
|
||
const p = baseData.find(b => b.row === adj.personIdx);
|
||
affectedNames.push(p ? p.name : '未知');
|
||
|
||
if (p) {
|
||
if(!deptStats[p.dept]) deptStats[p.dept] = { count: 0, cost: 0 };
|
||
deptStats[p.dept].count += 1;
|
||
deptStats[p.dept].cost += costDiff;
|
||
}
|
||
});
|
||
}
|
||
|
||
if (!hasValidAdjForYear) return; // Skip rendering into the table if no adjustments for this year
|
||
|
||
let firstMonth = ev.effectiveMonth || (adjList.length > 0 ? adjList[0].startMonth : '--');
|
||
let namesDisplay = `${evPersonCount} 人`;
|
||
if (affectedNames.length > 0) {
|
||
namesDisplay = affectedNames.length <= 3 ? affectedNames.join(', ') : `${affectedNames.slice(0, 3).join(', ')} 等 ${affectedNames.length} 人`;
|
||
}
|
||
|
||
totalAnnualImpact += evAnnualImpact;
|
||
totalAffectedPeople += evPersonCount;
|
||
|
||
const tr = document.createElement('tr');
|
||
tr.innerHTML = `
|
||
<td style="font-weight:700; color:var(--accent-secondary);">${targetYear}年 ${firstMonth}月</td>
|
||
<td style="font-weight:700; color:var(--text-main);">${evName}</td>
|
||
<td style="font-size:0.85rem; max-width:220px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;" title="${affectedNames.join(', ')}">${namesDisplay}</td>
|
||
<td style="display: flex; gap: 0.5rem; justify-content: flex-end;">
|
||
<button class="btn btn-outline" style="padding:4px 8px; font-size:0.75rem; color:var(--text-main); border-color:var(--border-glass);" onclick="editRaiseEvent(${idx})">✏️ 編輯</button>
|
||
<button class="btn btn-outline" style="padding:4px 8px; font-size:0.75rem; color:var(--accent-danger);" onclick="deleteRaiseEvent(${idx})">刪除</button>
|
||
</td>
|
||
`;
|
||
container.appendChild(tr);
|
||
});
|
||
|
||
if (!container.children.length) {
|
||
container.innerHTML = '<tr><td colspan="4" style="padding:1.5rem; text-align:center; color:var(--text-muted);">本年度尚無調薪事件(目前使用合成資料)</td></tr>';
|
||
}
|
||
|
||
// Render KPI Grid
|
||
if (kpiGrid) {
|
||
let kpiHtml = `
|
||
<div class="card" style="box-shadow: 0 4px 12px rgba(0,0,0,0.1); border-left: 4px solid var(--accent-primary);">
|
||
<div class="card-label">年度受影響總人數</div>
|
||
<div class="card-value">${totalAffectedPeople} 人</div>
|
||
</div>
|
||
<div class="card" style="box-shadow: 0 4px 12px rgba(0,0,0,0.1); border-left: 4px solid var(--accent-warning);">
|
||
<div class="card-label">年度總增額成本 (Est.)</div>
|
||
<div class="card-value" style="color: var(--accent-warning);">NT$ ${Math.round(totalAnnualImpact).toLocaleString()}</div>
|
||
</div>
|
||
`;
|
||
|
||
kpiGrid.style.display = 'grid';
|
||
kpiGrid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(200px, 1fr))';
|
||
kpiGrid.style.gap = '1rem';
|
||
kpiGrid.style.marginBottom = '2rem';
|
||
|
||
const depts = Object.keys(deptStats).sort();
|
||
depts.forEach(dept => {
|
||
const stats = deptStats[dept];
|
||
kpiHtml += `
|
||
<div class="card" style="padding: 1.2rem; border-top: 2px solid rgba(255,255,255,0.05); background: rgba(0,0,0,0.15);">
|
||
<div class="card-label" style="font-size: 0.85rem; margin-bottom: 0.5rem;">[${dept}] 年度調薪</div>
|
||
<div style="font-size: 1.1rem; font-weight: 700; display:flex; align-items:flex-end; gap:0.5rem;">
|
||
<span style="font-size:1.3rem;">${stats.count}</span><span style="font-size:0.8rem; color:var(--text-dim); margin-bottom:2px;">人</span>
|
||
</div>
|
||
<div style="font-size: 0.85rem; color: var(--accent-warning); margin-top: 0.2rem;">NT$ ${Math.round(stats.cost).toLocaleString()}</div>
|
||
</div>
|
||
`;
|
||
});
|
||
kpiGrid.innerHTML = kpiHtml;
|
||
}
|
||
}
|
||
|
||
// Routing
|
||
if (!window._routerHooked) {
|
||
const oldShowView = window.showView;
|
||
window.showView = function(viewId) {
|
||
if (oldShowView) oldShowView(viewId);
|
||
if (viewId === 'versions') renderVersions();
|
||
};
|
||
window._routerHooked = true;
|
||
}
|
||
|
||
function confirmCreateRaiseEvent() {
|
||
const nameEl = document.getElementById('modal-raise-event-name');
|
||
const name = nameEl.value.trim();
|
||
if (!name) { alert('請填寫事件名稱'); nameEl.focus(); return; }
|
||
|
||
const container = document.getElementById('raise-adjustments-container');
|
||
const rows = container.querySelectorAll('.adj-row');
|
||
|
||
let parsedInputs = [];
|
||
let hasError = false;
|
||
|
||
rows.forEach(row => {
|
||
const personRowStr = row.querySelector('.adj-person').value;
|
||
const personRowIdx = parseInt(personRowStr);
|
||
const startYear = parseInt(row.querySelector('.adj-year').value) || new Date().getFullYear();
|
||
const startMonth = parseInt(row.querySelector('.adj-month').value);
|
||
const salaryInput = row.querySelector('.adj-salary');
|
||
const newSalary = parseFloat(salaryInput.value);
|
||
|
||
if (isNaN(newSalary) || newSalary <= 0) {
|
||
salaryInput.style.borderColor = 'var(--accent-danger)';
|
||
hasError = true;
|
||
} else {
|
||
salaryInput.style.borderColor = 'var(--border-glass)';
|
||
parsedInputs.push({ personIdx: personRowIdx, startYear, startMonth, newSalary });
|
||
}
|
||
});
|
||
|
||
if (hasError) { alert('請填寫正確的新薪水數字'); return; }
|
||
if (parsedInputs.length === 0) { alert('請至少新增一位調薪人員'); return; }
|
||
|
||
// Keep the baseline salary intact; the calculation applies dated events.
|
||
const current = isSimMode ? simData : baseData;
|
||
const adjustments = parsedInputs.map(input => {
|
||
const p = current.find(person => person.row === input.personIdx);
|
||
return { ...input, oldSalary: Number(p?.dayrate || p?.salary || 0) };
|
||
});
|
||
|
||
const newEvent = {
|
||
id: (window.editingRaiseEventIdx !== undefined && globalParams.raiseEvents[window.editingRaiseEventIdx].id)
|
||
? globalParams.raiseEvents[window.editingRaiseEventIdx].id : 'evt_' + Date.now(),
|
||
name: name,
|
||
createdAt: Date.now(),
|
||
adjustments: adjustments
|
||
};
|
||
|
||
if (!globalParams.raiseEvents) globalParams.raiseEvents = [];
|
||
|
||
if (window.editingRaiseEventIdx !== undefined) {
|
||
globalParams.raiseEvents[window.editingRaiseEventIdx] = newEvent;
|
||
window.editingRaiseEventIdx = undefined; // reset
|
||
} else {
|
||
globalParams.raiseEvents.push(newEvent);
|
||
}
|
||
|
||
closeCreateRaiseEventModal();
|
||
saveAndRefresh();
|
||
if (typeof renderVersions === 'function') renderVersions();
|
||
}
|
||
|
||
function deleteRaiseEvent(idx) {
|
||
if (confirm("確定要刪除這筆調薪事件嗎?這將會把受影響的薪水自動退回調薪前的狀態。")) {
|
||
if (globalParams.raiseEvents) {
|
||
globalParams.raiseEvents.splice(idx, 1);
|
||
saveAndRefresh();
|
||
if (typeof renderVersions === 'function') renderVersions();
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- SNAPSHOTS LOGIC ---
|
||
let snapshots = []; // @PLACEHOLDER_SNAPSHOTS@
|
||
|
||
function loadSnapshots() {
|
||
// Preview snapshots intentionally live only in memory until a persistence API is designed.
|
||
}
|
||
|
||
function saveSnapshots() {
|
||
// No browser storage: snapshots reset when the preview session ends.
|
||
}
|
||
|
||
function renderSnapshotsTable() {
|
||
loadSnapshots();
|
||
const tbody = document.querySelector('#snapshots-table tbody');
|
||
if (snapshots.length === 0) {
|
||
tbody.innerHTML = '<tr><td colspan="3" style="text-align:center; color:var(--text-dim); padding:2rem;">尚無歷史快照</td></tr>';
|
||
return;
|
||
}
|
||
|
||
const sorted = [...snapshots].sort((a, b) => b.timestamp - a.timestamp);
|
||
tbody.innerHTML = sorted.map(snap => {
|
||
const dateStr = new Date(snap.timestamp).toLocaleString('zh-TW', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||
return `
|
||
<tr>
|
||
<td><div style="font-weight:700; color:var(--text-main);">${snap.name}</div></td>
|
||
<td style="color:var(--text-muted); font-size:0.8rem;">${dateStr}</td>
|
||
<td>
|
||
<button class="btn btn-outline" onclick="loadSnapshot('${snap.id}')" style="padding: 4px 8px; font-size: 0.75rem; margin-right: 4px;">讀取</button>
|
||
<button class="btn btn-outline" onclick="deleteSnapshot('${snap.id}')" style="padding: 4px 8px; font-size: 0.75rem; color: var(--accent-danger); border-color: rgba(239,68,68,0.3);">刪除</button>
|
||
</td>
|
||
</tr>
|
||
`;
|
||
}).join('');
|
||
}
|
||
|
||
function createSnapshot() {
|
||
const name = prompt("請輸入新快照名稱 (例如:2024年4月 第一次結算版)");
|
||
if (!name) return;
|
||
|
||
// Deep clone current state
|
||
const snapshot = {
|
||
id: 'snap_' + Date.now(),
|
||
name: name,
|
||
timestamp: Date.now(),
|
||
data: JSON.parse(JSON.stringify(baseData)),
|
||
params: JSON.parse(JSON.stringify(globalParams))
|
||
};
|
||
|
||
snapshots.push(snapshot);
|
||
saveSnapshots();
|
||
renderSnapshotsTable();
|
||
alert("✅ 快照建立成功!");
|
||
}
|
||
|
||
function loadSnapshot(id) {
|
||
const snap = snapshots.find(s => s.id === id);
|
||
if (!snap) return;
|
||
|
||
if (confirm(`即將載入快照【${snap.name}】。\n這將會覆蓋您目前的工作狀態,請確認您已將目前狀態存為快照。\n確定載入嗎?`)) {
|
||
// Exit simulation mode if active
|
||
if (isSimMode) toggleMode();
|
||
baseData = structuredClone(snap.data);
|
||
globalParams = structuredClone(snap.params);
|
||
if (!globalParams.raiseEvents) globalParams.raiseEvents = [];
|
||
|
||
// Alert immediately because DOM refresh loses context visually temporarily
|
||
saveAndRefresh();
|
||
}
|
||
}
|
||
|
||
function deleteSnapshot(id) {
|
||
if (confirm("確定要刪除此快照嗎?操作無法還原。")) {
|
||
snapshots = snapshots.filter(s => s.id !== id);
|
||
saveSnapshots();
|
||
renderSnapshotsTable();
|
||
}
|
||
}
|
||
|
||
// Temporary local preview identity. This is not authentication or access control.
|
||
function getCurrentUser() {
|
||
return { username: '本機預覽', role: 'admin', dept: '', group: '' };
|
||
}
|
||
|
||
function applyPreviewUI() {
|
||
document.getElementById('auth-avatar-initial').textContent = '預';
|
||
document.getElementById('auth-username-display').textContent = '確認登入狀態中';
|
||
document.getElementById('auth-role-display').textContent = '合成資料預覽';
|
||
document.getElementById('nav-reset-data').style.display = '';
|
||
document.getElementById('mode-toggle').style.display = '';
|
||
document.getElementById('mode-indicator').style.display = '';
|
||
document.getElementById('mode-indicator').textContent = '合成資料預覽';
|
||
}
|
||
|
||
async function applyLoginUI() {
|
||
try {
|
||
const response = await fetch('/api/auth/me', { cache: 'no-store', signal: AbortSignal.timeout(10000) });
|
||
if (response.status === 401) {
|
||
showLoginRequired();
|
||
return false;
|
||
}
|
||
if (!response.ok) throw new Error('無法確認登入狀態');
|
||
const user = await response.json();
|
||
document.getElementById('login-link').style.display = 'none';
|
||
if (user.employeeNumber === 'preview') {
|
||
document.getElementById('auth-username-display').textContent = '本機預覽';
|
||
document.getElementById('auth-role-display').textContent = '本機未啟用公司登入';
|
||
return true;
|
||
}
|
||
const name = user.name || user.employeeNumber;
|
||
document.getElementById('auth-avatar-initial').textContent = name.slice(0, 1);
|
||
document.getElementById('auth-username-display').textContent = name;
|
||
document.getElementById('auth-role-display').textContent = '公司帳號';
|
||
document.getElementById('auth-user-badge').title = '目前登入帳號';
|
||
document.getElementById('logout-form').style.display = '';
|
||
document.getElementById('company-logout-form').style.display = '';
|
||
return true;
|
||
} catch (error) {
|
||
document.getElementById('auth-username-display').textContent = '登入狀態確認失敗';
|
||
document.getElementById('auth-role-display').textContent = '請重新整理或登入';
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
function showLoginRequired() {
|
||
document.getElementById('auth-username-display').textContent = '尚未登入或登入已逾時';
|
||
document.getElementById('auth-role-display').textContent = '登入後即可載入資料';
|
||
document.getElementById('login-link').textContent = '重新登入';
|
||
document.getElementById('login-link').style.display = '';
|
||
document.getElementById('logout-form').style.display = 'none';
|
||
document.getElementById('company-logout-form').style.display = 'none';
|
||
document.getElementById('data-source-banner').textContent = '登入已失效,請按左下角「重新登入」載入資料。';
|
||
}
|
||
|
||
// Revalidate when returning through the browser's back/forward cache.
|
||
window.addEventListener('pageshow', (event) => {
|
||
if (event.persisted) window.location.reload();
|
||
});
|
||
|
||
// --- API-backed preview boot ---
|
||
async function loadBootstrapData() {
|
||
const response = await fetch('/api/bootstrap', { cache: 'no-store', signal: AbortSignal.timeout(10000) });
|
||
if (response.status === 401) {
|
||
showLoginRequired();
|
||
return false;
|
||
}
|
||
const payload = await response.json().catch(() => ({}));
|
||
if (!response.ok) {
|
||
const labels = {
|
||
access_denied: '目前登入的公司帳號不在 PM Board 的允許名單內。',
|
||
hr_not_configured: '本站尚未收到平台提供的 HR Sync 執行期設定;因此沒有使用合成資料替代。',
|
||
hr_exchange_denied: '公司登入成功,但 HR Sync 未核准這個帳號的資料交換權限。',
|
||
hr_endpoint_forbidden: 'HR Sync 已連線,但拒絕目前要求的資料範圍。',
|
||
reauthentication_required: '公司登入已過期,請重新登入。',
|
||
hr_unavailable: 'HR Sync 暫時無法回應,請稍後重新整理。',
|
||
hr_target_unavailable: 'HR Sync 服務目前尚未可用。'
|
||
};
|
||
throw new Error(labels[payload.error] || `HR 試算資料讀取失敗(HTTP ${response.status})`);
|
||
}
|
||
if (!['synthetic-demo', 'hr-sync-2027-planning'].includes(payload.source) || !Array.isArray(payload.baseData) || !payload.globalParams) {
|
||
throw new Error('伺服器回傳格式不符。');
|
||
}
|
||
baseData = payload.baseData;
|
||
globalParams = payload.globalParams;
|
||
contractorSignature = JSON.stringify(contractorPayload());
|
||
const banner = document.getElementById('data-source-banner');
|
||
if (payload.source === 'hr-sync-2027-planning') {
|
||
const summary = payload.summary || {};
|
||
banner.textContent = `2027 HR 試算|已轉入 ${summary.activeEmployees || 0} 位 HR 在職人員;${summary.needsReview || 0} 位待確認 P/A、管理職或薪資,暫不納入正式總額。時薪先按每週 5 天、每天 8 小時計算;H1 預設為 1–6 月。常態型外包 ${summary.legacyContractors || 0} 位,在本站手動維護並儲存。`;
|
||
} else {
|
||
banner.textContent = '合成資料預覽|姓名、薪資與參數皆為虛構資料;修改只保留在目前頁面工作階段。';
|
||
}
|
||
return true;
|
||
}
|
||
|
||
function bootApp() {
|
||
saveAndRefresh();
|
||
}
|
||
|
||
window.onload = async () => {
|
||
applyPreviewUI();
|
||
try {
|
||
if (!await applyLoginUI()) return;
|
||
if (!await loadBootstrapData()) return;
|
||
bootApp();
|
||
} catch (error) {
|
||
console.error(error);
|
||
const banner = document.getElementById('data-source-banner');
|
||
banner.textContent = `無法載入預覽資料:${error.message}`;
|
||
banner.style.color = 'var(--accent-danger)';
|
||
}
|
||
};
|
||
|
||
</script>
|
||
<!-- ============ ADD PERSON MODAL ============ -->
|
||
<div id="add-person-modal" class="modal-backdrop" onclick="if(event.target===this)closeAddPersonModal()">
|
||
<div class="modal-box" role="dialog" aria-modal="true" aria-labelledby="modal-title">
|
||
<div class="modal-title" id="modal-title">➕ 新增人員</div>
|
||
|
||
<div class="modal-grid">
|
||
<!-- 姓名 -->
|
||
<div class="modal-field">
|
||
<div class="modal-label">姓名 Name</div>
|
||
<input id="modal-name" class="modal-input" type="text" placeholder="請輸入姓名" />
|
||
</div>
|
||
<!-- 職稱 -->
|
||
<div class="modal-field">
|
||
<div class="modal-label">職稱 Title</div>
|
||
<input id="modal-title-field" class="modal-input" type="text" placeholder="例:資深特效師" />
|
||
</div>
|
||
<!-- 部門 -->
|
||
<div class="modal-field">
|
||
<div class="modal-label">部門 Department</div>
|
||
<select id="modal-dept" class="modal-input" onchange="addPersonModalUpdateGroups()">
|
||
</select>
|
||
</div>
|
||
<!-- 組別 -->
|
||
<div class="modal-field">
|
||
<div class="modal-label">組別 Group</div>
|
||
<select id="modal-group" class="modal-input">
|
||
</select>
|
||
</div>
|
||
<!-- 職能角色 -->
|
||
<div class="modal-field">
|
||
<div class="modal-label">職能角色 Role</div>
|
||
<select id="modal-role" class="modal-input" onchange="addPersonModalUpdateSalaryLabel()">
|
||
<option value="P - 製作人">P - 製作人 (Producer)</option>
|
||
<option value="P - 執行製作">P - 執行製作 (PM)</option>
|
||
<option value="A - 藝術家" selected>A - 藝術家 (Artist)</option>
|
||
<option value="A - 特效師">A - 特效師 (FX Artist)</option>
|
||
<option value="A - 動畫師">A - 動畫師 (Animator)</option>
|
||
<option value="A - 剪輯">A - 剪輯 (Editor)</option>
|
||
<option value="A - 燈光">A - 燈光 (Lighter)</option>
|
||
<option value="O - 外包">O - 外包 (Outsource)</option>
|
||
</select>
|
||
</div>
|
||
<!-- 管理職 -->
|
||
<div class="modal-field" style="justify-content: flex-end;">
|
||
<div class="modal-label">屬性</div>
|
||
<label class="modal-checkbox-row">
|
||
<input type="checkbox" id="modal-is-manager" />
|
||
<label for="modal-is-manager">管理職 (Manager)</label>
|
||
</label>
|
||
</div>
|
||
<!-- 薪資 -->
|
||
<div class="modal-field full-width">
|
||
<div class="modal-label" id="modal-salary-label">月薪 Monthly Salary</div>
|
||
<div class="modal-salary-wrapper">
|
||
<div class="modal-salary-prefix" id="modal-salary-prefix">NT$ / 月</div>
|
||
<input id="modal-salary" class="modal-salary-input" type="number" placeholder="例:40000" />
|
||
</div>
|
||
</div>
|
||
<!-- H1 -->
|
||
<div class="modal-field">
|
||
<div class="modal-label">H1 上半年合約期間</div>
|
||
<div class="modal-h-period">
|
||
<select id="modal-h1s" class="modal-input">
|
||
<option value="">— 無</option>
|
||
<option value="1">1月</option>
|
||
<option value="2">2月</option>
|
||
<option value="3">3月</option>
|
||
<option value="4">4月</option>
|
||
<option value="5">5月</option>
|
||
<option value="6">6月</option>
|
||
</select>
|
||
<span>→</span>
|
||
<select id="modal-h1e" class="modal-input">
|
||
<option value="">— 無</option>
|
||
<option value="1">1月</option>
|
||
<option value="2">2月</option>
|
||
<option value="3">3月</option>
|
||
<option value="4">4月</option>
|
||
<option value="5">5月</option>
|
||
<option value="6">6月</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
<!-- H2 -->
|
||
<div class="modal-field">
|
||
<div class="modal-label">H2 下半年合約期間</div>
|
||
<div class="modal-h-period">
|
||
<select id="modal-h2s" class="modal-input">
|
||
<option value="">— 無</option>
|
||
<option value="7">7月</option>
|
||
<option value="8">8月</option>
|
||
<option value="9">9月</option>
|
||
<option value="10">10月</option>
|
||
<option value="11">11月</option>
|
||
<option value="12">12月</option>
|
||
</select>
|
||
<span>→</span>
|
||
<select id="modal-h2e" class="modal-input">
|
||
<option value="">— 無</option>
|
||
<option value="7">7月</option>
|
||
<option value="8">8月</option>
|
||
<option value="9">9月</option>
|
||
<option value="10">10月</option>
|
||
<option value="11">11月</option>
|
||
<option value="12">12月</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="modal-footer">
|
||
<button class="btn btn-outline" onclick="closeAddPersonModal()">取消</button>
|
||
<button class="btn btn-primary" onclick="confirmAddPerson()">✓ 確認新增</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- CREATE RAISE EVENT MODAL -->
|
||
<div class="modal-backdrop" id="create-raise-event-modal"
|
||
onclick="if(event.target===this)closeCreateRaiseEventModal()">
|
||
<div class="modal-box" role="dialog" aria-modal="true" style="max-width: 600px;">
|
||
<div class="modal-title">📝 新增調薪批次事件</div>
|
||
<div class="modal-grid" style="grid-template-columns: 1fr;">
|
||
<div class="modal-field">
|
||
<div class="modal-label">事件名稱</div>
|
||
<input id="modal-raise-event-name" class="modal-input" type="text" placeholder="例:2024年4月 全體調薪" />
|
||
</div>
|
||
</div>
|
||
|
||
<div style="margin-top: 1.5rem;">
|
||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
|
||
<div class="modal-label" style="margin: 0;">調薪名單</div>
|
||
<div style="display:flex; gap:8px;">
|
||
<input type="text" id="raise-search-filter" class="modal-input" placeholder="🔍 搜尋姓名..."
|
||
style="width: 151px; padding: 4px 8px; font-size: 0.75rem;"
|
||
onkeyup="filterRaisePersonnel()">
|
||
<button class="btn btn-outline" onclick="addRaiseAdjustmentRow()"
|
||
style="padding: 4px 8px; font-size: 0.75rem;">+ 新增人員</button>
|
||
</div>
|
||
</div>
|
||
<!-- Container for dynamic adjustment rows -->
|
||
<div id="raise-adjustments-container"
|
||
style="display: flex; flex-direction: column; gap: 0.5rem; max-height: 250px; overflow-y: auto; padding-right: 0.5rem;">
|
||
|
||
</div>
|
||
</div>
|
||
|
||
<div class="modal-footer" style="margin-top: 1.5rem;">
|
||
<button class="btn btn-outline" onclick="closeCreateRaiseEventModal()">取消</button>
|
||
<button class="btn btn-primary" onclick="confirmCreateRaiseEvent()">✓ 確認建立</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ============ IMPORT REVIEW MODAL ============ -->
|
||
<div id="import-review-modal" class="modal-backdrop" style="display:none;" onclick="if(event.target===this)closeImportReview()">
|
||
<div class="modal-box" style="max-width: 800px; width: 90%;">
|
||
<div class="modal-header">
|
||
<div class="modal-title">🔍 匯入資料對照與診斷報表</div>
|
||
<button class="modal-close" onclick="closeImportReview()">×</button>
|
||
</div>
|
||
<div class="modal-body" style="padding-top:0;">
|
||
<p style="color: var(--text-muted); margin-bottom: 1.5rem; font-size: 0.9rem;">系統已將 CSV 資料與目前名單進行比對,以下為詳細差異報告:</p>
|
||
<div id="import-summary"></div>
|
||
<div id="import-details" style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-glass); border-radius: 12px; padding: 1.5rem; margin-top: 1rem;"></div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button class="btn btn-outline" onclick="closeImportReview()">取消匯入</button>
|
||
<button class="btn btn-primary" onclick="confirmImport()">✓ 確認更新資料</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</body>
|
||
|
||
</html>
|