FinancePage.tsx 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  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. if (ownerUserId == null) return t('finance.personal', 'Personal');
  570. const ownerName = usersById.get(ownerUserId);
  571. if (ownerName) return ownerName;
  572. if (user?.id === ownerUserId && user.username) return user.username;
  573. return t('finance.userWithId', 'User #{{id}}', { id: ownerUserId });
  574. };
  575. const formatBudgetProgress = (center: { budget_available: number | null; budget_limit: number | null }) => {
  576. if (center.budget_limit == null || center.budget_available == null) return t('finance.unlimited', 'Unlimited');
  577. return `${currencySymbol}${center.budget_available.toFixed(2)}/${currencySymbol}${center.budget_limit.toFixed(2)}`;
  578. };
  579. if (!canAccessFinance) {
  580. return (
  581. <div className="p-4 md:p-8 space-y-6">
  582. <div className="flex items-center gap-2">
  583. <Wallet className="h-6 w-6 text-bambu-green" />
  584. <h1 className="text-2xl font-bold text-white">{t('finance.title', 'Finance')}</h1>
  585. </div>
  586. <div>
  587. <p className="text-bambu-gray mt-2 max-w-2xl">{t('finance.subtitle', 'Wallet, personal transactions, and cost centers')}</p>
  588. </div>
  589. <Card>
  590. <CardContent className="py-8 text-center text-bambu-gray">
  591. {t('finance.noAccess', 'You do not have permission to view finance data.')}
  592. </CardContent>
  593. </Card>
  594. </div>
  595. );
  596. }
  597. return (
  598. <div className="p-4 md:p-8 space-y-8">
  599. <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
  600. <div>
  601. <div className="flex items-center gap-2">
  602. <Wallet className="h-6 w-6 text-bambu-green" />
  603. <h1 className="text-2xl font-bold text-white">{t('finance.title', 'Finance')}</h1>
  604. </div>
  605. <p className="text-bambu-gray mt-2 max-w-2xl">{t('finance.subtitle', 'Wallet, personal transactions, and cost centers')}</p>
  606. <p className="text-xs text-bambu-gray mt-1 max-w-2xl">
  607. {t('finance.budgetPolicyHint', 'Account balances track costs. Printing is limited only by the selected cost center budget; without a budget, printing is unlimited.')}
  608. </p>
  609. </div>
  610. <div className="flex flex-col gap-2 lg:items-end">
  611. {hasAdminFinanceControls && (
  612. <div className="inline-flex overflow-hidden rounded border border-bambu-dark-tertiary">
  613. <button
  614. type="button"
  615. onClick={() => setFinanceViewMode('personal')}
  616. className={`px-3 py-1.5 text-sm ${financeViewMode === 'personal' ? 'bg-bambu-green text-black font-medium' : 'bg-bambu-dark text-bambu-gray'}`}
  617. >
  618. {t('finance.personalView', 'Personal view')}
  619. </button>
  620. <button
  621. type="button"
  622. onClick={() => setFinanceViewMode('admin')}
  623. className={`px-3 py-1.5 text-sm ${financeViewMode === 'admin' ? 'bg-bambu-green text-black font-medium' : 'bg-bambu-dark text-bambu-gray'}`}
  624. >
  625. {t('finance.adminView', 'Admin view')}
  626. </button>
  627. </div>
  628. )}
  629. {financeViewMode === 'admin' && hasAdminFinanceControls && (
  630. <div className="flex flex-wrap gap-2 lg:justify-end">
  631. {canCreateCostCenters && (
  632. <Button size="sm" variant="secondary" onClick={() => setShowCreateCenterModal(true)}>
  633. {t('finance.createCostCenter', 'Create cost center')}
  634. </Button>
  635. )}
  636. {canAdjustWallet && canReadUsers && (
  637. <Button size="sm" variant="secondary" onClick={() => setShowAdjustWalletModal(true)}>
  638. {t('finance.adjustWallet', 'Adjust wallet')}
  639. </Button>
  640. )}
  641. {canAdjustWallet && canReadUsers && (
  642. <Button size="sm" variant="secondary" onClick={() => setShowManualPrintModal(true)}>
  643. {t('finance.addManualPrint', 'Add manual print')}
  644. </Button>
  645. )}
  646. {canAssignCostCenterUsers && canReadUsers && (
  647. <Button size="sm" variant="secondary" onClick={() => setShowMembersModal(true)}>
  648. {t('finance.manageMembers', 'Manage cost center members')}
  649. </Button>
  650. )}
  651. </div>
  652. )}
  653. </div>
  654. </div>
  655. <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-3">
  656. <Card>
  657. <CardHeader className="flex flex-row items-center justify-between pb-2">
  658. <span className="text-sm text-bambu-gray">{t('finance.currentBalance', 'Personal account balance')}</span>
  659. <Wallet className="w-4 h-4 text-bambu-green/90" />
  660. </CardHeader>
  661. <CardContent className="pt-1">
  662. <p className="text-3xl font-semibold text-white leading-tight">
  663. {walletLoading ? t('common.loading', 'Loading...') : `${currencySymbol}${(wallet?.balance ?? 0).toFixed(2)}`}
  664. </p>
  665. </CardContent>
  666. </Card>
  667. <Card>
  668. <CardHeader className="flex flex-row items-center justify-between pb-2">
  669. <span className="text-sm text-bambu-gray">
  670. {financeViewMode === 'admin'
  671. ? t('finance.transactions', 'Transactions')
  672. : t('finance.personalTransactions', 'Personal transactions')}
  673. </span>
  674. <Clock3 className="w-4 h-4 text-blue-400" />
  675. </CardHeader>
  676. <CardContent className="pt-1">
  677. <p className="text-3xl font-semibold text-white leading-tight">{txLoading ? '-' : txTotal}</p>
  678. </CardContent>
  679. </Card>
  680. <Card>
  681. <CardHeader className="flex flex-row items-center justify-between pb-2">
  682. <span className="text-sm text-bambu-gray">{t('finance.costCenters', 'Cost centers')}</span>
  683. <Building2 className="w-4 h-4 text-orange-400" />
  684. </CardHeader>
  685. <CardContent className="pt-1">
  686. <p className="text-3xl font-semibold text-white leading-tight">{centersLoading ? '-' : costCenters?.length ?? 0}</p>
  687. </CardContent>
  688. </Card>
  689. </div>
  690. {showCreateCenterModal && canCreateCostCenters && (
  691. <FinanceModal title={t('finance.createCostCenter', 'Create cost center')} size="md" onClose={() => setShowCreateCenterModal(false)}>
  692. <div className="space-y-4">
  693. <div className="grid gap-4 md:grid-cols-3">
  694. <div>
  695. <label className={labelClass}>{t('finance.costCenterName', 'Name')}</label>
  696. <input
  697. type="text"
  698. value={newCenterName}
  699. onChange={(e) => setNewCenterName(e.target.value)}
  700. placeholder={t('finance.costCenterName', 'Name')}
  701. className={fieldClass}
  702. />
  703. </div>
  704. <div>
  705. <label className={labelClass}>{t('finance.budgetType', 'Budget type')}</label>
  706. <select
  707. value={newCenterBudgetMode}
  708. onChange={(e) => setNewCenterBudgetMode(e.target.value as 'total' | 'monthly')}
  709. className={fieldClass}
  710. >
  711. <option value="monthly">{t('finance.monthlyBudget', 'Monthly budget')}</option>
  712. <option value="total">{t('finance.totalBudget', 'Total budget')}</option>
  713. </select>
  714. </div>
  715. <div>
  716. <label className={labelClass}>
  717. {newCenterBudgetMode === 'monthly' ? t('finance.monthlyBudget', 'Monthly budget') : t('finance.totalBudget', 'Total budget')}
  718. </label>
  719. <input
  720. type="number"
  721. step="0.01"
  722. value={newCenterBudgetValue}
  723. onChange={(e) => setNewCenterBudgetValue(e.target.value)}
  724. placeholder="0.00"
  725. className={fieldClass}
  726. />
  727. </div>
  728. </div>
  729. <Button className="min-w-[180px]" onClick={handleCreateCostCenter} disabled={createCostCenterMutation.isPending}>
  730. {createCostCenterMutation.isPending ? t('common.saving', 'Saving...') : t('finance.create', 'Create')}
  731. </Button>
  732. </div>
  733. </FinanceModal>
  734. )}
  735. {showAdjustWalletModal && canAdjustWallet && canReadUsers && (
  736. <FinanceModal title={t('finance.adjustWallet', 'Adjust wallet')} size="md" onClose={() => setShowAdjustWalletModal(false)}>
  737. <div className="space-y-4">
  738. <div className="grid gap-4 md:grid-cols-2">
  739. <div>
  740. <label className={labelClass}>{t('finance.selectUser', 'Select user')}</label>
  741. <select
  742. value={selectedUserId ?? ''}
  743. onChange={(e) => setSelectedUserId(e.target.value ? Number(e.target.value) : null)}
  744. className={fieldClass}
  745. >
  746. {(sortedUsers || []).map((u) => (
  747. <option key={u.id} value={u.id}>{u.username}</option>
  748. ))}
  749. </select>
  750. </div>
  751. <div>
  752. <label className={labelClass}>{t('finance.transactionType', 'Type')}</label>
  753. <select
  754. value={selectedAdjustmentType}
  755. onChange={(e) => setSelectedAdjustmentType(e.target.value as 'deposit' | 'withdraw')}
  756. className={fieldClass}
  757. >
  758. <option value="deposit">{t('finance.deposit', 'Deposit')}</option>
  759. <option value="withdraw">{t('finance.withdraw', 'Withdraw')}</option>
  760. </select>
  761. </div>
  762. <div>
  763. <label className={labelClass}>{t('finance.amount', 'Amount')}</label>
  764. <input
  765. type="number"
  766. step="0.01"
  767. min="0"
  768. value={adjustmentAmount}
  769. onChange={(e) => setAdjustmentAmount(e.target.value)}
  770. placeholder="0.00"
  771. className={fieldClass}
  772. />
  773. </div>
  774. <div>
  775. <label className={labelClass}>{t('finance.costCenters', 'Cost centers')}</label>
  776. <select
  777. value={adjustmentCostCenterId ?? ''}
  778. onChange={(e) => setAdjustmentCostCenterId(e.target.value ? Number(e.target.value) : null)}
  779. className={fieldClass}
  780. >
  781. <option value="">{t('finance.noCostCenter', 'No cost center')}</option>
  782. {(costCenters || []).map((center) => (
  783. <option key={center.id} value={center.id}>{center.name}</option>
  784. ))}
  785. </select>
  786. </div>
  787. </div>
  788. <div>
  789. <label className={labelClass}>{t('common.description', 'Description')}</label>
  790. <input
  791. type="text"
  792. value={adjustmentDescription}
  793. onChange={(e) => setAdjustmentDescription(e.target.value)}
  794. placeholder={t('finance.descriptionOptional', 'Description (optional)')}
  795. className={fieldClass}
  796. />
  797. </div>
  798. <Button className="min-w-[180px]" onClick={handleWalletAdjustment} disabled={isAdjustingWallet}>
  799. {isAdjustingWallet ? t('common.saving', 'Saving...') : t('finance.applyAdjustment', 'Apply adjustment')}
  800. </Button>
  801. </div>
  802. </FinanceModal>
  803. )}
  804. {showMembersModal && canAssignCostCenterUsers && canReadUsers && (
  805. <FinanceModal title={t('finance.manageMembers', 'Manage cost center members')} size="lg" onClose={() => setShowMembersModal(false)}>
  806. <div className="space-y-5">
  807. <div className="grid gap-5 md:grid-cols-2">
  808. <div>
  809. <label className={labelClass}>{t('finance.costCenters', 'Cost centers')}</label>
  810. <select
  811. value={selectedManageCenterId ?? ''}
  812. onChange={(e) => setSelectedManageCenterId(e.target.value ? Number(e.target.value) : null)}
  813. className={fieldClass}
  814. >
  815. {(costCenters || [])
  816. .filter((center) => !center.is_private)
  817. .map((center) => (
  818. <option key={center.id} value={center.id}>{center.name}</option>
  819. ))}
  820. </select>
  821. </div>
  822. <div>
  823. <label className={labelClass}>{t('finance.selectUser', 'Select user')}</label>
  824. <select
  825. value={memberUserId ?? ''}
  826. onChange={(e) => setMemberUserId(e.target.value ? Number(e.target.value) : null)}
  827. className={fieldClass}
  828. >
  829. <option value="">{t('finance.selectUser', 'Select user')}</option>
  830. {availableUsersForCenter.map((u) => (
  831. <option key={u.id} value={u.id}>{u.username}</option>
  832. ))}
  833. </select>
  834. </div>
  835. <div className="flex items-center gap-2 rounded border border-bambu-dark-tertiary bg-bambu-dark-secondary px-3 py-2">
  836. <input
  837. id="memberCanPrint"
  838. type="checkbox"
  839. checked={memberCanPrint}
  840. onChange={(e) => setMemberCanPrint(e.target.checked)}
  841. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  842. />
  843. <label htmlFor="memberCanPrint" className="text-sm text-bambu-gray">
  844. {t('finance.memberCanPrint', 'Member can print')}
  845. </label>
  846. </div>
  847. <div className="flex items-end">
  848. <Button className="min-w-[180px]" onClick={handleAddMember} disabled={upsertMemberMutation.isPending || memberUserId == null}>
  849. {upsertMemberMutation.isPending ? t('common.saving', 'Saving...') : t('finance.addMember', 'Add member')}
  850. </Button>
  851. </div>
  852. </div>
  853. <div className="overflow-auto rounded-lg border border-bambu-dark-tertiary">
  854. <table className="w-full text-sm">
  855. <thead>
  856. <tr className="border-b border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray">
  857. <th className={tableHeadCellClass}>{t('common.name', 'Name')}</th>
  858. <th className={tableHeadCellClass}>{t('finance.canPrint', 'Can print')}</th>
  859. <th className={tableHeadCellClass}>{t('common.actions', 'Actions')}</th>
  860. </tr>
  861. </thead>
  862. <tbody>
  863. {(selectedCenterDetail?.members || []).map((member) => {
  864. const user = sortedUsers.find((u) => u.id === member.user_id);
  865. return (
  866. <tr key={member.id} className="border-b border-bambu-dark-tertiary/60 text-white">
  867. <td className={tableCellClass}>{user?.username || `User ${member.user_id}`}</td>
  868. <td className={tableCellClass}>{member.can_print ? t('common.yes', 'Yes') : t('common.no', 'No')}</td>
  869. <td className={tableCellClass}>
  870. <Button
  871. size="sm"
  872. variant="danger"
  873. onClick={() => handleRemoveMember(member.user_id)}
  874. disabled={removeMemberMutation.isPending}
  875. >
  876. {t('common.remove', 'Remove')}
  877. </Button>
  878. </td>
  879. </tr>
  880. );
  881. })}
  882. {(selectedCenterDetail?.members || []).length === 0 && (
  883. <tr>
  884. <td colSpan={3} className="py-3 text-bambu-gray">
  885. {t('finance.noMembers', 'No members assigned.')}
  886. </td>
  887. </tr>
  888. )}
  889. </tbody>
  890. </table>
  891. </div>
  892. </div>
  893. </FinanceModal>
  894. )}
  895. {showEditCenterModal && (canUpdateCostCenters || canUpdateBudgets) && (
  896. <FinanceModal title={t('finance.editCostCenter', 'Edit cost center')} size="md" onClose={() => setShowEditCenterModal(false)}>
  897. <div className="space-y-4">
  898. <div>
  899. <label className={labelClass}>{t('finance.costCenterName', 'Name')}</label>
  900. <input
  901. type="text"
  902. value={editCenterName}
  903. onChange={(e) => setEditCenterName(e.target.value)}
  904. placeholder={t('finance.costCenterName', 'Name')}
  905. className={fieldClass}
  906. disabled={!canUpdateCostCenters}
  907. />
  908. </div>
  909. <div className="grid gap-4 md:grid-cols-2">
  910. <div>
  911. <label className={labelClass}>{t('finance.budgetType', 'Budget type')}</label>
  912. <select
  913. value={editCenterBudgetMode}
  914. onChange={(e) => setEditCenterBudgetMode(e.target.value as 'total' | 'monthly')}
  915. className={fieldClass}
  916. disabled={!canUpdateBudgets}
  917. >
  918. <option value="monthly">{t('finance.monthlyBudget', 'Monthly budget')}</option>
  919. <option value="total">{t('finance.totalBudget', 'Total budget')}</option>
  920. </select>
  921. </div>
  922. <div>
  923. <label className={labelClass}>
  924. {editCenterBudgetMode === 'monthly' ? t('finance.monthlyBudget', 'Monthly budget') : t('finance.totalBudget', 'Total budget')}
  925. </label>
  926. <input
  927. type="number"
  928. step="0.01"
  929. value={editCenterBudgetValue}
  930. onChange={(e) => setEditCenterBudgetValue(e.target.value)}
  931. placeholder="0.00"
  932. className={fieldClass}
  933. disabled={!canUpdateBudgets}
  934. />
  935. </div>
  936. </div>
  937. <Button
  938. className="min-w-[180px]"
  939. onClick={handleSaveEditedCenter}
  940. disabled={updateCostCenterMutation.isPending || updateBudgetMutation.isPending || selectedEditCenterId == null}
  941. >
  942. {(updateCostCenterMutation.isPending || updateBudgetMutation.isPending)
  943. ? t('common.saving', 'Saving...')
  944. : t('common.save', 'Save')}
  945. </Button>
  946. </div>
  947. </FinanceModal>
  948. )}
  949. <div className={`grid gap-6 ${canViewMyCostCenters && canReadOwn ? 'xl:grid-cols-2' : ''}`}>
  950. {canViewMyCostCenters && (
  951. <Card>
  952. <CardHeader>
  953. <h2 className="text-lg font-semibold text-white">{t('finance.myCostCenters', 'My cost centers')}</h2>
  954. <p className="text-sm text-bambu-gray mt-1">{t('finance.costCentersHint', 'Review budget limits and keep costs under control')}</p>
  955. </CardHeader>
  956. <CardContent className="space-y-3">
  957. {centersLoading && <p className="text-sm text-bambu-gray">{t('common.loading', 'Loading...')}</p>}
  958. {!centersLoading && (!costCenters || costCenters.length === 0) && (
  959. <p className="text-sm text-bambu-gray">{t('finance.noCostCenters', 'No cost centers found.')}</p>
  960. )}
  961. {!centersLoading && costCenters && costCenters.length > 0 && (
  962. <div className="overflow-auto rounded-lg border border-bambu-dark-tertiary">
  963. <table className="w-full text-sm">
  964. <thead>
  965. <tr className="border-b border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray">
  966. <th className={tableHeadCellClass}>{t('common.name', 'Name')}</th>
  967. {showCostCenterAccountColumn && <th className={tableHeadCellClass}>{t('finance.owner', 'Owner')}</th>}
  968. <th className={tableHeadCellClass}>{t('finance.balance', 'Account balance')}</th>
  969. <th className={tableHeadCellClass}>{t('finance.budget', 'Budget')}</th>
  970. {showCostCenterAccountColumn && <th className={tableHeadCellClass}>{t('common.actions', 'Actions')}</th>}
  971. </tr>
  972. </thead>
  973. <tbody>
  974. {costCenters.map((center) => {
  975. const canEditRow = canUpdateCostCenters || canUpdateBudgets;
  976. const canDeleteRow = !center.is_private && canUpdateCostCenters;
  977. return (
  978. <tr key={center.id} className="border-b border-bambu-dark-tertiary/60 text-white">
  979. <td className={tableCellClass}>{center.name}</td>
  980. {showCostCenterAccountColumn && (
  981. <td className={tableCellClass}>{center.is_private ? getPrivateOwnerLabel(center.owner_user_id) : t('finance.shared', 'Shared')}</td>
  982. )}
  983. <td className={tableCellClass}>{currencySymbol}{center.total_balance.toFixed(2)}</td>
  984. <td className={tableCellClass}>
  985. <div className="flex flex-col gap-0.5">
  986. <span>{formatBudgetProgress(center)}</span>
  987. <span className="text-xs text-bambu-gray">
  988. {center.budget_mode === 'monthly'
  989. ? t('finance.monthlyBudget', 'Monthly budget')
  990. : center.budget_mode === 'total'
  991. ? t('finance.totalBudget', 'Total budget')
  992. : t('finance.noBudget', 'No budget')}
  993. </span>
  994. </div>
  995. </td>
  996. {showCostCenterAccountColumn && (
  997. <td className={tableCellClass}>
  998. <div className="flex items-center gap-2">
  999. <Button
  1000. size="sm"
  1001. variant="ghost"
  1002. onClick={() => handleOpenEditCenter(center.id)}
  1003. disabled={!canEditRow}
  1004. title={canEditRow ? t('common.edit', 'Edit') : t('finance.cannotEditPrivateCostCenter', 'Private cost centers cannot be edited here')}
  1005. className="p-1.5 sm:p-2"
  1006. >
  1007. <Pencil className="w-4 h-4" />
  1008. </Button>
  1009. {canDeleteRow && (
  1010. <Button
  1011. size="sm"
  1012. variant="ghost"
  1013. onClick={() => setPendingDeleteCenter({ id: center.id, name: center.name })}
  1014. disabled={deleteCostCenterMutation.isPending}
  1015. title={t('common.delete', 'Delete')}
  1016. className="text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2"
  1017. >
  1018. <Trash2 className="w-4 h-4" />
  1019. </Button>
  1020. )}
  1021. </div>
  1022. </td>
  1023. )}
  1024. </tr>
  1025. );
  1026. })}
  1027. </tbody>
  1028. </table>
  1029. </div>
  1030. )}
  1031. </CardContent>
  1032. </Card>
  1033. )}
  1034. {canReadOwn && (
  1035. <Card>
  1036. <CardHeader>
  1037. <h2 className="text-lg font-semibold text-white">{t('finance.recentTransactions', 'Recent transactions')}</h2>
  1038. <p className="text-sm text-bambu-gray mt-1">{t('finance.transactionsHint', 'Filter by type and cost center, then navigate pages')}</p>
  1039. </CardHeader>
  1040. <CardContent className="space-y-4">
  1041. <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">
  1042. <div>
  1043. <label className={labelClass}>{t('finance.transactionType', 'Type')}</label>
  1044. <select
  1045. value={txTypeFilter}
  1046. onChange={(e) => setTxTypeFilter(e.target.value)}
  1047. className={fieldClass}
  1048. >
  1049. <option value="all">{t('finance.allTypes')}</option>
  1050. <option value="deposit">{t('finance.deposit')}</option>
  1051. <option value="withdraw">{t('finance.withdraw')}</option>
  1052. <option value="print_charge">{t('finance.printCharge')}</option>
  1053. </select>
  1054. </div>
  1055. <div>
  1056. <label className={labelClass}>{t('finance.costCenters', 'Cost centers')}</label>
  1057. <select
  1058. value={txCostCenterFilter}
  1059. onChange={(e) => setTxCostCenterFilter(e.target.value === 'all' ? 'all' : Number(e.target.value))}
  1060. className={fieldClass}
  1061. >
  1062. <option value="all">{t('finance.allCostCenters')}</option>
  1063. {(costCenters || []).map((center) => (
  1064. <option key={center.id} value={center.id}>{center.name}</option>
  1065. ))}
  1066. </select>
  1067. </div>
  1068. </div>
  1069. {txLoading && <p className="text-sm text-bambu-gray">{t('common.loading', 'Loading...')}</p>}
  1070. {!txLoading && (!transactions || transactions.length === 0) && (
  1071. <p className="text-sm text-bambu-gray">{t('finance.noTransactions', 'No transactions available.')}</p>
  1072. )}
  1073. {!txLoading && transactions.length > 0 && filteredTransactions.length === 0 && (
  1074. <p className="text-sm text-bambu-gray">{t('finance.noTransactionsForFilter', 'No transactions match the selected filters.')}</p>
  1075. )}
  1076. {!txLoading && filteredTransactions.length > 0 && (
  1077. <div className="overflow-auto rounded-lg border border-bambu-dark-tertiary">
  1078. <table className="w-full text-sm">
  1079. <thead>
  1080. <tr className="border-b border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray">
  1081. <th className={tableHeadCellClass}>{t('common.date', 'Date')}</th>
  1082. {showCostCenterAccountColumn && <th className={tableHeadCellClass}>{t('common.user', 'User')}</th>}
  1083. <th className={tableHeadCellClass}>{t('finance.costCenter', 'Cost center')}</th>
  1084. <th className={tableHeadCellClass}>{t('finance.transactionType', 'Type')}</th>
  1085. <th className={tableHeadCellClass}>{t('common.description', 'Description')}</th>
  1086. <th className={tableHeadCellClass}>{t('finance.amount', 'Amount')}</th>
  1087. <th className={tableHeadCellClass}>{t('finance.balanceAfter', 'Balance after')}</th>
  1088. {showCostCenterAccountColumn && <th className={tableHeadCellClass}>{t('common.actions', 'Actions')}</th>}
  1089. </tr>
  1090. </thead>
  1091. <tbody>
  1092. {filteredTransactions.map((tx) => {
  1093. const positive = tx.amount >= 0;
  1094. const txCostCenter = tx.cost_center_id == null
  1095. ? null
  1096. : (costCenters || []).find((center) => center.id === tx.cost_center_id);
  1097. const txUser = usersById.get(tx.user_id);
  1098. const parsed = tx.transaction_type === 'print_charge'
  1099. ? parsePrintChargeDescription((tx as { description: string | null }).description ?? null)
  1100. : null;
  1101. const txIsPartialPrint = parsed?.isPartial ?? false;
  1102. return (
  1103. <tr key={tx.id} className="border-b border-bambu-dark-tertiary/60 text-white">
  1104. <td className={tableCellClass}>{formatTimestamp(tx.created_at, i18n.language)}</td>
  1105. {showCostCenterAccountColumn && (
  1106. <td className={tableCellClass}>{txUser || t('finance.userWithId', 'User #{{id}}', { id: tx.user_id })}</td>
  1107. )}
  1108. <td className={tableCellClass}>{txCostCenter?.name || '-'}</td>
  1109. <td className={tableCellClass}>
  1110. <span className="inline-flex items-center gap-2">
  1111. <span>{getTransactionTypeLabel(tx.transaction_type)}</span>
  1112. {txIsPartialPrint && (
  1113. <span className="rounded border border-yellow-500/40 bg-yellow-500/10 px-2 py-0.5 text-[11px] text-yellow-300">
  1114. {parsed && parsed.partialType
  1115. ? t(`finance.partialStatus.${parsed.partialType}`, parsed.partialType)
  1116. : t('finance.partial', 'Partial')}
  1117. </span>
  1118. )}
  1119. </span>
  1120. </td>
  1121. <td className={tableCellClass}>{(parsed?.cleanedDescription ?? tx.description) || '-'}</td>
  1122. <td className={`${tableCellClass} ${positive ? 'text-green-400' : 'text-red-400'}`}>
  1123. {positive ? '+' : '-'}{currencySymbol}{Math.abs(tx.amount).toFixed(2)}
  1124. </td>
  1125. <td className={tableCellClass}>{
  1126. tx.balance_after == null
  1127. ? '-'
  1128. : `${tx.balance_after < 0 ? '-' : ''}${currencySymbol}${Math.abs(tx.balance_after).toFixed(2)}`
  1129. }</td>
  1130. {showCostCenterAccountColumn && (
  1131. <td className={tableCellClass}>
  1132. <div className="flex items-center gap-2">
  1133. <Button
  1134. size="sm"
  1135. variant="secondary"
  1136. onClick={() => handleEditTransaction(tx)}
  1137. disabled={editTransactionMutation.isPending}
  1138. >
  1139. <Pencil className="w-4 h-4" />
  1140. </Button>
  1141. <Button
  1142. size="sm"
  1143. variant="danger"
  1144. onClick={() => setPendingDeleteTransactionId(tx.id)}
  1145. disabled={deleteTransactionMutation.isPending}
  1146. >
  1147. <Trash2 className="w-4 h-4" />
  1148. </Button>
  1149. </div>
  1150. </td>
  1151. )}
  1152. </tr>
  1153. );
  1154. })}
  1155. </tbody>
  1156. </table>
  1157. </div>
  1158. )}
  1159. {!txLoading && filteredTransactions.length > 0 && (
  1160. <div className="flex justify-end pt-2 lg:pt-0">
  1161. <div className="flex flex-wrap items-center justify-end gap-2">
  1162. <button
  1163. type="button"
  1164. onClick={() => setTxOffset(0)}
  1165. disabled={txOffset === 0 || txLoading}
  1166. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  1167. aria-label={t('finance.first', 'First')}
  1168. >
  1169. <ChevronsLeft className="w-4 h-4" />
  1170. </button>
  1171. <button
  1172. type="button"
  1173. onClick={() => setTxOffset((prev) => Math.max(0, prev - txLimit))}
  1174. disabled={txOffset === 0 || txLoading}
  1175. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  1176. aria-label={t('finance.prev', 'Previous')}
  1177. >
  1178. <ChevronLeft className="w-4 h-4" />
  1179. </button>
  1180. <span className="text-bambu-gray px-1 whitespace-nowrap">
  1181. {t('finance.pageNumberOf', 'Page {{page}} of {{total}}', { page: txPage, total: txTotalPages })}
  1182. </span>
  1183. <button
  1184. type="button"
  1185. onClick={() => setTxOffset((prev) => prev + txLimit)}
  1186. disabled={txLoading || txPage >= txTotalPages}
  1187. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  1188. aria-label={t('finance.next', 'Next')}
  1189. >
  1190. <ChevronRight className="w-4 h-4" />
  1191. </button>
  1192. <button
  1193. type="button"
  1194. onClick={() => setTxOffset(Math.max(0, (txTotalPages - 1) * txLimit))}
  1195. disabled={txLoading || txPage >= txTotalPages}
  1196. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  1197. aria-label={t('finance.last', 'Last')}
  1198. >
  1199. <ChevronsRight className="w-4 h-4" />
  1200. </button>
  1201. </div>
  1202. </div>
  1203. )}
  1204. </CardContent>
  1205. </Card>
  1206. )}
  1207. {showEditTransactionModal && selectedEditTransactionId !== null && (
  1208. <FinanceModal
  1209. title={t('finance.editTransaction', 'Edit Transaction')}
  1210. onClose={() => setShowEditTransactionModal(false)}
  1211. size="md"
  1212. >
  1213. <div className="space-y-4">
  1214. <div>
  1215. <label className={labelClass}>{t('common.user', 'User')}</label>
  1216. <select
  1217. className={fieldClass}
  1218. value={editTransactionUserId || ''}
  1219. onChange={(e) => setEditTransactionUserId(e.target.value ? Number(e.target.value) : null)}
  1220. >
  1221. <option value="">{t('finance.selectUser', 'Select user...')}</option>
  1222. {sortedUsers.map((u) => (
  1223. <option key={u.id} value={u.id}>{u.username}</option>
  1224. ))}
  1225. </select>
  1226. </div>
  1227. <div>
  1228. <label className={labelClass}>{t('finance.costCenter', 'Cost center (optional)')}</label>
  1229. <select
  1230. className={fieldClass}
  1231. value={editTransactionCostCenterId || ''}
  1232. onChange={(e) => setEditTransactionCostCenterId(e.target.value ? Number(e.target.value) : null)}
  1233. >
  1234. <option value="">{t('finance.noCostCenter', 'Personal (no cost center)')}</option>
  1235. {(costCenters || []).map((cc) => (
  1236. <option key={cc.id} value={cc.id}>{cc.name}</option>
  1237. ))}
  1238. </select>
  1239. </div>
  1240. <div>
  1241. <label className={labelClass}>{t('finance.amount', 'Amount')}</label>
  1242. <input
  1243. type="number"
  1244. step="0.01"
  1245. className={fieldClass}
  1246. value={editTransactionAmount}
  1247. onChange={(e) => setEditTransactionAmount(e.target.value)}
  1248. placeholder={t('finance.amountExample', 'e.g., 10.50')}
  1249. />
  1250. </div>
  1251. <div>
  1252. <label className={labelClass}>{t('common.description', 'Description')}</label>
  1253. <textarea
  1254. className={`${fieldClass} resize-none`}
  1255. rows={3}
  1256. value={editTransactionDescription}
  1257. onChange={(e) => setEditTransactionDescription(e.target.value)}
  1258. placeholder={t('finance.manualAdjustmentExample', 'e.g., Manual adjustment')}
  1259. />
  1260. </div>
  1261. <div className="flex justify-end gap-2 pt-4">
  1262. <Button
  1263. variant="secondary"
  1264. onClick={() => setShowEditTransactionModal(false)}
  1265. >
  1266. {t('common.cancel', 'Cancel')}
  1267. </Button>
  1268. <Button
  1269. onClick={handleSaveEditTransaction}
  1270. disabled={editTransactionMutation.isPending}
  1271. >
  1272. {t('common.save', 'Save')}
  1273. </Button>
  1274. </div>
  1275. </div>
  1276. </FinanceModal>
  1277. )}
  1278. {showManualPrintModal && (
  1279. <FinanceModal
  1280. title={t('finance.addManualPrint', 'Add manual print')}
  1281. onClose={() => setShowManualPrintModal(false)}
  1282. size="md"
  1283. >
  1284. <div className="space-y-4">
  1285. <div>
  1286. <label className={labelClass}>{t('common.user', 'User')}</label>
  1287. <select
  1288. className={fieldClass}
  1289. value={manualPrintUserId || ''}
  1290. onChange={(e) => setManualPrintUserId(e.target.value ? Number(e.target.value) : null)}
  1291. >
  1292. <option value="">{t('finance.selectUser', 'Select user...')}</option>
  1293. {sortedUsers.map((u) => (
  1294. <option key={u.id} value={u.id}>{u.username}</option>
  1295. ))}
  1296. </select>
  1297. </div>
  1298. <div>
  1299. <label className={labelClass}>{t('finance.costCenter', 'Cost center')}</label>
  1300. <select
  1301. className={fieldClass}
  1302. value={manualPrintCostCenterId || ''}
  1303. onChange={(e) => setManualPrintCostCenterId(e.target.value ? Number(e.target.value) : null)}
  1304. >
  1305. <option value="">{t('finance.selectCostCenter', 'Select cost center...')}</option>
  1306. {(costCenters || []).map((cc) => (
  1307. <option key={cc.id} value={cc.id}>{cc.name}</option>
  1308. ))}
  1309. </select>
  1310. </div>
  1311. <div>
  1312. <label className={labelClass}>{t('finance.amount', 'Amount')}</label>
  1313. <input
  1314. type="number"
  1315. step="0.01"
  1316. className={fieldClass}
  1317. value={manualPrintAmount}
  1318. onChange={(e) => setManualPrintAmount(e.target.value)}
  1319. placeholder={t('finance.amountExample', 'e.g., 4.00')}
  1320. />
  1321. </div>
  1322. <div>
  1323. <label className={labelClass}>{t('common.description', 'Description')}</label>
  1324. <input
  1325. type="text"
  1326. value={manualPrintDescription}
  1327. onChange={(e) => setManualPrintDescription(e.target.value)}
  1328. placeholder={t('finance.descriptionOptional', 'Description (optional)')}
  1329. className={fieldClass}
  1330. />
  1331. </div>
  1332. <div>
  1333. <label className={labelClass}>{t('common.date', 'Date')}</label>
  1334. <input
  1335. type="datetime-local"
  1336. value={manualPrintDate}
  1337. onChange={(e) => setManualPrintDate(e.target.value)}
  1338. className={fieldClass}
  1339. />
  1340. </div>
  1341. <div className="flex justify-end gap-2 pt-4">
  1342. <Button variant="secondary" onClick={() => setShowManualPrintModal(false)}>
  1343. {t('common.cancel', 'Cancel')}
  1344. </Button>
  1345. <Button onClick={handleSaveManualPrint} disabled={manualPrintMutation.isPending}>
  1346. {manualPrintMutation.isPending ? t('common.saving', 'Saving...') : t('finance.addManualPrint', 'Add manual print')}
  1347. </Button>
  1348. </div>
  1349. </div>
  1350. </FinanceModal>
  1351. )}
  1352. {pendingDeleteCenter && (
  1353. <ConfirmModal
  1354. title={t('common.delete', 'Delete')}
  1355. message={t('finance.confirmDeleteCostCenter', 'Delete cost center "{{name}}"?', {
  1356. name: pendingDeleteCenter.name,
  1357. })}
  1358. confirmText={t('common.delete', 'Delete')}
  1359. variant="danger"
  1360. isLoading={deleteCostCenterMutation.isPending}
  1361. onConfirm={confirmDeleteCenter}
  1362. onCancel={() => setPendingDeleteCenter(null)}
  1363. />
  1364. )}
  1365. {pendingDeleteTransactionId != null && (
  1366. <ConfirmModal
  1367. title={t('finance.deleteTransaction', 'Delete transaction')}
  1368. message={t(
  1369. 'finance.deleteTransactionConfirm',
  1370. 'Delete this transaction? Balances will be recalculated automatically.',
  1371. )}
  1372. confirmText={t('common.delete', 'Delete')}
  1373. variant="danger"
  1374. isLoading={deleteTransactionMutation.isPending}
  1375. onConfirm={confirmDeleteTransaction}
  1376. onCancel={() => setPendingDeleteTransactionId(null)}
  1377. />
  1378. )}
  1379. </div>
  1380. </div>
  1381. );
  1382. }