FinancePage.tsx 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  2. import { Building2, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, Clock3, Pencil, Trash2, Wallet } from 'lucide-react';
  3. import { useEffect, useMemo, useState } from 'react';
  4. import { useTranslation } from 'react-i18next';
  5. import { api, type ManualPrintRequest, type TransactionEditRequest, type WalletTransaction } from '../api/client';
  6. import { Button } from '../components/Button';
  7. import { Card, CardContent, CardHeader } from '../components/Card';
  8. import { ConfirmModal } from '../components/ConfirmModal';
  9. import { useAuth } from '../contexts/AuthContext';
  10. import { useToast } from '../contexts/ToastContext';
  11. import { getCurrencySymbol } from '../utils/currency';
  12. import { parseUTCDate } from '../utils/date';
  13. type PartialPrintStatus = 'aborted' | 'failed' | 'cancelled';
  14. interface ParsedPrintChargeDescription {
  15. isPartial: boolean;
  16. partialType: PartialPrintStatus | null;
  17. cleanedDescription: string | null;
  18. }
  19. const PRINT_CHARGE_PARTIAL_REGEX = /\[(aborted|failed|cancelled):\s*([^\]]*)\]/i;
  20. function parsePrintChargeDescription(description: string | null): ParsedPrintChargeDescription {
  21. if (!description) {
  22. return { isPartial: false, partialType: null, cleanedDescription: null };
  23. }
  24. const match = description.match(PRINT_CHARGE_PARTIAL_REGEX);
  25. if (!match) {
  26. return { isPartial: false, partialType: null, cleanedDescription: description };
  27. }
  28. const cleanedDescription = description.replace(match[0], '').trim();
  29. return {
  30. isPartial: true,
  31. partialType: match[1].toLowerCase() as PartialPrintStatus,
  32. cleanedDescription: cleanedDescription || null,
  33. };
  34. }
  35. function formatTimestamp(value: string | null, locale: string): string {
  36. if (!value) return '-';
  37. const parsed = parseUTCDate(value);
  38. if (!parsed) return value;
  39. return parsed.toLocaleString(locale);
  40. }
  41. function parseBudgetValue(raw: string): number | null {
  42. const trimmed = raw.trim();
  43. if (!trimmed) return null;
  44. const parsed = Number.parseFloat(trimmed);
  45. return Number.isFinite(parsed) ? parsed : null;
  46. }
  47. function formatLocalDateTime(value: Date): string {
  48. const year = value.getFullYear();
  49. const month = String(value.getMonth() + 1).padStart(2, '0');
  50. const day = String(value.getDate()).padStart(2, '0');
  51. const hours = String(value.getHours()).padStart(2, '0');
  52. const minutes = String(value.getMinutes()).padStart(2, '0');
  53. return `${year}-${month}-${day}T${hours}:${minutes}`;
  54. }
  55. const fieldClass =
  56. 'w-full px-3 py-2 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:outline-none focus:ring-1 focus:ring-bambu-green';
  57. const labelClass = 'block text-sm font-medium text-white mb-1';
  58. const tableHeadCellClass = 'px-4 py-3 text-left text-bambu-gray font-medium';
  59. const tableCellClass = 'px-4 py-3 align-top text-white';
  60. interface FinanceModalProps {
  61. title: string;
  62. onClose: () => void;
  63. children: React.ReactNode;
  64. size?: 'sm' | 'md' | 'lg';
  65. }
  66. function FinanceModal({ title, onClose, children, size = 'md' }: FinanceModalProps) {
  67. const { t } = useTranslation();
  68. const sizeClass = size === 'sm' ? 'max-w-xl' : size === 'lg' ? 'max-w-6xl' : 'max-w-4xl';
  69. return (
  70. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
  71. <div className={`w-full ${sizeClass} overflow-hidden rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary`}>
  72. <div className="flex items-center justify-between border-b border-bambu-dark-tertiary px-4 py-3">
  73. <h3 className="text-lg font-semibold text-white">{title}</h3>
  74. <Button size="sm" variant="secondary" onClick={onClose}>{t('common.close', 'Close')}</Button>
  75. </div>
  76. <div className="max-h-[75vh] overflow-auto p-4">{children}</div>
  77. </div>
  78. </div>
  79. );
  80. }
  81. export function FinancePage() {
  82. const { t, i18n } = useTranslation();
  83. const { hasPermission, user } = useAuth();
  84. const { showToast } = useToast();
  85. const queryClient = useQueryClient();
  86. const canReadOwn = hasPermission('cost_centers:read_own');
  87. const canReadAllFinance = hasPermission('cost_centers:read_all');
  88. const canCreateCostCenters = hasPermission('cost_centers:create');
  89. const canUpdateCostCenters = hasPermission('cost_centers:modify');
  90. const canUpdateBudgets = hasPermission('cost_centers:modify');
  91. const canAssignCostCenterUsers = hasPermission('cost_centers:modify');
  92. const canAdjustWallet = hasPermission('cost_centers:modify');
  93. // Finance only ever labels a user or picks one to assign, so the slim
  94. // listing suffices -- and a billing operator should not need the admin-level
  95. // users:read (emails, roles, permission sets) to staff a cost center (#1894).
  96. const canReadUsers = hasPermission('users:read_slim') || hasPermission('users:read');
  97. const canAccessAllCostCenters =
  98. canReadAllFinance ||
  99. canCreateCostCenters ||
  100. canUpdateCostCenters ||
  101. canUpdateBudgets ||
  102. canAssignCostCenterUsers ||
  103. canAdjustWallet;
  104. const canAccessFinance = canReadOwn || canAccessAllCostCenters;
  105. const canViewMyCostCenters = canAccessFinance;
  106. const [newCenterName, setNewCenterName] = useState('');
  107. const [newCenterBudgetMode, setNewCenterBudgetMode] = useState<'total' | 'monthly'>('monthly');
  108. const [newCenterBudgetValue, setNewCenterBudgetValue] = useState('');
  109. const [selectedUserId, setSelectedUserId] = useState<number | null>(null);
  110. const [selectedAdjustmentType, setSelectedAdjustmentType] = useState<'deposit' | 'withdraw'>('deposit');
  111. const [adjustmentAmount, setAdjustmentAmount] = useState('');
  112. const [adjustmentDescription, setAdjustmentDescription] = useState('');
  113. const [adjustmentCostCenterId, setAdjustmentCostCenterId] = useState<number | null>(null);
  114. const [selectedManageCenterId, setSelectedManageCenterId] = useState<number | null>(null);
  115. const [memberUserId, setMemberUserId] = useState<number | null>(null);
  116. const [memberCanPrint, setMemberCanPrint] = useState(true);
  117. const [txOffset, setTxOffset] = useState(0);
  118. const txLimit = 50;
  119. const [txTypeFilter, setTxTypeFilter] = useState<string>('all');
  120. const [txCostCenterFilter, setTxCostCenterFilter] = useState<number | 'all'>('all');
  121. const [showCreateCenterModal, setShowCreateCenterModal] = useState(false);
  122. const [showAdjustWalletModal, setShowAdjustWalletModal] = useState(false);
  123. const [showMembersModal, setShowMembersModal] = useState(false);
  124. const [showEditCenterModal, setShowEditCenterModal] = useState(false);
  125. const [financeViewMode, setFinanceViewMode] = useState<'personal' | 'admin'>('personal');
  126. const [selectedEditCenterId, setSelectedEditCenterId] = useState<number | null>(null);
  127. const [editCenterName, setEditCenterName] = useState('');
  128. const [editCenterBudgetMode, setEditCenterBudgetMode] = useState<'total' | 'monthly'>('monthly');
  129. const [editCenterBudgetValue, setEditCenterBudgetValue] = useState('');
  130. const [showEditTransactionModal, setShowEditTransactionModal] = useState(false);
  131. const [selectedEditTransactionId, setSelectedEditTransactionId] = useState<number | null>(null);
  132. const [editTransactionUserId, setEditTransactionUserId] = useState<number | null>(null);
  133. const [editTransactionCostCenterId, setEditTransactionCostCenterId] = useState<number | null>(null);
  134. const [editTransactionAmount, setEditTransactionAmount] = useState('');
  135. const [editTransactionDescription, setEditTransactionDescription] = useState('');
  136. const [showManualPrintModal, setShowManualPrintModal] = useState(false);
  137. const [manualPrintUserId, setManualPrintUserId] = useState<number | null>(null);
  138. const [manualPrintCostCenterId, setManualPrintCostCenterId] = useState<number | null>(null);
  139. const [manualPrintAmount, setManualPrintAmount] = useState('');
  140. const [manualPrintDescription, setManualPrintDescription] = useState('');
  141. const [manualPrintDate, setManualPrintDate] = useState(formatLocalDateTime(new Date()));
  142. const [pendingDeleteCenter, setPendingDeleteCenter] = useState<{ id: number; name: string } | null>(null);
  143. const [pendingDeleteTransactionId, setPendingDeleteTransactionId] = useState<number | null>(null);
  144. const hasAdminFinanceControls =
  145. canReadAllFinance ||
  146. canCreateCostCenters ||
  147. canUpdateCostCenters ||
  148. canUpdateBudgets ||
  149. (canAdjustWallet && canReadUsers) ||
  150. (canAssignCostCenterUsers && canReadUsers);
  151. useEffect(() => {
  152. if (!hasAdminFinanceControls) {
  153. setFinanceViewMode('personal');
  154. }
  155. }, [hasAdminFinanceControls]);
  156. const { data: wallet, isLoading: walletLoading } = useQuery({
  157. queryKey: ['finance', 'me', 'balance'],
  158. queryFn: api.getMyBalance,
  159. enabled: canReadOwn,
  160. });
  161. // Currency comes from the install setting, like every other page. Read from
  162. // /settings/ui-flags rather than /settings, which needs SETTINGS_READ that a
  163. // cost_centers:read_own user does not have (#3023). The Layout already holds
  164. // this query key, so this is served from cache.
  165. const { data: uiFlags } = useQuery({
  166. queryKey: ['ui-flags'],
  167. queryFn: api.getUiFlags,
  168. });
  169. const { data: transactionsResponse, isLoading: personalTxLoading } = useQuery({
  170. queryKey: ['finance', 'me', 'transactions', txLimit, txOffset],
  171. queryFn: () => api.getMyTransactions(txLimit, txOffset),
  172. enabled: canReadOwn,
  173. });
  174. const { data: adminTransactionsResponse, isLoading: adminTxLoading } = useQuery({
  175. queryKey: ['finance', 'transactions', txLimit, txOffset],
  176. queryFn: () => api.getAllTransactions(txLimit, txOffset),
  177. enabled: financeViewMode === 'admin' && canReadAllFinance,
  178. });
  179. const { data: costCenters, isLoading: centersLoading } = useQuery({
  180. queryKey: ['finance', 'cost-centers', financeViewMode],
  181. queryFn: () => (financeViewMode === 'admin' && canAccessAllCostCenters ? api.listCostCenters(true) : api.getMyCostCenters()),
  182. enabled: canViewMyCostCenters,
  183. });
  184. const { data: users } = useQuery({
  185. queryKey: ['users', 'slim'],
  186. queryFn: api.getUsersSlim,
  187. enabled: canReadUsers && (canViewMyCostCenters || canAdjustWallet || canAssignCostCenterUsers),
  188. });
  189. const { data: selectedCenterDetail } = useQuery({
  190. queryKey: ['finance', 'cost-center', selectedManageCenterId],
  191. queryFn: () => api.getCostCenter(selectedManageCenterId!),
  192. enabled: canAssignCostCenterUsers && selectedManageCenterId != null,
  193. });
  194. useEffect(() => {
  195. if (!users || users.length === 0) return;
  196. if (selectedUserId != null && users.some((u) => u.id === selectedUserId)) return;
  197. setSelectedUserId(users[0].id);
  198. }, [users, selectedUserId]);
  199. useEffect(() => {
  200. if (!canAssignCostCenterUsers) return;
  201. const sharedCenters = (costCenters || []).filter((c) => !c.is_private);
  202. if (sharedCenters.length === 0) {
  203. setSelectedManageCenterId(null);
  204. return;
  205. }
  206. if (selectedManageCenterId != null && sharedCenters.some((c) => c.id === selectedManageCenterId)) return;
  207. setSelectedManageCenterId(sharedCenters[0].id);
  208. }, [canAssignCostCenterUsers, costCenters, selectedManageCenterId]);
  209. useEffect(() => {
  210. if (!canAssignCostCenterUsers || !users || users.length === 0) return;
  211. const existingMemberIds = new Set((selectedCenterDetail?.members || []).map((m) => m.user_id));
  212. const firstAvailable = users.find((u) => !existingMemberIds.has(u.id));
  213. setMemberUserId(firstAvailable ? firstAvailable.id : null);
  214. }, [canAssignCostCenterUsers, users, selectedCenterDetail]);
  215. useEffect(() => {
  216. if (!showEditCenterModal) return;
  217. const editableCenters = costCenters || [];
  218. if (editableCenters.length === 0) {
  219. setSelectedEditCenterId(null);
  220. return;
  221. }
  222. if (selectedEditCenterId != null && editableCenters.some((center) => center.id === selectedEditCenterId)) return;
  223. setSelectedEditCenterId(editableCenters[0].id);
  224. }, [showEditCenterModal, selectedEditCenterId, costCenters]);
  225. useEffect(() => {
  226. if (!showEditCenterModal || selectedEditCenterId == null) return;
  227. const center = (costCenters || []).find((entry) => entry.id === selectedEditCenterId);
  228. if (!center) return;
  229. setEditCenterName(center.name);
  230. if (center.budget_mode === 'total') {
  231. setEditCenterBudgetMode('total');
  232. setEditCenterBudgetValue(center.total_budget == null ? '' : String(center.total_budget));
  233. return;
  234. }
  235. setEditCenterBudgetMode('monthly');
  236. setEditCenterBudgetValue(center.monthly_budget == null ? '' : String(center.monthly_budget));
  237. }, [showEditCenterModal, selectedEditCenterId, costCenters]);
  238. const createCostCenterMutation = useMutation({
  239. mutationFn: () =>
  240. api.createCostCenter({
  241. name: newCenterName.trim(),
  242. total_budget: newCenterBudgetMode === 'total' ? parseBudgetValue(newCenterBudgetValue) : null,
  243. monthly_budget: newCenterBudgetMode === 'monthly' ? parseBudgetValue(newCenterBudgetValue) : null,
  244. is_active: true,
  245. }),
  246. onSuccess: () => {
  247. queryClient.invalidateQueries({ queryKey: ['finance'] });
  248. setNewCenterName('');
  249. setNewCenterBudgetValue('');
  250. showToast(t('finance.createdCostCenter', 'Cost center created'));
  251. },
  252. onError: (error: Error) => {
  253. showToast(error.message || t('finance.createCostCenterFailed', 'Failed to create cost center'), 'error');
  254. },
  255. });
  256. const updateBudgetMutation = useMutation({
  257. mutationFn: ({ costCenterId, value, mode }: { costCenterId: number; value: string; mode: 'total' | 'monthly' }) =>
  258. api.updateCostCenterBudgets(costCenterId, {
  259. total_budget: mode === 'total' ? parseBudgetValue(value) : null,
  260. monthly_budget: mode === 'monthly' ? parseBudgetValue(value) : null,
  261. }),
  262. });
  263. const updateCostCenterMutation = useMutation({
  264. mutationFn: ({ costCenterId, name }: { costCenterId: number; name: string }) =>
  265. api.updateCostCenter(costCenterId, {
  266. name,
  267. }),
  268. });
  269. const deleteCostCenterMutation = useMutation({
  270. mutationFn: (costCenterId: number) => api.deleteCostCenter(costCenterId),
  271. });
  272. const deleteTransactionMutation = useMutation({
  273. mutationFn: (transactionId: number) => api.deleteTransaction(transactionId),
  274. onSuccess: () => {
  275. queryClient.invalidateQueries({ queryKey: ['finance'] });
  276. showToast(t('finance.transactionDeleted', 'Transaction deleted'));
  277. },
  278. onError: (error: Error) => {
  279. showToast(error.message || t('finance.deleteTransactionFailed', 'Failed to delete transaction'), 'error');
  280. },
  281. });
  282. const editTransactionMutation = useMutation({
  283. mutationFn: (payload: { transactionId: number; data: TransactionEditRequest }) =>
  284. api.editTransaction(payload.transactionId, payload.data),
  285. onSuccess: () => {
  286. queryClient.invalidateQueries({ queryKey: ['finance'] });
  287. showToast(t('finance.transactionEdited', 'Transaction updated and ledger recalculated'));
  288. setShowEditTransactionModal(false);
  289. },
  290. onError: (error: Error) => {
  291. showToast(error.message || t('finance.editTransactionFailed', 'Failed to edit transaction'), 'error');
  292. },
  293. });
  294. const manualPrintMutation = useMutation({
  295. mutationFn: (data: ManualPrintRequest) => api.createManualPrint(data),
  296. onSuccess: () => {
  297. queryClient.invalidateQueries({ queryKey: ['finance'] });
  298. showToast(t('finance.manualPrintCreated', 'Manual print charge added and ledger recalculated'));
  299. setShowManualPrintModal(false);
  300. setManualPrintUserId(null);
  301. setManualPrintCostCenterId(null);
  302. setManualPrintAmount('');
  303. setManualPrintDescription('');
  304. setManualPrintDate(formatLocalDateTime(new Date()));
  305. },
  306. onError: (error: Error) => {
  307. showToast(error.message || t('finance.manualPrintFailed', 'Failed to create manual print'), 'error');
  308. },
  309. });
  310. const depositMutation = useMutation({
  311. mutationFn: (payload: { userId: number; amount: number; description?: string; costCenterId?: number | null }) =>
  312. api.depositUserBalance(payload.userId, {
  313. amount: payload.amount,
  314. description: payload.description,
  315. cost_center_id: payload.costCenterId ?? null,
  316. }),
  317. });
  318. const withdrawMutation = useMutation({
  319. mutationFn: (payload: { userId: number; amount: number; description?: string; costCenterId?: number | null }) =>
  320. api.withdrawUserBalance(payload.userId, {
  321. amount: payload.amount,
  322. description: payload.description,
  323. cost_center_id: payload.costCenterId ?? null,
  324. }),
  325. });
  326. const upsertMemberMutation = useMutation({
  327. mutationFn: (payload: { costCenterId: number; userId: number; canPrint: boolean }) =>
  328. api.upsertCostCenterMember(payload.costCenterId, {
  329. user_id: payload.userId,
  330. can_print: payload.canPrint,
  331. }),
  332. onSuccess: () => {
  333. queryClient.invalidateQueries({ queryKey: ['finance'] });
  334. showToast(t('finance.memberSaved', 'Member saved'));
  335. },
  336. onError: (error: Error) => {
  337. showToast(error.message || t('finance.memberSaveFailed', 'Failed to save member'), 'error');
  338. },
  339. });
  340. const removeMemberMutation = useMutation({
  341. mutationFn: (payload: { costCenterId: number; userId: number }) =>
  342. api.removeCostCenterMember(payload.costCenterId, payload.userId),
  343. onSuccess: () => {
  344. queryClient.invalidateQueries({ queryKey: ['finance'] });
  345. showToast(t('finance.memberRemoved', 'Member removed'));
  346. },
  347. onError: (error: Error) => {
  348. showToast(error.message || t('finance.memberRemoveFailed', 'Failed to remove member'), 'error');
  349. },
  350. });
  351. const isAdjustingWallet = depositMutation.isPending || withdrawMutation.isPending;
  352. const handleCreateCostCenter = () => {
  353. if (!newCenterName.trim()) {
  354. showToast(t('finance.costCenterNameRequired', 'Cost center name is required'), 'error');
  355. return;
  356. }
  357. createCostCenterMutation.mutate();
  358. };
  359. const handleSaveEditedCenter = async () => {
  360. if (selectedEditCenterId == null) {
  361. showToast(t('finance.selectCostCenter', 'Please select a cost center'), 'error');
  362. return;
  363. }
  364. const name = editCenterName.trim();
  365. if (!name) {
  366. showToast(t('finance.costCenterNameRequired', 'Cost center name is required'), 'error');
  367. return;
  368. }
  369. try {
  370. if (canUpdateCostCenters) {
  371. await updateCostCenterMutation.mutateAsync({ costCenterId: selectedEditCenterId, name });
  372. }
  373. if (canUpdateBudgets) {
  374. await updateBudgetMutation.mutateAsync({
  375. costCenterId: selectedEditCenterId,
  376. mode: editCenterBudgetMode,
  377. value: editCenterBudgetValue,
  378. });
  379. }
  380. queryClient.invalidateQueries({ queryKey: ['finance'] });
  381. showToast(t('finance.costCenterUpdated', 'Cost center updated'));
  382. setShowEditCenterModal(false);
  383. } catch (error) {
  384. showToast((error as Error).message || t('finance.costCenterUpdateFailed', 'Failed to update cost center'), 'error');
  385. }
  386. };
  387. const handleOpenEditCenter = (costCenterId: number) => {
  388. const center = (costCenters || []).find((entry) => entry.id === costCenterId);
  389. if (!center) return;
  390. setSelectedEditCenterId(center.id);
  391. setEditCenterName(center.name);
  392. if (center.budget_mode === 'total') {
  393. setEditCenterBudgetMode('total');
  394. setEditCenterBudgetValue(center.total_budget == null ? '' : String(center.total_budget));
  395. } else {
  396. setEditCenterBudgetMode('monthly');
  397. setEditCenterBudgetValue(center.monthly_budget == null ? '' : String(center.monthly_budget));
  398. }
  399. setShowEditCenterModal(true);
  400. };
  401. const confirmDeleteCenter = async () => {
  402. if (!pendingDeleteCenter) return;
  403. try {
  404. await deleteCostCenterMutation.mutateAsync(pendingDeleteCenter.id);
  405. queryClient.invalidateQueries({ queryKey: ['finance'] });
  406. if (selectedManageCenterId === pendingDeleteCenter.id) {
  407. setSelectedManageCenterId(null);
  408. }
  409. showToast(t('finance.costCenterDeleted', 'Cost center deleted'));
  410. } catch (error) {
  411. showToast((error as Error).message || t('finance.costCenterDeleteFailed', 'Failed to delete cost center'), 'error');
  412. } finally {
  413. setPendingDeleteCenter(null);
  414. }
  415. };
  416. const confirmDeleteTransaction = () => {
  417. if (pendingDeleteTransactionId == null) return;
  418. deleteTransactionMutation.mutate(pendingDeleteTransactionId, {
  419. onSettled: () => setPendingDeleteTransactionId(null),
  420. });
  421. };
  422. const handleEditTransaction = (tx: WalletTransaction) => {
  423. setSelectedEditTransactionId(tx.id);
  424. setEditTransactionUserId(tx.user_id);
  425. setEditTransactionCostCenterId(tx.cost_center_id);
  426. setEditTransactionAmount(String(tx.amount));
  427. setEditTransactionDescription(tx.description || '');
  428. setShowEditTransactionModal(true);
  429. };
  430. const handleSaveEditTransaction = async () => {
  431. if (selectedEditTransactionId == null) return;
  432. const amount = editTransactionAmount ? Number.parseFloat(editTransactionAmount) : null;
  433. if (amount !== null && !Number.isFinite(amount)) {
  434. showToast(t('finance.amountInvalid', 'Amount must be a valid number'), 'error');
  435. return;
  436. }
  437. editTransactionMutation.mutate({
  438. transactionId: selectedEditTransactionId,
  439. data: {
  440. user_id: editTransactionUserId || undefined,
  441. cost_center_id: editTransactionCostCenterId || undefined,
  442. amount: amount ?? undefined,
  443. description: editTransactionDescription || undefined,
  444. },
  445. });
  446. };
  447. const handleSaveManualPrint = async () => {
  448. if (manualPrintUserId == null) {
  449. showToast(t('finance.userRequired', 'Please select a user'), 'error');
  450. return;
  451. }
  452. if (manualPrintCostCenterId == null) {
  453. showToast(t('finance.costCenterRequired', 'Please select a cost center'), 'error');
  454. return;
  455. }
  456. let amount = manualPrintAmount ? Number.parseFloat(manualPrintAmount) : null;
  457. if (amount === null || !Number.isFinite(amount)) {
  458. showToast(t('finance.amountInvalid', 'Amount must be a valid number'), 'error');
  459. return;
  460. }
  461. amount = Math.abs(amount);
  462. manualPrintMutation.mutate({
  463. user_id: manualPrintUserId,
  464. cost_center_id: manualPrintCostCenterId,
  465. amount: amount,
  466. description: manualPrintDescription || undefined,
  467. created_at: manualPrintDate ? new Date(manualPrintDate).toISOString() : undefined,
  468. });
  469. };
  470. const handleWalletAdjustment = async () => {
  471. if (selectedUserId == null) {
  472. showToast(t('finance.userRequired', 'Please select a user'), 'error');
  473. return;
  474. }
  475. const amount = Number.parseFloat(adjustmentAmount);
  476. if (!Number.isFinite(amount) || amount <= 0) {
  477. showToast(t('finance.amountMustBePositive', 'Amount must be greater than zero'), 'error');
  478. return;
  479. }
  480. const payload = {
  481. userId: selectedUserId,
  482. amount,
  483. description: adjustmentDescription.trim() || undefined,
  484. costCenterId: adjustmentCostCenterId,
  485. };
  486. try {
  487. if (selectedAdjustmentType === 'deposit') {
  488. await depositMutation.mutateAsync(payload);
  489. } else {
  490. await withdrawMutation.mutateAsync(payload);
  491. }
  492. queryClient.invalidateQueries({ queryKey: ['finance'] });
  493. setAdjustmentAmount('');
  494. setAdjustmentDescription('');
  495. showToast(
  496. selectedAdjustmentType === 'deposit'
  497. ? t('finance.depositSuccess', 'Deposit successful')
  498. : t('finance.withdrawSuccess', 'Withdrawal successful')
  499. );
  500. } catch (error) {
  501. showToast((error as Error).message || t('finance.adjustmentFailed', 'Wallet adjustment failed'), 'error');
  502. }
  503. };
  504. const handleAddMember = () => {
  505. if (selectedManageCenterId == null) {
  506. showToast(t('finance.selectCostCenter', 'Please select a cost center'), 'error');
  507. return;
  508. }
  509. if (memberUserId == null) {
  510. showToast(t('finance.noEligibleUsers', 'No eligible users available'), 'error');
  511. return;
  512. }
  513. upsertMemberMutation.mutate({
  514. costCenterId: selectedManageCenterId,
  515. userId: memberUserId,
  516. canPrint: memberCanPrint,
  517. });
  518. };
  519. const handleRemoveMember = (userId: number) => {
  520. if (selectedManageCenterId == null) return;
  521. removeMemberMutation.mutate({ costCenterId: selectedManageCenterId, userId });
  522. };
  523. const currency = uiFlags?.currency || 'USD';
  524. const currencySymbol = getCurrencySymbol(currency);
  525. const sortedUsers = useMemo(() => {
  526. return [...(users || [])].sort((a, b) => a.username.localeCompare(b.username));
  527. }, [users]);
  528. const usersById = useMemo(() => {
  529. const map = new Map<number, string>();
  530. for (const entry of sortedUsers) {
  531. map.set(entry.id, entry.username);
  532. }
  533. return map;
  534. }, [sortedUsers]);
  535. const availableUsersForCenter = useMemo(() => {
  536. const existingIds = new Set((selectedCenterDetail?.members || []).map((m) => m.user_id));
  537. return sortedUsers.filter((u) => !existingIds.has(u.id));
  538. }, [sortedUsers, selectedCenterDetail]);
  539. const activeTransactionsResponse =
  540. financeViewMode === 'admin' && canReadAllFinance
  541. ? adminTransactionsResponse
  542. : transactionsResponse;
  543. const txLoading = (financeViewMode === 'admin' && canReadAllFinance)
  544. ? adminTxLoading
  545. : personalTxLoading;
  546. const transactions = useMemo(
  547. () => activeTransactionsResponse?.items ?? [],
  548. [activeTransactionsResponse?.items]
  549. );
  550. const txTotal = activeTransactionsResponse?.total ?? 0;
  551. const txTotalPages = Math.max(1, Math.ceil(txTotal / txLimit));
  552. const filteredTransactions = useMemo(() => {
  553. const items = transactions;
  554. return items.filter((tx) => {
  555. if (txTypeFilter !== 'all' && tx.transaction_type !== txTypeFilter) return false;
  556. if (txCostCenterFilter !== 'all' && tx.cost_center_id !== txCostCenterFilter) return false;
  557. return true;
  558. });
  559. }, [transactions, txTypeFilter, txCostCenterFilter]);
  560. const txPage = Math.floor(txOffset / txLimit) + 1;
  561. const showCostCenterAccountColumn = financeViewMode === 'admin';
  562. const getTransactionTypeLabel = (transactionType: string): string => {
  563. if (transactionType === 'deposit') return t('finance.deposit');
  564. if (transactionType === 'withdraw') return t('finance.withdraw');
  565. if (transactionType === 'print_charge') return t('finance.printCharge');
  566. return transactionType;
  567. };
  568. const getPrivateOwnerLabel = (ownerUserId: number | null): string => {
  569. // Private centres are always created with an owner; none means they were deleted.
  570. if (ownerUserId == null) return t('finance.deletedUser', 'Deleted user');
  571. const ownerName = usersById.get(ownerUserId);
  572. if (ownerName) return ownerName;
  573. if (user?.id === ownerUserId && user.username) return user.username;
  574. return t('finance.userWithId', 'User #{{id}}', { id: ownerUserId });
  575. };
  576. const formatBudgetProgress = (center: { budget_available: number | null; budget_limit: number | null }) => {
  577. if (center.budget_limit == null || center.budget_available == null) return t('finance.unlimited', 'Unlimited');
  578. return `${currencySymbol}${center.budget_available.toFixed(2)}/${currencySymbol}${center.budget_limit.toFixed(2)}`;
  579. };
  580. if (!canAccessFinance) {
  581. return (
  582. <div className="p-4 md:p-8 space-y-6">
  583. <div className="flex items-center gap-2">
  584. <Wallet className="h-6 w-6 text-bambu-green" />
  585. <h1 className="text-2xl font-bold text-white">{t('finance.title', 'Finance')}</h1>
  586. </div>
  587. <div>
  588. <p className="text-bambu-gray mt-2 max-w-2xl">{t('finance.subtitle', 'Wallet, personal transactions, and cost centers')}</p>
  589. </div>
  590. <Card>
  591. <CardContent className="py-8 text-center text-bambu-gray">
  592. {t('finance.noAccess', 'You do not have permission to view finance data.')}
  593. </CardContent>
  594. </Card>
  595. </div>
  596. );
  597. }
  598. return (
  599. <div className="p-4 md:p-8 space-y-8">
  600. <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
  601. <div>
  602. <div className="flex items-center gap-2">
  603. <Wallet className="h-6 w-6 text-bambu-green" />
  604. <h1 className="text-2xl font-bold text-white">{t('finance.title', 'Finance')}</h1>
  605. </div>
  606. <p className="text-bambu-gray mt-2 max-w-2xl">{t('finance.subtitle', 'Wallet, personal transactions, and cost centers')}</p>
  607. <p className="text-xs text-bambu-gray mt-1 max-w-2xl">
  608. {t('finance.budgetPolicyHint', 'Account balances track costs. Printing is limited only by the selected cost center budget; without a budget, printing is unlimited.')}
  609. </p>
  610. </div>
  611. <div className="flex flex-col gap-2 lg:items-end">
  612. {hasAdminFinanceControls && (
  613. <div className="inline-flex overflow-hidden rounded border border-bambu-dark-tertiary">
  614. <button
  615. type="button"
  616. onClick={() => setFinanceViewMode('personal')}
  617. className={`px-3 py-1.5 text-sm ${financeViewMode === 'personal' ? 'bg-bambu-green text-black font-medium' : 'bg-bambu-dark text-bambu-gray'}`}
  618. >
  619. {t('finance.personalView', 'Personal view')}
  620. </button>
  621. <button
  622. type="button"
  623. onClick={() => setFinanceViewMode('admin')}
  624. className={`px-3 py-1.5 text-sm ${financeViewMode === 'admin' ? 'bg-bambu-green text-black font-medium' : 'bg-bambu-dark text-bambu-gray'}`}
  625. >
  626. {t('finance.adminView', 'Admin view')}
  627. </button>
  628. </div>
  629. )}
  630. {financeViewMode === 'admin' && hasAdminFinanceControls && (
  631. <div className="flex flex-wrap gap-2 lg:justify-end">
  632. {canCreateCostCenters && (
  633. <Button size="sm" variant="secondary" onClick={() => setShowCreateCenterModal(true)}>
  634. {t('finance.createCostCenter', 'Create cost center')}
  635. </Button>
  636. )}
  637. {canAdjustWallet && canReadUsers && (
  638. <Button size="sm" variant="secondary" onClick={() => setShowAdjustWalletModal(true)}>
  639. {t('finance.adjustWallet', 'Adjust wallet')}
  640. </Button>
  641. )}
  642. {canAdjustWallet && canReadUsers && (
  643. <Button size="sm" variant="secondary" onClick={() => setShowManualPrintModal(true)}>
  644. {t('finance.addManualPrint', 'Add manual print')}
  645. </Button>
  646. )}
  647. {canAssignCostCenterUsers && canReadUsers && (
  648. <Button size="sm" variant="secondary" onClick={() => setShowMembersModal(true)}>
  649. {t('finance.manageMembers', 'Manage cost center members')}
  650. </Button>
  651. )}
  652. </div>
  653. )}
  654. </div>
  655. </div>
  656. <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-3">
  657. <Card>
  658. <CardHeader className="flex flex-row items-center justify-between pb-2">
  659. <span className="text-sm text-bambu-gray">{t('finance.currentBalance', 'Personal account balance')}</span>
  660. <Wallet className="w-4 h-4 text-bambu-green/90" />
  661. </CardHeader>
  662. <CardContent className="pt-1">
  663. <p className="text-3xl font-semibold text-white leading-tight">
  664. {walletLoading ? t('common.loading', 'Loading...') : `${currencySymbol}${(wallet?.balance ?? 0).toFixed(2)}`}
  665. </p>
  666. </CardContent>
  667. </Card>
  668. <Card>
  669. <CardHeader className="flex flex-row items-center justify-between pb-2">
  670. <span className="text-sm text-bambu-gray">
  671. {financeViewMode === 'admin'
  672. ? t('finance.transactions', 'Transactions')
  673. : t('finance.personalTransactions', 'Personal transactions')}
  674. </span>
  675. <Clock3 className="w-4 h-4 text-blue-400" />
  676. </CardHeader>
  677. <CardContent className="pt-1">
  678. <p className="text-3xl font-semibold text-white leading-tight">{txLoading ? '-' : txTotal}</p>
  679. </CardContent>
  680. </Card>
  681. <Card>
  682. <CardHeader className="flex flex-row items-center justify-between pb-2">
  683. <span className="text-sm text-bambu-gray">{t('finance.costCenters', 'Cost centers')}</span>
  684. <Building2 className="w-4 h-4 text-orange-400" />
  685. </CardHeader>
  686. <CardContent className="pt-1">
  687. <p className="text-3xl font-semibold text-white leading-tight">{centersLoading ? '-' : costCenters?.length ?? 0}</p>
  688. </CardContent>
  689. </Card>
  690. </div>
  691. {showCreateCenterModal && canCreateCostCenters && (
  692. <FinanceModal title={t('finance.createCostCenter', 'Create cost center')} size="md" onClose={() => setShowCreateCenterModal(false)}>
  693. <div className="space-y-4">
  694. <div className="grid gap-4 md:grid-cols-3">
  695. <div>
  696. <label className={labelClass}>{t('finance.costCenterName', 'Name')}</label>
  697. <input
  698. type="text"
  699. value={newCenterName}
  700. onChange={(e) => setNewCenterName(e.target.value)}
  701. placeholder={t('finance.costCenterName', 'Name')}
  702. className={fieldClass}
  703. />
  704. </div>
  705. <div>
  706. <label className={labelClass}>{t('finance.budgetType', 'Budget type')}</label>
  707. <select
  708. value={newCenterBudgetMode}
  709. onChange={(e) => setNewCenterBudgetMode(e.target.value as 'total' | 'monthly')}
  710. className={fieldClass}
  711. >
  712. <option value="monthly">{t('finance.monthlyBudget', 'Monthly budget')}</option>
  713. <option value="total">{t('finance.totalBudget', 'Total budget')}</option>
  714. </select>
  715. </div>
  716. <div>
  717. <label className={labelClass}>
  718. {newCenterBudgetMode === 'monthly' ? t('finance.monthlyBudget', 'Monthly budget') : t('finance.totalBudget', 'Total budget')}
  719. </label>
  720. <input
  721. type="number"
  722. step="0.01"
  723. value={newCenterBudgetValue}
  724. onChange={(e) => setNewCenterBudgetValue(e.target.value)}
  725. placeholder="0.00"
  726. className={fieldClass}
  727. />
  728. </div>
  729. </div>
  730. <Button className="min-w-[180px]" onClick={handleCreateCostCenter} disabled={createCostCenterMutation.isPending}>
  731. {createCostCenterMutation.isPending ? t('common.saving', 'Saving...') : t('finance.create', 'Create')}
  732. </Button>
  733. </div>
  734. </FinanceModal>
  735. )}
  736. {showAdjustWalletModal && canAdjustWallet && canReadUsers && (
  737. <FinanceModal title={t('finance.adjustWallet', 'Adjust wallet')} size="md" onClose={() => setShowAdjustWalletModal(false)}>
  738. <div className="space-y-4">
  739. <div className="grid gap-4 md:grid-cols-2">
  740. <div>
  741. <label className={labelClass}>{t('finance.selectUser', 'Select user')}</label>
  742. <select
  743. value={selectedUserId ?? ''}
  744. onChange={(e) => setSelectedUserId(e.target.value ? Number(e.target.value) : null)}
  745. className={fieldClass}
  746. >
  747. {(sortedUsers || []).map((u) => (
  748. <option key={u.id} value={u.id}>{u.username}</option>
  749. ))}
  750. </select>
  751. </div>
  752. <div>
  753. <label className={labelClass}>{t('finance.transactionType', 'Type')}</label>
  754. <select
  755. value={selectedAdjustmentType}
  756. onChange={(e) => setSelectedAdjustmentType(e.target.value as 'deposit' | 'withdraw')}
  757. className={fieldClass}
  758. >
  759. <option value="deposit">{t('finance.deposit', 'Deposit')}</option>
  760. <option value="withdraw">{t('finance.withdraw', 'Withdraw')}</option>
  761. </select>
  762. </div>
  763. <div>
  764. <label className={labelClass}>{t('finance.amount', 'Amount')}</label>
  765. <input
  766. type="number"
  767. step="0.01"
  768. min="0"
  769. value={adjustmentAmount}
  770. onChange={(e) => setAdjustmentAmount(e.target.value)}
  771. placeholder="0.00"
  772. className={fieldClass}
  773. />
  774. </div>
  775. <div>
  776. <label className={labelClass}>{t('finance.costCenters', 'Cost centers')}</label>
  777. <select
  778. value={adjustmentCostCenterId ?? ''}
  779. onChange={(e) => setAdjustmentCostCenterId(e.target.value ? Number(e.target.value) : null)}
  780. className={fieldClass}
  781. >
  782. <option value="">{t('finance.noCostCenter', 'No cost center')}</option>
  783. {(costCenters || []).map((center) => (
  784. <option key={center.id} value={center.id}>{center.name}</option>
  785. ))}
  786. </select>
  787. </div>
  788. </div>
  789. <div>
  790. <label className={labelClass}>{t('common.description', 'Description')}</label>
  791. <input
  792. type="text"
  793. value={adjustmentDescription}
  794. onChange={(e) => setAdjustmentDescription(e.target.value)}
  795. placeholder={t('finance.descriptionOptional', 'Description (optional)')}
  796. className={fieldClass}
  797. />
  798. </div>
  799. <Button className="min-w-[180px]" onClick={handleWalletAdjustment} disabled={isAdjustingWallet}>
  800. {isAdjustingWallet ? t('common.saving', 'Saving...') : t('finance.applyAdjustment', 'Apply adjustment')}
  801. </Button>
  802. </div>
  803. </FinanceModal>
  804. )}
  805. {showMembersModal && canAssignCostCenterUsers && canReadUsers && (
  806. <FinanceModal title={t('finance.manageMembers', 'Manage cost center members')} size="lg" onClose={() => setShowMembersModal(false)}>
  807. <div className="space-y-5">
  808. <div className="grid gap-5 md:grid-cols-2">
  809. <div>
  810. <label className={labelClass}>{t('finance.costCenters', 'Cost centers')}</label>
  811. <select
  812. value={selectedManageCenterId ?? ''}
  813. onChange={(e) => setSelectedManageCenterId(e.target.value ? Number(e.target.value) : null)}
  814. className={fieldClass}
  815. >
  816. {(costCenters || [])
  817. .filter((center) => !center.is_private)
  818. .map((center) => (
  819. <option key={center.id} value={center.id}>{center.name}</option>
  820. ))}
  821. </select>
  822. </div>
  823. <div>
  824. <label className={labelClass}>{t('finance.selectUser', 'Select user')}</label>
  825. <select
  826. value={memberUserId ?? ''}
  827. onChange={(e) => setMemberUserId(e.target.value ? Number(e.target.value) : null)}
  828. className={fieldClass}
  829. >
  830. <option value="">{t('finance.selectUser', 'Select user')}</option>
  831. {availableUsersForCenter.map((u) => (
  832. <option key={u.id} value={u.id}>{u.username}</option>
  833. ))}
  834. </select>
  835. </div>
  836. <div className="flex items-center gap-2 rounded border border-bambu-dark-tertiary bg-bambu-dark-secondary px-3 py-2">
  837. <input
  838. id="memberCanPrint"
  839. type="checkbox"
  840. checked={memberCanPrint}
  841. onChange={(e) => setMemberCanPrint(e.target.checked)}
  842. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  843. />
  844. <label htmlFor="memberCanPrint" className="text-sm text-bambu-gray">
  845. {t('finance.memberCanPrint', 'Member can print')}
  846. </label>
  847. </div>
  848. <div className="flex items-end">
  849. <Button className="min-w-[180px]" onClick={handleAddMember} disabled={upsertMemberMutation.isPending || memberUserId == null}>
  850. {upsertMemberMutation.isPending ? t('common.saving', 'Saving...') : t('finance.addMember', 'Add member')}
  851. </Button>
  852. </div>
  853. </div>
  854. <div className="overflow-auto rounded-lg border border-bambu-dark-tertiary">
  855. <table className="w-full text-sm">
  856. <thead>
  857. <tr className="border-b border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray">
  858. <th className={tableHeadCellClass}>{t('common.name', 'Name')}</th>
  859. <th className={tableHeadCellClass}>{t('finance.canPrint', 'Can print')}</th>
  860. <th className={tableHeadCellClass}>{t('common.actions', 'Actions')}</th>
  861. </tr>
  862. </thead>
  863. <tbody>
  864. {(selectedCenterDetail?.members || []).map((member) => {
  865. const user = sortedUsers.find((u) => u.id === member.user_id);
  866. return (
  867. <tr key={member.id} className="border-b border-bambu-dark-tertiary/60 text-white">
  868. <td className={tableCellClass}>{user?.username || `User ${member.user_id}`}</td>
  869. <td className={tableCellClass}>{member.can_print ? t('common.yes', 'Yes') : t('common.no', 'No')}</td>
  870. <td className={tableCellClass}>
  871. <Button
  872. size="sm"
  873. variant="danger"
  874. onClick={() => handleRemoveMember(member.user_id)}
  875. disabled={removeMemberMutation.isPending}
  876. >
  877. {t('common.remove', 'Remove')}
  878. </Button>
  879. </td>
  880. </tr>
  881. );
  882. })}
  883. {(selectedCenterDetail?.members || []).length === 0 && (
  884. <tr>
  885. <td colSpan={3} className="py-3 text-bambu-gray">
  886. {t('finance.noMembers', 'No members assigned.')}
  887. </td>
  888. </tr>
  889. )}
  890. </tbody>
  891. </table>
  892. </div>
  893. </div>
  894. </FinanceModal>
  895. )}
  896. {showEditCenterModal && (canUpdateCostCenters || canUpdateBudgets) && (
  897. <FinanceModal title={t('finance.editCostCenter', 'Edit cost center')} size="md" onClose={() => setShowEditCenterModal(false)}>
  898. <div className="space-y-4">
  899. <div>
  900. <label className={labelClass}>{t('finance.costCenterName', 'Name')}</label>
  901. <input
  902. type="text"
  903. value={editCenterName}
  904. onChange={(e) => setEditCenterName(e.target.value)}
  905. placeholder={t('finance.costCenterName', 'Name')}
  906. className={fieldClass}
  907. disabled={!canUpdateCostCenters}
  908. />
  909. </div>
  910. <div className="grid gap-4 md:grid-cols-2">
  911. <div>
  912. <label className={labelClass}>{t('finance.budgetType', 'Budget type')}</label>
  913. <select
  914. value={editCenterBudgetMode}
  915. onChange={(e) => setEditCenterBudgetMode(e.target.value as 'total' | 'monthly')}
  916. className={fieldClass}
  917. disabled={!canUpdateBudgets}
  918. >
  919. <option value="monthly">{t('finance.monthlyBudget', 'Monthly budget')}</option>
  920. <option value="total">{t('finance.totalBudget', 'Total budget')}</option>
  921. </select>
  922. </div>
  923. <div>
  924. <label className={labelClass}>
  925. {editCenterBudgetMode === 'monthly' ? t('finance.monthlyBudget', 'Monthly budget') : t('finance.totalBudget', 'Total budget')}
  926. </label>
  927. <input
  928. type="number"
  929. step="0.01"
  930. value={editCenterBudgetValue}
  931. onChange={(e) => setEditCenterBudgetValue(e.target.value)}
  932. placeholder="0.00"
  933. className={fieldClass}
  934. disabled={!canUpdateBudgets}
  935. />
  936. </div>
  937. </div>
  938. <Button
  939. className="min-w-[180px]"
  940. onClick={handleSaveEditedCenter}
  941. disabled={updateCostCenterMutation.isPending || updateBudgetMutation.isPending || selectedEditCenterId == null}
  942. >
  943. {(updateCostCenterMutation.isPending || updateBudgetMutation.isPending)
  944. ? t('common.saving', 'Saving...')
  945. : t('common.save', 'Save')}
  946. </Button>
  947. </div>
  948. </FinanceModal>
  949. )}
  950. <div className={`grid gap-6 ${canViewMyCostCenters && canReadOwn ? 'xl:grid-cols-2' : ''}`}>
  951. {canViewMyCostCenters && (
  952. <Card>
  953. <CardHeader>
  954. <h2 className="text-lg font-semibold text-white">{t('finance.myCostCenters', 'My cost centers')}</h2>
  955. <p className="text-sm text-bambu-gray mt-1">{t('finance.costCentersHint', 'Review budget limits and keep costs under control')}</p>
  956. </CardHeader>
  957. <CardContent className="space-y-3">
  958. {centersLoading && <p className="text-sm text-bambu-gray">{t('common.loading', 'Loading...')}</p>}
  959. {!centersLoading && (!costCenters || costCenters.length === 0) && (
  960. <p className="text-sm text-bambu-gray">{t('finance.noCostCenters', 'No cost centers found.')}</p>
  961. )}
  962. {!centersLoading && costCenters && costCenters.length > 0 && (
  963. <div className="overflow-auto rounded-lg border border-bambu-dark-tertiary">
  964. <table className="w-full text-sm">
  965. <thead>
  966. <tr className="border-b border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray">
  967. <th className={tableHeadCellClass}>{t('common.name', 'Name')}</th>
  968. {showCostCenterAccountColumn && <th className={tableHeadCellClass}>{t('finance.owner', 'Owner')}</th>}
  969. <th className={tableHeadCellClass}>{t('finance.balance', 'Account balance')}</th>
  970. <th className={tableHeadCellClass}>{t('finance.budget', 'Budget')}</th>
  971. {showCostCenterAccountColumn && <th className={tableHeadCellClass}>{t('common.actions', 'Actions')}</th>}
  972. </tr>
  973. </thead>
  974. <tbody>
  975. {costCenters.map((center) => {
  976. const canEditRow = canUpdateCostCenters || canUpdateBudgets;
  977. const canDeleteRow = !center.is_private && canUpdateCostCenters;
  978. return (
  979. <tr key={center.id} className="border-b border-bambu-dark-tertiary/60 text-white">
  980. <td className={tableCellClass}>{center.name}</td>
  981. {showCostCenterAccountColumn && (
  982. <td className={tableCellClass}>{center.is_private ? getPrivateOwnerLabel(center.owner_user_id) : t('finance.shared', 'Shared')}</td>
  983. )}
  984. <td className={tableCellClass}>{currencySymbol}{center.total_balance.toFixed(2)}</td>
  985. <td className={tableCellClass}>
  986. <div className="flex flex-col gap-0.5">
  987. <span>{formatBudgetProgress(center)}</span>
  988. <span className="text-xs text-bambu-gray">
  989. {center.budget_mode === 'monthly'
  990. ? t('finance.monthlyBudget', 'Monthly budget')
  991. : center.budget_mode === 'total'
  992. ? t('finance.totalBudget', 'Total budget')
  993. : t('finance.noBudget', 'No budget')}
  994. </span>
  995. </div>
  996. </td>
  997. {showCostCenterAccountColumn && (
  998. <td className={tableCellClass}>
  999. <div className="flex items-center gap-2">
  1000. <Button
  1001. size="sm"
  1002. variant="ghost"
  1003. onClick={() => handleOpenEditCenter(center.id)}
  1004. disabled={!canEditRow}
  1005. title={canEditRow ? t('common.edit', 'Edit') : t('finance.cannotEditPrivateCostCenter', 'Private cost centers cannot be edited here')}
  1006. className="p-1.5 sm:p-2"
  1007. >
  1008. <Pencil className="w-4 h-4" />
  1009. </Button>
  1010. {canDeleteRow && (
  1011. <Button
  1012. size="sm"
  1013. variant="ghost"
  1014. onClick={() => setPendingDeleteCenter({ id: center.id, name: center.name })}
  1015. disabled={deleteCostCenterMutation.isPending}
  1016. title={t('common.delete', 'Delete')}
  1017. className="text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2"
  1018. >
  1019. <Trash2 className="w-4 h-4" />
  1020. </Button>
  1021. )}
  1022. </div>
  1023. </td>
  1024. )}
  1025. </tr>
  1026. );
  1027. })}
  1028. </tbody>
  1029. </table>
  1030. </div>
  1031. )}
  1032. </CardContent>
  1033. </Card>
  1034. )}
  1035. {canReadOwn && (
  1036. <Card>
  1037. <CardHeader>
  1038. <h2 className="text-lg font-semibold text-white">{t('finance.recentTransactions', 'Recent transactions')}</h2>
  1039. <p className="text-sm text-bambu-gray mt-1">{t('finance.transactionsHint', 'Filter by type and cost center, then navigate pages')}</p>
  1040. </CardHeader>
  1041. <CardContent className="space-y-4">
  1042. <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_auto] items-end">
  1043. <div>
  1044. <label className={labelClass}>{t('finance.transactionType', 'Type')}</label>
  1045. <select
  1046. value={txTypeFilter}
  1047. onChange={(e) => setTxTypeFilter(e.target.value)}
  1048. className={fieldClass}
  1049. >
  1050. <option value="all">{t('finance.allTypes')}</option>
  1051. <option value="deposit">{t('finance.deposit')}</option>
  1052. <option value="withdraw">{t('finance.withdraw')}</option>
  1053. <option value="print_charge">{t('finance.printCharge')}</option>
  1054. </select>
  1055. </div>
  1056. <div>
  1057. <label className={labelClass}>{t('finance.costCenters', 'Cost centers')}</label>
  1058. <select
  1059. value={txCostCenterFilter}
  1060. onChange={(e) => setTxCostCenterFilter(e.target.value === 'all' ? 'all' : Number(e.target.value))}
  1061. className={fieldClass}
  1062. >
  1063. <option value="all">{t('finance.allCostCenters')}</option>
  1064. {(costCenters || []).map((center) => (
  1065. <option key={center.id} value={center.id}>{center.name}</option>
  1066. ))}
  1067. </select>
  1068. </div>
  1069. </div>
  1070. {txLoading && <p className="text-sm text-bambu-gray">{t('common.loading', 'Loading...')}</p>}
  1071. {!txLoading && (!transactions || transactions.length === 0) && (
  1072. <p className="text-sm text-bambu-gray">{t('finance.noTransactions', 'No transactions available.')}</p>
  1073. )}
  1074. {!txLoading && transactions.length > 0 && filteredTransactions.length === 0 && (
  1075. <p className="text-sm text-bambu-gray">{t('finance.noTransactionsForFilter', 'No transactions match the selected filters.')}</p>
  1076. )}
  1077. {!txLoading && filteredTransactions.length > 0 && (
  1078. <div className="overflow-auto rounded-lg border border-bambu-dark-tertiary">
  1079. <table className="w-full text-sm">
  1080. <thead>
  1081. <tr className="border-b border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray">
  1082. <th className={tableHeadCellClass}>{t('common.date', 'Date')}</th>
  1083. {showCostCenterAccountColumn && <th className={tableHeadCellClass}>{t('common.user', 'User')}</th>}
  1084. <th className={tableHeadCellClass}>{t('finance.costCenter', 'Cost center')}</th>
  1085. <th className={tableHeadCellClass}>{t('finance.transactionType', 'Type')}</th>
  1086. <th className={tableHeadCellClass}>{t('common.description', 'Description')}</th>
  1087. <th className={tableHeadCellClass}>{t('finance.amount', 'Amount')}</th>
  1088. <th className={tableHeadCellClass}>{t('finance.balanceAfter', 'Balance after')}</th>
  1089. {showCostCenterAccountColumn && <th className={tableHeadCellClass}>{t('common.actions', 'Actions')}</th>}
  1090. </tr>
  1091. </thead>
  1092. <tbody>
  1093. {filteredTransactions.map((tx) => {
  1094. const positive = tx.amount >= 0;
  1095. const txCostCenter = tx.cost_center_id == null
  1096. ? null
  1097. : (costCenters || []).find((center) => center.id === tx.cost_center_id);
  1098. // No user: deleted since, or with auth off never had one.
  1099. const txUser = tx.user_id == null
  1100. ? t('finance.noUser', 'No user')
  1101. : usersById.get(tx.user_id) || t('finance.userWithId', 'User #{{id}}', { id: tx.user_id });
  1102. const parsed = tx.transaction_type === 'print_charge'
  1103. ? parsePrintChargeDescription((tx as { description: string | null }).description ?? null)
  1104. : null;
  1105. const txIsPartialPrint = parsed?.isPartial ?? false;
  1106. return (
  1107. <tr key={tx.id} className="border-b border-bambu-dark-tertiary/60 text-white">
  1108. <td className={tableCellClass}>{formatTimestamp(tx.created_at, i18n.language)}</td>
  1109. {showCostCenterAccountColumn && (
  1110. <td className={tableCellClass}>{txUser}</td>
  1111. )}
  1112. <td className={tableCellClass}>{txCostCenter?.name || '-'}</td>
  1113. <td className={tableCellClass}>
  1114. <span className="inline-flex items-center gap-2">
  1115. <span>{getTransactionTypeLabel(tx.transaction_type)}</span>
  1116. {txIsPartialPrint && (
  1117. <span className="rounded border border-yellow-500/40 bg-yellow-500/10 px-2 py-0.5 text-[11px] text-yellow-300">
  1118. {parsed && parsed.partialType
  1119. ? t(`finance.partialStatus.${parsed.partialType}`, parsed.partialType)
  1120. : t('finance.partial', 'Partial')}
  1121. </span>
  1122. )}
  1123. </span>
  1124. </td>
  1125. <td className={tableCellClass}>{(parsed?.cleanedDescription ?? tx.description) || '-'}</td>
  1126. <td className={`${tableCellClass} ${positive ? 'text-green-400' : 'text-red-400'}`}>
  1127. {positive ? '+' : '-'}{currencySymbol}{Math.abs(tx.amount).toFixed(2)}
  1128. </td>
  1129. <td className={tableCellClass}>{
  1130. tx.balance_after == null
  1131. ? '-'
  1132. : `${tx.balance_after < 0 ? '-' : ''}${currencySymbol}${Math.abs(tx.balance_after).toFixed(2)}`
  1133. }</td>
  1134. {showCostCenterAccountColumn && (
  1135. <td className={tableCellClass}>
  1136. <div className="flex items-center gap-2">
  1137. <Button
  1138. size="sm"
  1139. variant="secondary"
  1140. onClick={() => handleEditTransaction(tx)}
  1141. disabled={editTransactionMutation.isPending}
  1142. >
  1143. <Pencil className="w-4 h-4" />
  1144. </Button>
  1145. <Button
  1146. size="sm"
  1147. variant="danger"
  1148. onClick={() => setPendingDeleteTransactionId(tx.id)}
  1149. disabled={deleteTransactionMutation.isPending}
  1150. >
  1151. <Trash2 className="w-4 h-4" />
  1152. </Button>
  1153. </div>
  1154. </td>
  1155. )}
  1156. </tr>
  1157. );
  1158. })}
  1159. </tbody>
  1160. </table>
  1161. </div>
  1162. )}
  1163. {!txLoading && filteredTransactions.length > 0 && (
  1164. <div className="flex justify-end pt-2 lg:pt-0">
  1165. <div className="flex flex-wrap items-center justify-end gap-2">
  1166. <button
  1167. type="button"
  1168. onClick={() => setTxOffset(0)}
  1169. disabled={txOffset === 0 || txLoading}
  1170. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  1171. aria-label={t('finance.first', 'First')}
  1172. >
  1173. <ChevronsLeft className="w-4 h-4" />
  1174. </button>
  1175. <button
  1176. type="button"
  1177. onClick={() => setTxOffset((prev) => Math.max(0, prev - txLimit))}
  1178. disabled={txOffset === 0 || txLoading}
  1179. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  1180. aria-label={t('finance.prev', 'Previous')}
  1181. >
  1182. <ChevronLeft className="w-4 h-4" />
  1183. </button>
  1184. <span className="text-bambu-gray px-1 whitespace-nowrap">
  1185. {t('finance.pageNumberOf', 'Page {{page}} of {{total}}', { page: txPage, total: txTotalPages })}
  1186. </span>
  1187. <button
  1188. type="button"
  1189. onClick={() => setTxOffset((prev) => prev + txLimit)}
  1190. disabled={txLoading || txPage >= txTotalPages}
  1191. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  1192. aria-label={t('finance.next', 'Next')}
  1193. >
  1194. <ChevronRight className="w-4 h-4" />
  1195. </button>
  1196. <button
  1197. type="button"
  1198. onClick={() => setTxOffset(Math.max(0, (txTotalPages - 1) * txLimit))}
  1199. disabled={txLoading || txPage >= txTotalPages}
  1200. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  1201. aria-label={t('finance.last', 'Last')}
  1202. >
  1203. <ChevronsRight className="w-4 h-4" />
  1204. </button>
  1205. </div>
  1206. </div>
  1207. )}
  1208. </CardContent>
  1209. </Card>
  1210. )}
  1211. {showEditTransactionModal && selectedEditTransactionId !== null && (
  1212. <FinanceModal
  1213. title={t('finance.editTransaction', 'Edit Transaction')}
  1214. onClose={() => setShowEditTransactionModal(false)}
  1215. size="md"
  1216. >
  1217. <div className="space-y-4">
  1218. <div>
  1219. <label className={labelClass}>{t('common.user', 'User')}</label>
  1220. <select
  1221. className={fieldClass}
  1222. value={editTransactionUserId || ''}
  1223. onChange={(e) => setEditTransactionUserId(e.target.value ? Number(e.target.value) : null)}
  1224. >
  1225. <option value="">{t('finance.selectUser', 'Select user...')}</option>
  1226. {sortedUsers.map((u) => (
  1227. <option key={u.id} value={u.id}>{u.username}</option>
  1228. ))}
  1229. </select>
  1230. </div>
  1231. <div>
  1232. <label className={labelClass}>{t('finance.costCenter', 'Cost center (optional)')}</label>
  1233. <select
  1234. className={fieldClass}
  1235. value={editTransactionCostCenterId || ''}
  1236. onChange={(e) => setEditTransactionCostCenterId(e.target.value ? Number(e.target.value) : null)}
  1237. >
  1238. <option value="">{t('finance.noCostCenter', 'Personal (no cost center)')}</option>
  1239. {(costCenters || []).map((cc) => (
  1240. <option key={cc.id} value={cc.id}>{cc.name}</option>
  1241. ))}
  1242. </select>
  1243. </div>
  1244. <div>
  1245. <label className={labelClass}>{t('finance.amount', 'Amount')}</label>
  1246. <input
  1247. type="number"
  1248. step="0.01"
  1249. className={fieldClass}
  1250. value={editTransactionAmount}
  1251. onChange={(e) => setEditTransactionAmount(e.target.value)}
  1252. placeholder={t('finance.amountExample', 'e.g., 10.50')}
  1253. />
  1254. </div>
  1255. <div>
  1256. <label className={labelClass}>{t('common.description', 'Description')}</label>
  1257. <textarea
  1258. className={`${fieldClass} resize-none`}
  1259. rows={3}
  1260. value={editTransactionDescription}
  1261. onChange={(e) => setEditTransactionDescription(e.target.value)}
  1262. placeholder={t('finance.manualAdjustmentExample', 'e.g., Manual adjustment')}
  1263. />
  1264. </div>
  1265. <div className="flex justify-end gap-2 pt-4">
  1266. <Button
  1267. variant="secondary"
  1268. onClick={() => setShowEditTransactionModal(false)}
  1269. >
  1270. {t('common.cancel', 'Cancel')}
  1271. </Button>
  1272. <Button
  1273. onClick={handleSaveEditTransaction}
  1274. disabled={editTransactionMutation.isPending}
  1275. >
  1276. {t('common.save', 'Save')}
  1277. </Button>
  1278. </div>
  1279. </div>
  1280. </FinanceModal>
  1281. )}
  1282. {showManualPrintModal && (
  1283. <FinanceModal
  1284. title={t('finance.addManualPrint', 'Add manual print')}
  1285. onClose={() => setShowManualPrintModal(false)}
  1286. size="md"
  1287. >
  1288. <div className="space-y-4">
  1289. <div>
  1290. <label className={labelClass}>{t('common.user', 'User')}</label>
  1291. <select
  1292. className={fieldClass}
  1293. value={manualPrintUserId || ''}
  1294. onChange={(e) => setManualPrintUserId(e.target.value ? Number(e.target.value) : null)}
  1295. >
  1296. <option value="">{t('finance.selectUser', 'Select user...')}</option>
  1297. {sortedUsers.map((u) => (
  1298. <option key={u.id} value={u.id}>{u.username}</option>
  1299. ))}
  1300. </select>
  1301. </div>
  1302. <div>
  1303. <label className={labelClass}>{t('finance.costCenter', 'Cost center')}</label>
  1304. <select
  1305. className={fieldClass}
  1306. value={manualPrintCostCenterId || ''}
  1307. onChange={(e) => setManualPrintCostCenterId(e.target.value ? Number(e.target.value) : null)}
  1308. >
  1309. <option value="">{t('finance.selectCostCenter', 'Select cost center...')}</option>
  1310. {(costCenters || []).map((cc) => (
  1311. <option key={cc.id} value={cc.id}>{cc.name}</option>
  1312. ))}
  1313. </select>
  1314. </div>
  1315. <div>
  1316. <label className={labelClass}>{t('finance.amount', 'Amount')}</label>
  1317. <input
  1318. type="number"
  1319. step="0.01"
  1320. className={fieldClass}
  1321. value={manualPrintAmount}
  1322. onChange={(e) => setManualPrintAmount(e.target.value)}
  1323. placeholder={t('finance.amountExample', 'e.g., 4.00')}
  1324. />
  1325. </div>
  1326. <div>
  1327. <label className={labelClass}>{t('common.description', 'Description')}</label>
  1328. <input
  1329. type="text"
  1330. value={manualPrintDescription}
  1331. onChange={(e) => setManualPrintDescription(e.target.value)}
  1332. placeholder={t('finance.descriptionOptional', 'Description (optional)')}
  1333. className={fieldClass}
  1334. />
  1335. </div>
  1336. <div>
  1337. <label className={labelClass}>{t('common.date', 'Date')}</label>
  1338. <input
  1339. type="datetime-local"
  1340. value={manualPrintDate}
  1341. onChange={(e) => setManualPrintDate(e.target.value)}
  1342. className={fieldClass}
  1343. />
  1344. </div>
  1345. <div className="flex justify-end gap-2 pt-4">
  1346. <Button variant="secondary" onClick={() => setShowManualPrintModal(false)}>
  1347. {t('common.cancel', 'Cancel')}
  1348. </Button>
  1349. <Button onClick={handleSaveManualPrint} disabled={manualPrintMutation.isPending}>
  1350. {manualPrintMutation.isPending ? t('common.saving', 'Saving...') : t('finance.addManualPrint', 'Add manual print')}
  1351. </Button>
  1352. </div>
  1353. </div>
  1354. </FinanceModal>
  1355. )}
  1356. {pendingDeleteCenter && (
  1357. <ConfirmModal
  1358. title={t('common.delete', 'Delete')}
  1359. message={t('finance.confirmDeleteCostCenter', 'Delete cost center "{{name}}"?', {
  1360. name: pendingDeleteCenter.name,
  1361. })}
  1362. confirmText={t('common.delete', 'Delete')}
  1363. variant="danger"
  1364. isLoading={deleteCostCenterMutation.isPending}
  1365. onConfirm={confirmDeleteCenter}
  1366. onCancel={() => setPendingDeleteCenter(null)}
  1367. />
  1368. )}
  1369. {pendingDeleteTransactionId != null && (
  1370. <ConfirmModal
  1371. title={t('finance.deleteTransaction', 'Delete transaction')}
  1372. message={t(
  1373. 'finance.deleteTransactionConfirm',
  1374. 'Delete this transaction? Balances will be recalculated automatically.',
  1375. )}
  1376. confirmText={t('common.delete', 'Delete')}
  1377. variant="danger"
  1378. isLoading={deleteTransactionMutation.isPending}
  1379. onConfirm={confirmDeleteTransaction}
  1380. onCancel={() => setPendingDeleteTransactionId(null)}
  1381. />
  1382. )}
  1383. </div>
  1384. </div>
  1385. );
  1386. }