Add cost tracking for spools and usage history

This commit is contained in:
Matteo Parenti
2026-02-19 14:13:18 +01:00
parent c856badb84
commit 04ffca204f
24 changed files with 958 additions and 3 deletions
+2
View File
@@ -1788,6 +1788,7 @@ export interface InventorySpool {
archived_at: string | null;
created_at: string;
updated_at: string;
cost_per_kg: number | null;
k_profiles?: SpoolKProfile[];
}
@@ -1799,6 +1800,7 @@ export interface SpoolUsageRecord {
weight_used: number;
percent_used: number;
status: string;
cost: number | null;
created_at: string;
}
@@ -1,9 +1,10 @@
import { useState } from 'react';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Circle, Check, AlertTriangle, RefreshCw, ChevronDown, ChevronUp } from 'lucide-react';
import { api } from '../../api/client';
import { useFilamentMapping } from '../../hooks/useFilamentMapping';
import { getGlobalTrayId } from '../../utils/amsHelpers';
import { getColorName } from '../../utils/colors';
import type { FilamentMappingProps } from './types';
@@ -16,6 +17,8 @@ export function FilamentMapping({
filamentReqs,
manualMappings,
onManualMappingChange,
currencySymbol,
defaultCostPerKg,
defaultExpanded = false,
}: FilamentMappingProps & { defaultExpanded?: boolean }) {
const { t } = useTranslation();
@@ -30,9 +33,41 @@ export function FilamentMapping({
enabled: !!printerId,
});
const { data: assignments } = useQuery({
queryKey: ['spool-assignments', printerId],
queryFn: () => api.getAssignments(printerId),
enabled: !!printerId,
});
const { loadedFilaments, filamentComparison, hasTypeMismatch, hasColorMismatch } =
useFilamentMapping(filamentReqs, printerStatus, manualMappings);
const trayCostMap = useMemo(() => {
const map = new Map<number, number | null>();
for (const assignment of assignments || []) {
const isExternal = assignment.ams_id === 255;
const globalTrayId = isExternal
? 254 + assignment.tray_id
: getGlobalTrayId(assignment.ams_id, assignment.tray_id, false);
map.set(globalTrayId, assignment.spool?.cost_per_kg ?? null);
}
return map;
}, [assignments]);
const totalCost = useMemo(() => {
let total = 0;
for (const item of filamentComparison) {
const trayId = item.loaded?.globalTrayId;
if (trayId == null) continue;
const assignedCost = trayCostMap.get(trayId) ?? null;
const costPerKg = assignedCost ?? defaultCostPerKg;
if (costPerKg > 0) {
total += (item.used_grams / 1000) * costPerKg;
}
}
return total;
}, [filamentComparison, trayCostMap, defaultCostPerKg]);
const hasFilamentReqs = filamentReqs?.filaments && filamentReqs.filaments.length > 0;
const isDualNozzle = filamentReqs?.filaments?.some((f) => f.nozzle_id != null) ?? false;
@@ -90,7 +125,7 @@ export function FilamentMapping({
className="flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full"
>
<Circle className="w-4 h-4" fill={statusColor} stroke="none" />
<span>Filament Mapping</span>
<span>{t('printModal.filamentMapping')}</span>
{hasTypeMismatch ? (
<span className="text-xs text-orange-400">(Type not found)</span>
) : hasColorMismatch ? (
@@ -181,6 +216,9 @@ export function FilamentMapping({
)}
</div>
))}
<div className="text-xs text-bambu-gray">
{t('printModal.totalCost')} <span className="text-white">{currencySymbol}{totalCost.toFixed(2)}</span>
</div>
{hasTypeMismatch && (
<p className="text-xs text-orange-400 mt-2">Required filament type not found in printer.</p>
)}
@@ -10,6 +10,7 @@ import { useToast } from '../../contexts/ToastContext';
import { useFilamentMapping } from '../../hooks/useFilamentMapping';
import { useMultiPrinterFilamentMapping, type PerPrinterConfig } from '../../hooks/useMultiPrinterFilamentMapping';
import { isPlaceholderDate } from '../../utils/amsHelpers';
import { getCurrencySymbol } from '../../utils/currency';
import { toDateTimeLocalValue } from '../../utils/date';
import { PrinterSelector } from './PrinterSelector';
import { PlateSelector } from './PlateSelector';
@@ -170,6 +171,9 @@ export function PrintModal({
queryFn: api.getSettings,
});
const currencySymbol = getCurrencySymbol(settings?.currency || 'USD');
const defaultCostPerKg = settings?.default_filament_cost ?? 0;
const { data: printers, isLoading: loadingPrinters } = useQuery({
queryKey: ['printers'],
queryFn: api.getPrinters,
@@ -687,6 +691,8 @@ export function PrintModal({
manualMappings={manualMappings}
onManualMappingChange={setManualMappings}
defaultExpanded={settings?.per_printer_mapping_expanded ?? false}
currencySymbol={currencySymbol}
defaultCostPerKg={defaultCostPerKg}
/>
)}
@@ -171,6 +171,8 @@ export interface FilamentMappingProps {
filamentReqs: FilamentReqsData | undefined;
manualMappings: Record<number, number>;
onManualMappingChange: (mappings: Record<number, number>) => void;
currencySymbol: string;
defaultCostPerKg: number;
}
/**
@@ -175,6 +175,7 @@ export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibration
weight_used: spool.weight_used || 0,
slicer_filament: spool.slicer_filament || '',
note: spool.note || '',
cost_per_kg: spool.cost_per_kg ?? null,
});
setPresetInputValue(spool.slicer_filament_name || spool.slicer_filament || '');
@@ -343,6 +344,7 @@ export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibration
nozzle_temp_min: null,
nozzle_temp_max: null,
note: formData.note || null,
cost_per_kg: formData.cost_per_kg,
};
// Only send weight_used when creating or when explicitly changed by the user.
@@ -259,6 +259,27 @@ export function AdditionalSection({
</div>
</div>
{/* Cost per kg */}
<div>
<label className="block text-sm font-medium text-bambu-gray mb-1">{t('inventory.costPerKg', 'Cost per kg')}</label>
<div className="flex items-center gap-2">
<div className="relative flex-1">
<input
type="number"
value={formData.cost_per_kg ?? ''}
min={0}
step={0.01}
placeholder="0.00"
onChange={(e) => {
const value = e.target.value === '' ? null : parseFloat(e.target.value);
updateField('cost_per_kg', value);
}}
className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
/>
</div>
</div>
</div>
{/* Note */}
<div>
<label className="block text-sm font-medium text-bambu-gray mb-1">{t('inventory.note')}</label>
@@ -13,6 +13,7 @@ export interface SpoolFormData {
weight_used: number;
slicer_filament: string;
note: string;
cost_per_kg: number | null;
}
export const defaultFormData: SpoolFormData = {
@@ -27,6 +28,7 @@ export const defaultFormData: SpoolFormData = {
weight_used: 0,
slicer_filament: '',
note: '',
cost_per_kg: null,
};
// Printer with calibrations type
+2
View File
@@ -2534,6 +2534,7 @@ export default {
weightUsed: 'Verbraucht',
currentWeight: 'Restgewicht',
measuredWeight: 'Gemessenes Gewicht',
costPerKg: 'Kosten pro kg',
measuredWeightError: 'Das gemessene Gewicht muss zwischen {{min}}g und {{max}}g liegen.',
slicerFilament: 'Slicer-Filament',
slicerFilamentName: 'Slicer-Preset-Name',
@@ -2701,6 +2702,7 @@ export default {
selectPrinter: 'Drucker auswählen',
selectPlate: 'Platte auswählen',
filamentMapping: 'Filamentzuordnung',
totalCost: 'Gesamtkosten:',
printSettings: 'Druckeinstellungen',
bedLeveling: 'Bett-Nivellierung',
flowCalibration: 'Fluss-Kalibrierung',
+2
View File
@@ -2534,6 +2534,7 @@ export default {
weightUsed: 'Used',
currentWeight: 'Remaining Weight',
measuredWeight: 'Measured Weight',
costPerKg: 'Cost per kg',
measuredWeightError: 'Measured weight must be between {{min}}g and {{max}}g.',
slicerFilament: 'Slicer Filament',
slicerFilamentName: 'Slicer Preset Name',
@@ -2705,6 +2706,7 @@ export default {
selectPrinter: 'Select Printer',
selectPlate: 'Select Plate',
filamentMapping: 'Filament Mapping',
totalCost: 'Total cost:',
printSettings: 'Print Settings',
bedLeveling: 'Bed Leveling',
flowCalibration: 'Flow Calibration',
+2
View File
@@ -2522,6 +2522,7 @@ export default {
weightUsed: 'Consommé',
currentWeight: 'Poids restant',
measuredWeight: 'Poids mesuré',
costPerKg: 'Coût par kg',
measuredWeightError: 'Le poids mesuré doit être entre {{min}}g et {{max}}g.',
slicerFilament: 'Filament Slicer',
slicerFilamentName: 'Nom du Preset Slicer',
@@ -2693,6 +2694,7 @@ export default {
selectPrinter: 'Choisir l\'imprimante',
selectPlate: 'Choisir le plateau',
filamentMapping: 'Mapping Filament',
totalCost: 'Coût total :',
printSettings: 'Réglages d\'impression',
bedLeveling: 'Nivellement plateau',
flowCalibration: 'Calibration débit',
+2
View File
@@ -2339,6 +2339,7 @@ export default {
weightUsed: 'Utilizzato',
currentWeight: 'Peso Rimanente',
measuredWeight: 'Peso Misurato',
costPerKg: 'Costo per kg',
measuredWeightError: 'Il peso misurato deve essere compreso tra {{min}}g e {{max}}g.',
slicerFilament: 'Filamento Slicer',
slicerFilamentName: 'Nome Preset Slicer',
@@ -2418,6 +2419,7 @@ export default {
selectPrinter: 'Seleziona stampante',
selectPlate: 'Seleziona piatto',
filamentMapping: 'Mappatura filamento',
totalCost: 'Costo totale:',
printSettings: 'Impostazioni stampa',
bedLeveling: 'Livellamento piatto',
flowCalibration: 'Calibrazione flusso',
+2
View File
@@ -2462,6 +2462,7 @@ export default {
weightUsed: '使用量',
currentWeight: '残量',
measuredWeight: '計測重量',
costPerKg: 'kgあたりのコスト',
measuredWeightError: '計測重量は{{min}}gから{{max}}gの間で入力してください。',
slicerFilament: 'スライサーフィラメント',
slicerFilamentName: 'スライサープリセット名',
@@ -2625,6 +2626,7 @@ export default {
selectPrinter: 'プリンターを選択',
selectPlate: 'プレートを選択',
filamentMapping: 'フィラメントマッピング',
totalCost: '合計コスト:',
printSettings: '印刷設定',
bedLeveling: 'ベッドレベリング',
layerInspection: '第一層検査',
+2
View File
@@ -2534,6 +2534,7 @@ export default {
weightUsed: 'Usado',
currentWeight: 'Peso Restante',
measuredWeight: 'Peso Medido',
costPerKg: 'Custo por kg',
measuredWeightError: 'O peso medido deve estar entre {{min}}g e {{max}}g.',
slicerFilament: 'Filamento do Fatiador',
slicerFilamentName: 'Nome do Predefinido do Fatiador',
@@ -2703,6 +2704,7 @@ export default {
selectPrinter: 'Selecionar Impressora',
selectPlate: 'Selecionar Placa',
filamentMapping: 'Mapeamento de Filamento',
totalCost: 'Custo total:',
printSettings: 'Configurações de Impressão',
bedLeveling: 'Nivelamento da Mesa',
flowCalibration: 'Calibração de Fluxo',
+12
View File
@@ -48,10 +48,12 @@ import {
User,
Play,
ClipboardList,
Coins,
} from 'lucide-react';
import { api } from '../api/client';
import { openInSlicer, type SlicerType } from '../utils/slicer';
import { formatDateTime, formatDateOnly, parseUTCDate, type TimeFormat, formatDuration } from '../utils/date';
import { getCurrencySymbol } from '../utils/currency';
import { useIsMobile } from '../hooks/useIsMobile';
import type { Archive, ProjectListItem } from '../api/client';
import { Card, CardContent } from '../components/Card';
@@ -140,6 +142,7 @@ function ArchiveCard({
isHighlighted,
timeFormat = 'system',
preferredSlicer = 'bambu_studio',
currency,
t,
}: {
archive: Archive;
@@ -151,6 +154,7 @@ function ArchiveCard({
isHighlighted?: boolean;
timeFormat?: TimeFormat;
preferredSlicer?: SlicerType;
currency: string;
t: TFunction;
}) {
// Debug: log when card is highlighted
@@ -919,6 +923,12 @@ function ArchiveCard({
{archive.filament_used_grams.toFixed(1)}g
</div>
)}
{archive.cost != null && archive.cost > 0 && (
<div className="flex items-center gap-1.5 text-bambu-gray">
<Coins className="w-3 h-3" />
{currency}{archive.cost.toFixed(2)}
</div>
)}
{(archive.layer_height || archive.total_layers) && (
<div className="flex items-center gap-1.5 text-bambu-gray">
<Layers className="w-3 h-3" />
@@ -2383,6 +2393,7 @@ export function ArchivesPage() {
const timeFormat: TimeFormat = settings?.time_format || 'system';
const preferredSlicer: SlicerType = settings?.preferred_slicer || 'bambu_studio';
const currency = getCurrencySymbol(settings?.currency || 'USD');
const bulkDeleteMutation = useMutation({
mutationFn: async (ids: number[]) => {
@@ -3195,6 +3206,7 @@ export function ArchivesPage() {
isHighlighted={archive.id === highlightedArchiveId}
timeFormat={timeFormat}
preferredSlicer={preferredSlicer}
currency={currency}
t={t}
/>
))}
+18 -1
View File
@@ -15,6 +15,7 @@ import { ConfirmModal } from '../components/ConfirmModal';
import { ColumnConfigModal, type ColumnConfig } from '../components/ColumnConfigModal';
import { useToast } from '../contexts/ToastContext';
import { resolveSpoolColorName } from '../utils/colors';
import { getCurrencySymbol } from '../utils/currency';
type ArchiveFilter = 'active' | 'archived';
type UsageFilter = 'all' | 'used' | 'new';
@@ -50,6 +51,7 @@ const DEFAULT_COLUMNS: ColumnConfig[] = [
{ id: 'data_origin', label: 'Data Origin', visible: false },
{ id: 'tag_type', label: 'Linked Tag Type', visible: false },
{ id: 'remaining', label: 'Remaining', visible: true },
{ id: 'cost_per_kg', label: 'Cost/kg', visible: false },
];
function loadColumnConfig(): ColumnConfig[] {
@@ -109,6 +111,7 @@ type CellCtx = {
remaining: number;
pct: number;
assignmentMap: Record<number, SpoolAssignment>;
currencySymbol: string;
};
// Column header labels (25 columns — matching SpoolBuddy exactly)
@@ -137,6 +140,7 @@ const columnHeaders: Record<string, (t: TFn) => string> = {
data_origin: () => 'Data Origin',
tag_type: () => 'Linked Tag Type',
remaining: (t) => t('inventory.remaining'),
cost_per_kg: () => 'Cost/kg',
};
// Column cell renderers (25 columns — matching SpoolBuddy exactly)
@@ -251,6 +255,11 @@ const columnCells: Record<string, (ctx: CellCtx) => ReactNode> = {
<span className="text-xs text-bambu-gray min-w-[40px] text-right">{Math.round(remaining)}g</span>
</div>
),
cost_per_kg: ({ spool, currencySymbol }) => (
<span className="text-sm text-bambu-gray">
{spool.cost_per_kg != null ? `${currencySymbol} ${spool.cost_per_kg.toFixed(2)}` : '-'}
</span>
),
};
// Sort value extractors — return a comparable value for each sortable column
@@ -277,6 +286,7 @@ const columnSortValues: Record<string, (spool: InventorySpool, assignmentMap: Re
note: (s) => (s.note || '').toLowerCase(),
data_origin: (s) => (s.data_origin || '').toLowerCase(),
tag_type: (s) => (s.tag_type || '').toLowerCase(),
cost_per_kg: (s) => s.cost_per_kg ?? 0,
};
const SORT_STATE_KEY = 'bambuddy-inventory-sort';
@@ -342,6 +352,11 @@ export default function InventoryPage() {
refetchInterval: 30000,
});
const { data: settings } = useQuery({
queryKey: ['settings'],
queryFn: api.getSettings,
});
const deleteMutation = useMutation({
mutationFn: (id: number) => api.deleteSpool(id),
onSuccess: () => {
@@ -392,6 +407,8 @@ export default function InventoryPage() {
const inPrinterCount = assignments?.length ?? 0;
const currencySymbol = getCurrencySymbol(settings?.currency || 'USD');
// Map spool_id -> assignment for location column
const assignmentMap = useMemo(() => {
const map: Record<number, SpoolAssignment> = {};
@@ -927,7 +944,7 @@ export default function InventoryPage() {
>
{visibleColumns.map((colId) => (
<td key={colId} className="py-3 px-4">
{columnCells[colId]?.({ spool, remaining, pct, assignmentMap })}
{columnCells[colId]?.({ spool, remaining, pct, assignmentMap, currencySymbol })}
</td>
))}
<td className="py-3 px-4">