Compare commits
20 Commits
agent/dex/
...
9b0ffc4309
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b0ffc4309 | |||
| 10c9340e74 | |||
| ffff4213b6 | |||
| fc564c6c5a | |||
| f1614029b5 | |||
| 1109d1dd2f | |||
| 32798fbf14 | |||
| fd26b205bf | |||
| 41f66005a6 | |||
| 62d74beba4 | |||
| fca2ef5b84 | |||
| 3ac8432360 | |||
| f15597966f | |||
| a54fcdd371 | |||
| 1b86d617cd | |||
|
|
fd39fff433 | ||
| 2243859286 | |||
|
|
3fe0850711 | ||
| 42285c5dac | |||
| 9cd619b5ee |
@@ -1,37 +1,25 @@
|
||||
# ── Stage 1: Build ──────────────────────────────────────────
|
||||
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
|
||||
WORKDIR /src
|
||||
# Build stage
|
||||
FROM golang:1.24-alpine AS builder
|
||||
|
||||
# Copy csproj first for layer caching — restores before copying source
|
||||
COPY Extrudex.csproj .
|
||||
RUN dotnet restore
|
||||
|
||||
# Copy the rest of the source
|
||||
COPY . .
|
||||
RUN dotnet publish Extrudex.csproj \
|
||||
-c Release \
|
||||
-o /app/publish \
|
||||
--no-restore
|
||||
|
||||
# ── Stage 2: Runtime ────────────────────────────────────────
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS runtime
|
||||
WORKDIR /app
|
||||
|
||||
# Install curl for health check (not included in aspnet base image)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*
|
||||
# Copy go mod files first for caching
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# Non-root user for security
|
||||
RUN adduser --disabled-password --gecos "" appuser
|
||||
USER appuser
|
||||
# Copy source and build
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o server ./cmd/server
|
||||
|
||||
# Copy published output from build stage
|
||||
COPY --from=build /app/publish .
|
||||
# Final stage
|
||||
FROM alpine:latest
|
||||
RUN apk --no-cache add ca-certificates
|
||||
|
||||
WORKDIR /root/
|
||||
|
||||
# Copy binary from builder
|
||||
COPY --from=builder /app/server .
|
||||
|
||||
# ASP.NET Core listens on 8080 by default in .NET 8+
|
||||
EXPOSE 8080
|
||||
|
||||
# Health check against /health endpoint
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD curl --fail http://localhost:8080/health || exit 1
|
||||
|
||||
ENTRYPOINT ["dotnet", "Extrudex.dll"]
|
||||
CMD ["./server"]
|
||||
|
||||
50
backend/Domain/Interfaces/IFilamentUsageService.cs
Normal file
50
backend/Domain/Interfaces/IFilamentUsageService.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using Extrudex.Domain.Entities;
|
||||
|
||||
namespace Extrudex.Domain.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Service for persisting and querying filament usage records.
|
||||
/// Tracks consumption per print job and per spool for COGS and inventory tracking.
|
||||
/// </summary>
|
||||
public interface IFilamentUsageService
|
||||
{
|
||||
/// <summary>
|
||||
/// Records a new filament usage entry for a print job.
|
||||
/// </summary>
|
||||
/// <param name="printJobId">The print job that consumed the filament.</param>
|
||||
/// <param name="spoolId">The spool that provided the filament.</param>
|
||||
/// <param name="printerId">The printer that executed the print.</param>
|
||||
/// <param name="gramsUsed">Grams of filament consumed.</param>
|
||||
/// <param name="mmExtruded">Millimeters of filament extruded.</param>
|
||||
/// <param name="notes">Optional notes about this usage record.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The created FilamentUsage entity.</returns>
|
||||
Task<FilamentUsage> RecordUsageAsync(
|
||||
Guid printJobId,
|
||||
Guid spoolId,
|
||||
Guid printerId,
|
||||
decimal gramsUsed,
|
||||
decimal mmExtruded,
|
||||
string? notes = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves all filament usage records for a specific print job.
|
||||
/// </summary>
|
||||
/// <param name="printJobId">The print job ID.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Collection of filament usage records for the print job.</returns>
|
||||
Task<IReadOnlyList<FilamentUsage>> GetByPrintJobAsync(
|
||||
Guid printJobId,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves all filament usage records for a specific spool.
|
||||
/// </summary>
|
||||
/// <param name="spoolId">The spool ID.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Collection of filament usage records for the spool.</returns>
|
||||
Task<IReadOnlyList<FilamentUsage>> GetBySpoolAsync(
|
||||
Guid spoolId,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
79
backend/Infrastructure/Services/FilamentUsageService.cs
Normal file
79
backend/Infrastructure/Services/FilamentUsageService.cs
Normal file
@@ -0,0 +1,79 @@
|
||||
using Extrudex.Domain.Entities;
|
||||
using Extrudex.Domain.Interfaces;
|
||||
using Extrudex.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Extrudex.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// EF Core–backed implementation of the filament usage service.
|
||||
/// Persists usage records to the database and provides query methods
|
||||
/// for retrieving usage by print job or spool.
|
||||
/// </summary>
|
||||
public class FilamentUsageService : IFilamentUsageService
|
||||
{
|
||||
private readonly ExtrudexDbContext _dbContext;
|
||||
private readonly ILogger<FilamentUsageService> _logger;
|
||||
|
||||
public FilamentUsageService(
|
||||
ExtrudexDbContext dbContext,
|
||||
ILogger<FilamentUsageService> logger)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<FilamentUsage> RecordUsageAsync(
|
||||
Guid printJobId,
|
||||
Guid spoolId,
|
||||
Guid printerId,
|
||||
decimal gramsUsed,
|
||||
decimal mmExtruded,
|
||||
string? notes = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var usage = new FilamentUsage
|
||||
{
|
||||
PrintJobId = printJobId,
|
||||
SpoolId = spoolId,
|
||||
PrinterId = printerId,
|
||||
GramsUsed = gramsUsed,
|
||||
MmExtruded = mmExtruded,
|
||||
RecordedAt = DateTime.UtcNow,
|
||||
Notes = notes
|
||||
};
|
||||
|
||||
_dbContext.FilamentUsages.Add(usage);
|
||||
await _dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Recorded filament usage: {Grams}g / {Mm}mm for print job {JobId} on spool {SpoolId}",
|
||||
gramsUsed, mmExtruded, printJobId, spoolId);
|
||||
|
||||
return usage;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<FilamentUsage>> GetByPrintJobAsync(
|
||||
Guid printJobId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _dbContext.FilamentUsages
|
||||
.Where(u => u.PrintJobId == printJobId)
|
||||
.OrderByDescending(u => u.RecordedAt)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<FilamentUsage>> GetBySpoolAsync(
|
||||
Guid spoolId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _dbContext.FilamentUsages
|
||||
.Where(u => u.SpoolId == spoolId)
|
||||
.OrderByDescending(u => u.RecordedAt)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
390
backend/Infrastructure/Services/MoonrakerUsagePoller.cs
Normal file
390
backend/Infrastructure/Services/MoonrakerUsagePoller.cs
Normal file
@@ -0,0 +1,390 @@
|
||||
using Extrudex.Domain.DTOs.Moonraker;
|
||||
using Extrudex.Domain.Entities;
|
||||
using Extrudex.Domain.Enums;
|
||||
using Extrudex.Domain.Interfaces;
|
||||
using Extrudex.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Extrudex.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration options for the Moonraker usage polling service.
|
||||
/// </summary>
|
||||
public class MoonrakerPollerOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// How often to poll each Moonraker printer for filament usage data.
|
||||
/// Default: 30 seconds.
|
||||
/// </summary>
|
||||
public TimeSpan PollInterval { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>
|
||||
/// Timeout for individual Moonraker HTTP requests.
|
||||
/// Default: 10 seconds.
|
||||
/// </summary>
|
||||
public TimeSpan RequestTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the polling service is enabled. Default: true.
|
||||
/// Set to false to disable polling (e.g., in development or testing).
|
||||
/// </summary>
|
||||
public bool Enabled { get; set; } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Background service that periodically polls Moonraker-connected printers
|
||||
/// for filament usage data. When a print job is detected as complete,
|
||||
/// the usage data is persisted to the FilamentUsage table via
|
||||
/// <see cref="IFilamentUsageService"/>.
|
||||
///
|
||||
/// <para>Polling logic:</para>
|
||||
/// <list type="number">
|
||||
/// <item>Query the database for all active printers with ConnectionType == Moonraker.</item>
|
||||
/// <item>For each printer, call <see cref="IMoonrakerClient.GetPrintStatsAsync"/> for live data
|
||||
/// and <see cref="IMoonrakerClient.GetPrintHistoryAsync"/> for completed job history.</item>
|
||||
/// <item>If usage data is available and the print state is "complete",
|
||||
/// create or update a FilamentUsage record.</item>
|
||||
/// <item>If the printer is unreachable or returns malformed data, log a warning
|
||||
/// and continue to the next printer (no crash).</item>
|
||||
/// </list>
|
||||
///
|
||||
/// <para>Error handling:</para>
|
||||
/// <list type="bullet">
|
||||
/// <item>API unreachable: logged as warning, poller continues for other printers.</item>
|
||||
/// <item>Malformed response: logged as warning, poller continues.</item>
|
||||
/// <item>Database errors: logged as error, poller continues.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public class MoonrakerUsagePoller : BackgroundService
|
||||
{
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly ILogger<MoonrakerUsagePoller> _logger;
|
||||
private readonly MoonrakerPollerOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks which Moonraker print jobs have already been recorded,
|
||||
/// keyed by "printerId:gcodeFileName" to avoid duplicate recording.
|
||||
/// </summary>
|
||||
private readonly HashSet<string> _recordedJobs = new();
|
||||
|
||||
public MoonrakerUsagePoller(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<MoonrakerUsagePoller> logger,
|
||||
IOptions<MoonrakerPollerOptions> options)
|
||||
{
|
||||
_scopeFactory = scopeFactory;
|
||||
_logger = logger;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
_logger.LogInformation("Moonraker usage poller is disabled via configuration.");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"Moonraker usage poller starting. Poll interval: {Interval}",
|
||||
_options.PollInterval);
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await PollAllPrintersAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Unexpected error in Moonraker usage poller cycle. Continuing.");
|
||||
}
|
||||
|
||||
await Task.Delay(_options.PollInterval, stoppingToken);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Moonraker usage poller stopping.");
|
||||
}
|
||||
|
||||
private async Task PollAllPrintersAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var dbContext = scope.ServiceProvider.GetRequiredService<ExtrudexDbContext>();
|
||||
var moonrakerClient = scope.ServiceProvider.GetRequiredService<IMoonrakerClient>();
|
||||
var usageService = scope.ServiceProvider.GetRequiredService<IFilamentUsageService>();
|
||||
|
||||
var printers = await dbContext.Printers
|
||||
.Where(p => p.IsActive && p.ConnectionType == ConnectionType.Moonraker)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (printers.Count == 0)
|
||||
{
|
||||
_logger.LogDebug("No active Moonraker printers found.");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Polling {Count} Moonraker printer(s).", printers.Count);
|
||||
|
||||
foreach (var printer in printers)
|
||||
{
|
||||
await PollPrinterAsync(
|
||||
printer, moonrakerClient, usageService, dbContext, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PollPrinterAsync(
|
||||
Printer printer,
|
||||
IMoonrakerClient moonrakerClient,
|
||||
IFilamentUsageService usageService,
|
||||
ExtrudexDbContext dbContext,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Polling Moonraker printer {PrinterName} ({Host}:{Port})",
|
||||
printer.Name, printer.HostnameOrIp, printer.Port);
|
||||
|
||||
try
|
||||
{
|
||||
var printStats = await moonrakerClient.GetPrintStatsAsync(
|
||||
printer.HostnameOrIp,
|
||||
printer.Port,
|
||||
printer.ApiKey,
|
||||
cancellationToken);
|
||||
|
||||
if (printStats is null)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"No print stats available from printer {PrinterName}.", printer.Name);
|
||||
return;
|
||||
}
|
||||
|
||||
printer.LastSeenAt = DateTime.UtcNow;
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Printer {PrinterName}: state={State}, filament={Mm}mm, file={File}",
|
||||
printer.Name, printStats.State, printStats.FilamentUsedMm, printStats.Filename);
|
||||
|
||||
decimal mmExtruded = printStats.FilamentUsedMm;
|
||||
if (mmExtruded <= 0)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Printer {PrinterName} has no filament usage to record.", printer.Name);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsCompleteState(printStats.State))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Printer {PrinterName} print state '{State}' is not complete; skipping.",
|
||||
printer.Name, printStats.State);
|
||||
return;
|
||||
}
|
||||
|
||||
string gcodeFileName = printStats.Filename ?? $"unknown-{Guid.NewGuid():N}";
|
||||
var deduplicationKey = $"{printer.Id}:{gcodeFileName}";
|
||||
if (_recordedJobs.Contains(deduplicationKey))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Printer {PrinterName} job '{File}' already recorded; skipping.",
|
||||
printer.Name, gcodeFileName);
|
||||
return;
|
||||
}
|
||||
|
||||
DateTime? startedAt = null;
|
||||
DateTime? completedAt = null;
|
||||
try
|
||||
{
|
||||
var history = await moonrakerClient.GetPrintHistoryAsync(
|
||||
printer.HostnameOrIp, printer.Port, printer.ApiKey,
|
||||
limit: 1, cancellationToken);
|
||||
|
||||
if (history.Items.Count > 0)
|
||||
{
|
||||
var latestJob = history.Items[0];
|
||||
startedAt = latestJob.StartTime;
|
||||
completedAt = latestJob.EndTime;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex,
|
||||
"Could not fetch history for printer {PrinterName}; proceeding with stats only.",
|
||||
printer.Name);
|
||||
}
|
||||
|
||||
var printJob = await FindOrCreatePrintJobAsync(
|
||||
dbContext, printer, mmExtruded, gcodeFileName,
|
||||
startedAt, completedAt, cancellationToken);
|
||||
|
||||
if (printJob is null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Could not find or create print job for printer {PrinterName}. No active spool found.",
|
||||
printer.Name);
|
||||
return;
|
||||
}
|
||||
|
||||
var spool = await dbContext.Spools.FindAsync(
|
||||
new object[] { printJob.SpoolId }, cancellationToken);
|
||||
|
||||
var gramsUsed = CalculateGramsUsed(mmExtruded, spool);
|
||||
|
||||
await usageService.RecordUsageAsync(
|
||||
printJobId: printJob.Id,
|
||||
spoolId: printJob.SpoolId,
|
||||
printerId: printer.Id,
|
||||
gramsUsed: gramsUsed,
|
||||
mmExtruded: mmExtruded,
|
||||
notes: $"Moonraker auto-recorded: {gcodeFileName}",
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
_recordedJobs.Add(deduplicationKey);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Recorded Moonraker usage for printer {PrinterName}: {Mm}mm / {Grams}g, job '{File}'",
|
||||
printer.Name, mmExtruded, gramsUsed, gcodeFileName);
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Moonraker API unreachable for printer {PrinterName} ({Host}:{Port}). Will retry next cycle.",
|
||||
printer.Name, printer.HostnameOrIp, printer.Port);
|
||||
}
|
||||
catch (TaskCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (TaskCanceledException ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Moonraker request timed out for printer {PrinterName} ({Host}:{Port}).",
|
||||
printer.Name, printer.HostnameOrIp, printer.Port);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Unexpected error polling Moonraker printer {PrinterName}. Continuing to next printer.",
|
||||
printer.Name);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsCompleteState(string state) =>
|
||||
state.Equals("complete", StringComparison.OrdinalIgnoreCase) ||
|
||||
state.Equals("completed", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private async Task<PrintJob?> FindOrCreatePrintJobAsync(
|
||||
ExtrudexDbContext dbContext,
|
||||
Printer printer,
|
||||
decimal mmExtruded,
|
||||
string gcodeFileName,
|
||||
DateTime? startedAt,
|
||||
DateTime? completedAt,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(gcodeFileName))
|
||||
{
|
||||
var existingJob = await dbContext.PrintJobs
|
||||
.Where(j => j.PrinterId == printer.Id &&
|
||||
j.GcodeFilePath == gcodeFileName &&
|
||||
j.DataSource == DataSource.Moonraker &&
|
||||
j.Status != JobStatus.Cancelled)
|
||||
.OrderByDescending(j => j.CreatedAt)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (existingJob is not null)
|
||||
{
|
||||
existingJob.MmExtruded = mmExtruded;
|
||||
existingJob.GramsDerived = CalculateGramsUsed(
|
||||
mmExtruded,
|
||||
await dbContext.Spools.FindAsync(
|
||||
new object[] { existingJob.SpoolId }, cancellationToken));
|
||||
existingJob.Status = JobStatus.Completed;
|
||||
existingJob.CompletedAt = completedAt ?? DateTime.UtcNow;
|
||||
existingJob.StartedAt ??= startedAt;
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return existingJob;
|
||||
}
|
||||
}
|
||||
|
||||
var spool = await FindActiveSpoolForPrinterAsync(dbContext, printer, cancellationToken);
|
||||
if (spool is null) return null;
|
||||
|
||||
var gramsDerived = CalculateGramsUsed(mmExtruded, spool);
|
||||
|
||||
var newJob = new PrintJob
|
||||
{
|
||||
PrinterId = printer.Id,
|
||||
SpoolId = spool.Id,
|
||||
PrintName = gcodeFileName ?? "Moonraker Print",
|
||||
GcodeFilePath = gcodeFileName,
|
||||
MmExtruded = mmExtruded,
|
||||
GramsDerived = gramsDerived,
|
||||
FilamentDiameterAtPrintMm = spool.FilamentDiameterMm,
|
||||
MaterialDensityAtPrint = GetMaterialDensity(spool),
|
||||
DataSource = DataSource.Moonraker,
|
||||
Status = JobStatus.Completed,
|
||||
StartedAt = startedAt ?? DateTime.UtcNow,
|
||||
CompletedAt = completedAt ?? DateTime.UtcNow,
|
||||
Notes = "Auto-created by Moonraker usage poller"
|
||||
};
|
||||
|
||||
dbContext.PrintJobs.Add(newJob);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return newJob;
|
||||
}
|
||||
|
||||
private static async Task<Spool?> FindActiveSpoolForPrinterAsync(
|
||||
ExtrudexDbContext dbContext,
|
||||
Printer printer,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var amsSpool = await dbContext.AmsSlots
|
||||
.Include(s => s.Spool)
|
||||
.ThenInclude(s => s!.MaterialBase)
|
||||
.Include(s => s.AmsUnit)
|
||||
.Where(s => s.AmsUnit.PrinterId == printer.Id && s.Spool != null && s.Spool.IsActive)
|
||||
.Select(s => s.Spool)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (amsSpool is not null) return amsSpool;
|
||||
|
||||
return await dbContext.Spools
|
||||
.Include(s => s.MaterialBase)
|
||||
.Where(s => s.IsActive)
|
||||
.OrderByDescending(s => s.WeightRemainingGrams)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private static decimal CalculateGramsUsed(decimal mmExtruded, Spool? spool)
|
||||
{
|
||||
if (spool is null) return 0m;
|
||||
var diameterMm = spool.FilamentDiameterMm;
|
||||
var densityGcm3 = GetMaterialDensity(spool);
|
||||
var radiusMm = diameterMm / 2m;
|
||||
var crossSectionArea = Math.PI * (double)radiusMm * (double)radiusMm;
|
||||
var volumeMm3 = (double)mmExtruded * crossSectionArea;
|
||||
var volumeCm3 = volumeMm3 / 1000.0;
|
||||
var grams = volumeCm3 * (double)densityGcm3;
|
||||
return Math.Round((decimal)grams, 2);
|
||||
}
|
||||
|
||||
private static decimal GetMaterialDensity(Spool? spool)
|
||||
{
|
||||
return spool?.MaterialBase?.Name?.ToUpperInvariant() switch
|
||||
{
|
||||
"PLA" => 1.24m,
|
||||
"PETG" => 1.27m,
|
||||
"ABS" => 1.04m,
|
||||
"ASA" => 1.07m,
|
||||
"TPU" => 1.21m,
|
||||
"NYLON" or "PA" => 1.13m,
|
||||
"PC" => 1.20m,
|
||||
_ => 1.24m
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,14 @@ builder.Services.AddSingleton<ILowStockDetector, LowStockDetector>();
|
||||
// ── Usage Logging ───────────────────────────────────────────
|
||||
builder.Services.AddScoped<IUsageLogService, UsageLogService>();
|
||||
|
||||
// ── Filament Usage Service ──────────────────────────────────
|
||||
builder.Services.AddScoped<IFilamentUsageService, FilamentUsageService>();
|
||||
|
||||
// ── Moonraker Usage Poller (Background Service) ─────────────
|
||||
builder.Services.Configure<MoonrakerPollerOptions>(
|
||||
builder.Configuration.GetSection("MoonrakerPoller"));
|
||||
builder.Services.AddHostedService<MoonrakerUsagePoller>();
|
||||
|
||||
// ── FluentValidation ──────────────────────────────────────
|
||||
// Registers all validators from the API assembly into DI.
|
||||
builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
|
||||
|
||||
@@ -23,5 +23,11 @@
|
||||
},
|
||||
"FilamentAlerts": {
|
||||
"LowStockThresholdPercent": 20
|
||||
},
|
||||
"MoonrakerPoller": {
|
||||
"Enabled": true,
|
||||
"PollInterval": "00:00:30",
|
||||
"RequestTimeout": "00:00:10"
|
||||
}
|
||||
}
|
||||
}
|
||||
90
backend/cmd/server/main.go
Normal file
90
backend/cmd/server/main.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/config"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/db"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/router"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/sse"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Setup structured logging
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
|
||||
Level: slog.LevelInfo,
|
||||
})))
|
||||
|
||||
// Load configuration
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
slog.Error("failed to load config", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
slog.Info("config loaded", "port", cfg.Port, "cors_origin", cfg.CorsOrigin)
|
||||
|
||||
// Connect to database
|
||||
dbPool, err := db.NewPool(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
slog.Error("failed to connect to database", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer db.ClosePool(dbPool)
|
||||
|
||||
slog.Info("database connected")
|
||||
|
||||
// Create SSE broadcaster and start it
|
||||
sseBC := sse.NewBroadcaster(128)
|
||||
sseBC.Start()
|
||||
defer sseBC.Stop()
|
||||
|
||||
slog.Info("sse broadcaster started")
|
||||
|
||||
// Create router
|
||||
r := router.New(cfg, dbPool, sseBC)
|
||||
|
||||
// Create HTTP server
|
||||
// WriteTimeout is 0 for SSE support — the Chi middleware.Timeout(60s)
|
||||
// handles request-level timeouts on non-SSE routes.
|
||||
server := &http.Server{
|
||||
Addr: ":" + cfg.Port,
|
||||
Handler: r,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 0, // disabled for SSE long-lived connections
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
// Start server in goroutine
|
||||
go func() {
|
||||
slog.Info("server starting", "addr", server.Addr)
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
slog.Error("server error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for shutdown signal
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
|
||||
slog.Info("server shutting down")
|
||||
|
||||
// Graceful shutdown
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(ctx); err != nil {
|
||||
slog.Error("server shutdown error", "error", err)
|
||||
}
|
||||
|
||||
db.ClosePool(dbPool)
|
||||
slog.Info("server stopped")
|
||||
}
|
||||
18
backend/go.mod
Normal file
18
backend/go.mod
Normal file
@@ -0,0 +1,18 @@
|
||||
module github.com/CubeCraft-Creations/Extrudex/backend
|
||||
|
||||
go 1.24
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.2.0
|
||||
github.com/jackc/pgx/v5 v5.7.4
|
||||
github.com/kelseyhightower/envconfig v1.4.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/crypto v0.31.0 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
)
|
||||
32
backend/go.sum
Normal file
32
backend/go.sum
Normal file
@@ -0,0 +1,32 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-chi/chi/v5 v5.2.0 h1:Aj1EtB0qR2Rdo2dG4O94RIU35w2lvQSj6BRA4+qwFL0=
|
||||
github.com/go-chi/chi/v5 v5.2.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
|
||||
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
|
||||
github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
24
backend/internal/config/config.go
Normal file
24
backend/internal/config/config.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/kelseyhightower/envconfig"
|
||||
)
|
||||
|
||||
// Config holds all application configuration loaded from environment variables.
|
||||
type Config struct {
|
||||
DatabaseURL string `envconfig:"database_url" required:"true"`
|
||||
Port string `envconfig:"port" default:"8080"`
|
||||
CorsOrigin string `envconfig:"cors_origin" default:"*"`
|
||||
LogLevel string `envconfig:"log_level" default:"info"`
|
||||
}
|
||||
|
||||
// Load reads configuration from environment variables and returns a populated Config.
|
||||
func Load() (*Config, error) {
|
||||
var cfg Config
|
||||
if err := envconfig.Process("", &cfg); err != nil {
|
||||
return nil, fmt.Errorf("failed to load config: %w", err)
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
34
backend/internal/db/db.go
Normal file
34
backend/internal/db/db.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewPool creates a new pgx connection pool and verifies connectivity with a ping.
|
||||
func NewPool(databaseURL string) (*pgxpool.Pool, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create db pool: %w", err)
|
||||
}
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("failed to ping db: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// ClosePool gracefully closes the connection pool.
|
||||
func ClosePool(pool *pgxpool.Pool) {
|
||||
if pool != nil {
|
||||
pool.Close()
|
||||
}
|
||||
}
|
||||
67
backend/internal/dtos/dtos.go
Normal file
67
backend/internal/dtos/dtos.go
Normal file
@@ -0,0 +1,67 @@
|
||||
// Package dtos defines request/response data transfer objects for the Extrudex API.
|
||||
// DTOs keep HTTP serialization concerns separate from domain models.
|
||||
package dtos
|
||||
|
||||
// ============================================================================
|
||||
// Common Response Wrappers
|
||||
// ============================================================================
|
||||
|
||||
// ListResponse wraps a paginated collection response.
|
||||
type ListResponse struct {
|
||||
Data any `json:"data"`
|
||||
Total int `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
// SingleResponse wraps a single-item response.
|
||||
type SingleResponse struct {
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
// ErrorResponse is the standard error payload for all API errors.
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Code int `json:"code"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Filament DTOs
|
||||
// ============================================================================
|
||||
|
||||
// CreateFilamentRequest is the POST body for creating a new filament spool.
|
||||
type CreateFilamentRequest struct {
|
||||
Name string `json:"name"`
|
||||
MaterialBaseID int `json:"material_base_id"`
|
||||
MaterialFinishID int `json:"material_finish_id"`
|
||||
MaterialModifierID *int `json:"material_modifier_id,omitempty"`
|
||||
ColorHex string `json:"color_hex"`
|
||||
Brand *string `json:"brand,omitempty"`
|
||||
DiameterMM *float64 `json:"diameter_mm,omitempty"` // defaults to 1.75
|
||||
InitialGrams int `json:"initial_grams"`
|
||||
RemainingGrams int `json:"remaining_grams"`
|
||||
SpoolWeightGrams *int `json:"spool_weight_grams,omitempty"`
|
||||
CostUSD *float64 `json:"cost_usd,omitempty"`
|
||||
LowStockThresholdGrams *int `json:"low_stock_threshold_grams,omitempty"` // defaults to 50
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
Barcode *string `json:"barcode,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateFilamentRequest is the PUT body for partially updating a filament spool.
|
||||
// All fields are optional — only non-nil fields are applied.
|
||||
type UpdateFilamentRequest struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
MaterialBaseID *int `json:"material_base_id,omitempty"`
|
||||
MaterialFinishID *int `json:"material_finish_id,omitempty"`
|
||||
MaterialModifierID *int `json:"material_modifier_id,omitempty"`
|
||||
ColorHex *string `json:"color_hex,omitempty"`
|
||||
Brand *string `json:"brand,omitempty"`
|
||||
DiameterMM *float64 `json:"diameter_mm,omitempty"`
|
||||
InitialGrams *int `json:"initial_grams,omitempty"`
|
||||
RemainingGrams *int `json:"remaining_grams,omitempty"`
|
||||
SpoolWeightGrams *int `json:"spool_weight_grams,omitempty"`
|
||||
CostUSD *float64 `json:"cost_usd,omitempty"`
|
||||
LowStockThresholdGrams *int `json:"low_stock_threshold_grams,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
Barcode *string `json:"barcode,omitempty"`
|
||||
}
|
||||
273
backend/internal/handlers/filament_handler.go
Normal file
273
backend/internal/handlers/filament_handler.go
Normal file
@@ -0,0 +1,273 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/services"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// FilamentHandler handles HTTP requests for filament spool CRUD operations.
|
||||
type FilamentHandler struct {
|
||||
service *services.FilamentService
|
||||
}
|
||||
|
||||
// NewFilamentHandler creates a FilamentHandler with the given service.
|
||||
func NewFilamentHandler(service *services.FilamentService) *FilamentHandler {
|
||||
return &FilamentHandler{service: service}
|
||||
}
|
||||
|
||||
// List handles GET /api/filaments — returns paginated, filtered spools.
|
||||
func (h *FilamentHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset := parsePagination(r)
|
||||
filter := repositories.FilamentFilter{
|
||||
Material: r.URL.Query().Get("material"),
|
||||
Finish: r.URL.Query().Get("finish"),
|
||||
Color: r.URL.Query().Get("color"),
|
||||
LowStock: r.URL.Query().Get("low_stock") == "true",
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
}
|
||||
|
||||
spools, total, err := h.service.List(r.Context(), filter)
|
||||
if err != nil {
|
||||
slog.Error("failed to list filaments", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.ListResponse{
|
||||
Data: spools,
|
||||
Total: total,
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
})
|
||||
}
|
||||
|
||||
// Get handles GET /api/filaments/{id} — returns a single spool.
|
||||
func (h *FilamentHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "invalid filament ID",
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
spool, err := h.service.GetByID(r.Context(), id)
|
||||
if err != nil {
|
||||
slog.Error("failed to get filament", "id", id, "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
if spool == nil {
|
||||
writeJSON(w, http.StatusNotFound, dtos.ErrorResponse{
|
||||
Error: "filament not found",
|
||||
Code: http.StatusNotFound,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.SingleResponse{Data: spool})
|
||||
}
|
||||
|
||||
// Create handles POST /api/filaments — creates a new filament spool.
|
||||
func (h *FilamentHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req dtos.CreateFilamentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "invalid request body",
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required fields.
|
||||
if err := services.ValidateCreateFilamentRequest(req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "validation failed: " + err.Error(),
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Build domain model.
|
||||
spool := models.FilamentSpool{
|
||||
Name: req.Name,
|
||||
MaterialBaseID: req.MaterialBaseID,
|
||||
MaterialFinishID: req.MaterialFinishID,
|
||||
MaterialModifierID: req.MaterialModifierID,
|
||||
ColorHex: req.ColorHex,
|
||||
Brand: req.Brand,
|
||||
DiameterMM: 1.75, // default
|
||||
InitialGrams: req.InitialGrams,
|
||||
RemainingGrams: req.RemainingGrams,
|
||||
SpoolWeightGrams: req.SpoolWeightGrams,
|
||||
CostUSD: req.CostUSD,
|
||||
LowStockThresholdGrams: 50, // default
|
||||
Notes: req.Notes,
|
||||
Barcode: req.Barcode,
|
||||
}
|
||||
if req.DiameterMM != nil {
|
||||
spool.DiameterMM = *req.DiameterMM
|
||||
}
|
||||
if req.LowStockThresholdGrams != nil {
|
||||
spool.LowStockThresholdGrams = *req.LowStockThresholdGrams
|
||||
}
|
||||
|
||||
created, err := h.service.Create(r.Context(), &spool)
|
||||
if err != nil {
|
||||
slog.Error("failed to create filament", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, dtos.SingleResponse{Data: created})
|
||||
}
|
||||
|
||||
// Update handles PUT /api/filaments/{id} — partially updates a spool.
|
||||
func (h *FilamentHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "invalid filament ID",
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var req dtos.UpdateFilamentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "invalid request body",
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate update fields.
|
||||
if err := services.ValidateUpdateFilamentRequest(req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "validation failed: " + err.Error(),
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Build updates map (only non-nil fields).
|
||||
updates := buildFilamentUpdates(req)
|
||||
|
||||
updated, err := h.service.Update(r.Context(), id, updates)
|
||||
if err != nil {
|
||||
slog.Error("failed to update filament", "id", id, "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
if updated == nil {
|
||||
writeJSON(w, http.StatusNotFound, dtos.ErrorResponse{
|
||||
Error: "filament not found",
|
||||
Code: http.StatusNotFound,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.SingleResponse{Data: updated})
|
||||
}
|
||||
|
||||
// Delete handles DELETE /api/filaments/{id} — soft-deletes a spool.
|
||||
func (h *FilamentHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.Atoi(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "invalid filament ID",
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
deleted, err := h.service.SoftDelete(r.Context(), id)
|
||||
if err != nil {
|
||||
slog.Error("failed to delete filament", "id", id, "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
if !deleted {
|
||||
writeJSON(w, http.StatusNotFound, dtos.ErrorResponse{
|
||||
Error: "filament not found",
|
||||
Code: http.StatusNotFound,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// buildFilamentUpdates converts an UpdateFilamentRequest to a map of column→value.
|
||||
func buildFilamentUpdates(req dtos.UpdateFilamentRequest) map[string]interface{} {
|
||||
updates := make(map[string]interface{})
|
||||
if req.Name != nil {
|
||||
updates["name"] = *req.Name
|
||||
}
|
||||
if req.MaterialBaseID != nil {
|
||||
updates["material_base_id"] = *req.MaterialBaseID
|
||||
}
|
||||
if req.MaterialFinishID != nil {
|
||||
updates["material_finish_id"] = *req.MaterialFinishID
|
||||
}
|
||||
if req.MaterialModifierID != nil {
|
||||
updates["material_modifier_id"] = *req.MaterialModifierID
|
||||
}
|
||||
if req.ColorHex != nil {
|
||||
updates["color_hex"] = *req.ColorHex
|
||||
}
|
||||
if req.Brand != nil {
|
||||
updates["brand"] = *req.Brand
|
||||
}
|
||||
if req.DiameterMM != nil {
|
||||
updates["diameter_mm"] = *req.DiameterMM
|
||||
}
|
||||
if req.InitialGrams != nil {
|
||||
updates["initial_grams"] = *req.InitialGrams
|
||||
}
|
||||
if req.RemainingGrams != nil {
|
||||
updates["remaining_grams"] = *req.RemainingGrams
|
||||
}
|
||||
if req.SpoolWeightGrams != nil {
|
||||
updates["spool_weight_grams"] = *req.SpoolWeightGrams
|
||||
}
|
||||
if req.CostUSD != nil {
|
||||
updates["cost_usd"] = *req.CostUSD
|
||||
}
|
||||
if req.LowStockThresholdGrams != nil {
|
||||
updates["low_stock_threshold_grams"] = *req.LowStockThresholdGrams
|
||||
}
|
||||
if req.Notes != nil {
|
||||
updates["notes"] = *req.Notes
|
||||
}
|
||||
if req.Barcode != nil {
|
||||
updates["barcode"] = *req.Barcode
|
||||
}
|
||||
return updates
|
||||
}
|
||||
50
backend/internal/handlers/health.go
Normal file
50
backend/internal/handlers/health.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// HealthHandler provides a health check endpoint that verifies database connectivity.
|
||||
type HealthHandler struct {
|
||||
dbPool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewHealthHandler creates a new HealthHandler with the given database pool.
|
||||
func NewHealthHandler(dbPool *pgxpool.Pool) *HealthHandler {
|
||||
return &HealthHandler{dbPool: dbPool}
|
||||
}
|
||||
|
||||
// ServeHTTP handles GET /health requests.
|
||||
func (h *HealthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dbConnected := false
|
||||
if h.dbPool != nil {
|
||||
if err := h.dbPool.Ping(ctx); err == nil {
|
||||
dbConnected = true
|
||||
} else {
|
||||
slog.Warn("health check db ping failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
resp := map[string]any{
|
||||
"status": "ok",
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
"db_connected": dbConnected,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if !dbConnected {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(resp); err != nil {
|
||||
slog.Error("failed to encode health response", "error", err)
|
||||
}
|
||||
}
|
||||
51
backend/internal/handlers/helpers.go
Normal file
51
backend/internal/handlers/helpers.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/services"
|
||||
)
|
||||
|
||||
// writeJSON serializes v as JSON to the response writer with the given status code.
|
||||
// Logs an error if encoding fails.
|
||||
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
slog.Error("failed to encode JSON response", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// parsePagination reads limit and offset query parameters with defaults of 20 and 0.
|
||||
func parsePagination(r *http.Request) (limit, offset int) {
|
||||
limit = 20
|
||||
offset = 0
|
||||
|
||||
if l := r.URL.Query().Get("limit"); l != "" {
|
||||
if parsed, err := strconv.Atoi(l); err == nil && parsed > 0 {
|
||||
limit = parsed
|
||||
}
|
||||
}
|
||||
if o := r.URL.Query().Get("offset"); o != "" {
|
||||
if parsed, err := strconv.Atoi(o); err == nil && parsed >= 0 {
|
||||
offset = parsed
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ValidateCreateFilamentRequest validates a CreateFilamentRequest DTO.
|
||||
// Re-exports the service-layer validator for handler use.
|
||||
func ValidateCreateFilamentRequest(req dtos.CreateFilamentRequest) error {
|
||||
return services.ValidateCreateFilamentRequest(req)
|
||||
}
|
||||
|
||||
// ValidateUpdateFilamentRequest validates an UpdateFilamentRequest DTO.
|
||||
// Re-exports the service-layer validator for handler use.
|
||||
func ValidateUpdateFilamentRequest(req dtos.UpdateFilamentRequest) error {
|
||||
return services.ValidateUpdateFilamentRequest(req)
|
||||
}
|
||||
34
backend/internal/handlers/material_finish_handler.go
Normal file
34
backend/internal/handlers/material_finish_handler.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
|
||||
)
|
||||
|
||||
// MaterialFinishHandler handles requests for material finish lookup data.
|
||||
type MaterialFinishHandler struct {
|
||||
repo *repositories.MaterialFinishRepository
|
||||
}
|
||||
|
||||
// NewMaterialFinishHandler creates a MaterialFinishHandler with the given repository.
|
||||
func NewMaterialFinishHandler(repo *repositories.MaterialFinishRepository) *MaterialFinishHandler {
|
||||
return &MaterialFinishHandler{repo: repo}
|
||||
}
|
||||
|
||||
// List handles GET /api/finishes — returns all material finishes.
|
||||
func (h *MaterialFinishHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
finishes, err := h.repo.GetAll(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("failed to list finishes", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.SingleResponse{Data: finishes})
|
||||
}
|
||||
34
backend/internal/handlers/material_handler.go
Normal file
34
backend/internal/handlers/material_handler.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
|
||||
)
|
||||
|
||||
// MaterialHandler handles requests for material lookup data.
|
||||
type MaterialHandler struct {
|
||||
repo *repositories.MaterialRepository
|
||||
}
|
||||
|
||||
// NewMaterialHandler creates a MaterialHandler with the given repository.
|
||||
func NewMaterialHandler(repo *repositories.MaterialRepository) *MaterialHandler {
|
||||
return &MaterialHandler{repo: repo}
|
||||
}
|
||||
|
||||
// List handles GET /api/materials — returns all material bases.
|
||||
func (h *MaterialHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
materials, err := h.repo.GetAll(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("failed to list materials", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.SingleResponse{Data: materials})
|
||||
}
|
||||
34
backend/internal/handlers/material_modifier_handler.go
Normal file
34
backend/internal/handlers/material_modifier_handler.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
|
||||
)
|
||||
|
||||
// MaterialModifierHandler handles requests for material modifier lookup data.
|
||||
type MaterialModifierHandler struct {
|
||||
repo *repositories.MaterialModifierRepository
|
||||
}
|
||||
|
||||
// NewMaterialModifierHandler creates a MaterialModifierHandler with the given repository.
|
||||
func NewMaterialModifierHandler(repo *repositories.MaterialModifierRepository) *MaterialModifierHandler {
|
||||
return &MaterialModifierHandler{repo: repo}
|
||||
}
|
||||
|
||||
// List handles GET /api/modifiers — returns all material modifiers.
|
||||
func (h *MaterialModifierHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
modifiers, err := h.repo.GetAll(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("failed to list modifiers", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.SingleResponse{Data: modifiers})
|
||||
}
|
||||
60
backend/internal/handlers/print_job_handler.go
Normal file
60
backend/internal/handlers/print_job_handler.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/services"
|
||||
)
|
||||
|
||||
// PrintJobHandler handles HTTP requests for print job operations.
|
||||
type PrintJobHandler struct {
|
||||
service *services.PrintJobService
|
||||
}
|
||||
|
||||
// NewPrintJobHandler creates a PrintJobHandler with the given service.
|
||||
func NewPrintJobHandler(service *services.PrintJobService) *PrintJobHandler {
|
||||
return &PrintJobHandler{service: service}
|
||||
}
|
||||
|
||||
// List handles GET /api/print-jobs — returns paginated, filtered print jobs.
|
||||
func (h *PrintJobHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset := parsePagination(r)
|
||||
filter := repositories.PrintJobFilter{
|
||||
Status: r.URL.Query().Get("status"),
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
}
|
||||
|
||||
if pidStr := r.URL.Query().Get("printer_id"); pidStr != "" {
|
||||
pid, err := strconv.Atoi(pidStr)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "invalid printer_id",
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
filter.PrinterID = &pid
|
||||
}
|
||||
|
||||
jobs, total, err := h.service.List(r.Context(), filter)
|
||||
if err != nil {
|
||||
slog.Error("failed to list print jobs", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.ListResponse{
|
||||
Data: jobs,
|
||||
Total: total,
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
})
|
||||
}
|
||||
34
backend/internal/handlers/printer_handler.go
Normal file
34
backend/internal/handlers/printer_handler.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/services"
|
||||
)
|
||||
|
||||
// PrinterHandler handles HTTP requests for printer listings.
|
||||
type PrinterHandler struct {
|
||||
service *services.PrinterService
|
||||
}
|
||||
|
||||
// NewPrinterHandler creates a PrinterHandler with the given service.
|
||||
func NewPrinterHandler(service *services.PrinterService) *PrinterHandler {
|
||||
return &PrinterHandler{service: service}
|
||||
}
|
||||
|
||||
// List handles GET /api/printers — returns all printers with printer_type info.
|
||||
func (h *PrinterHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
printers, err := h.service.List(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("failed to list printers", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.SingleResponse{Data: printers})
|
||||
}
|
||||
70
backend/internal/handlers/usage_log_handler.go
Normal file
70
backend/internal/handlers/usage_log_handler.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
|
||||
)
|
||||
|
||||
// UsageLogHandler handles HTTP requests for usage log operations.
|
||||
type UsageLogHandler struct {
|
||||
repo *repositories.UsageLogRepository
|
||||
}
|
||||
|
||||
// NewUsageLogHandler creates a UsageLogHandler with the given repository.
|
||||
func NewUsageLogHandler(repo *repositories.UsageLogRepository) *UsageLogHandler {
|
||||
return &UsageLogHandler{repo: repo}
|
||||
}
|
||||
|
||||
// List handles GET /api/usage-logs — returns paginated, filtered usage logs.
|
||||
func (h *UsageLogHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset := parsePagination(r)
|
||||
filter := repositories.UsageLogFilter{
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
}
|
||||
|
||||
if sidStr := r.URL.Query().Get("spool_id"); sidStr != "" {
|
||||
sid, err := strconv.Atoi(sidStr)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "invalid spool_id",
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
filter.SpoolID = &sid
|
||||
}
|
||||
|
||||
if jidStr := r.URL.Query().Get("job_id"); jidStr != "" {
|
||||
jid, err := strconv.Atoi(jidStr)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, dtos.ErrorResponse{
|
||||
Error: "invalid job_id",
|
||||
Code: http.StatusBadRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
filter.JobID = &jid
|
||||
}
|
||||
|
||||
logs, total, err := h.repo.GetAll(r.Context(), filter)
|
||||
if err != nil {
|
||||
slog.Error("failed to list usage logs", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, dtos.ErrorResponse{
|
||||
Error: "internal server error",
|
||||
Code: http.StatusInternalServerError,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, dtos.ListResponse{
|
||||
Data: logs,
|
||||
Total: total,
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
})
|
||||
}
|
||||
162
backend/internal/models/models.go
Normal file
162
backend/internal/models/models.go
Normal file
@@ -0,0 +1,162 @@
|
||||
// Package models defines the Extrudex domain model structs.
|
||||
// These map 1:1 to PostgreSQL tables with snake_case JSON serialization.
|
||||
// Nullable fields use pointer types; all timestamps are time.Time.
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// ============================================================================
|
||||
// Lookup Tables
|
||||
// ============================================================================
|
||||
|
||||
// PrinterType represents a printer technology category (fdm, resin, etc.).
|
||||
type PrinterType struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// JobStatus represents a print job lifecycle state.
|
||||
type JobStatus struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// MaterialBase represents a base material type (PLA, PETG, ABS, etc.).
|
||||
// Density and temperature ranges are stored here for grams-calculation and slicing guidance.
|
||||
type MaterialBase struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
DensityGCm3 float64 `json:"density_g_cm3"`
|
||||
ExtrusionTempMin *int `json:"extrusion_temp_min,omitempty"`
|
||||
ExtrusionTempMax *int `json:"extrusion_temp_max,omitempty"`
|
||||
BedTempMin *int `json:"bed_temp_min,omitempty"`
|
||||
BedTempMax *int `json:"bed_temp_max,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// MaterialFinish represents the visual/texture finish (Basic, Silk, Matte, etc.).
|
||||
type MaterialFinish struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// MaterialModifier represents an additive property (Carbon Fiber, Wood-Filled, etc.).
|
||||
type MaterialModifier struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Core Entity Tables
|
||||
// ============================================================================
|
||||
|
||||
// Printer represents a 3D printer in the fleet.
|
||||
type Printer struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
PrinterTypeID int `json:"printer_type_id"`
|
||||
PrinterType *PrinterType `json:"printer_type,omitempty"` // populated on JOIN queries
|
||||
Manufacturer *string `json:"manufacturer,omitempty"`
|
||||
Model *string `json:"model,omitempty"`
|
||||
MoonrakerURL *string `json:"moonraker_url,omitempty"`
|
||||
MoonrakerAPIKey *string `json:"moonraker_api_key,omitempty"`
|
||||
MQTTBrokerHost *string `json:"mqtt_broker_host,omitempty"`
|
||||
MQTTTopicPrefix *string `json:"mqtt_topic_prefix,omitempty"`
|
||||
MQTTTLSEnabled bool `json:"mqtt_tls_enabled"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// FilamentSpool represents a physical filament spool in inventory.
|
||||
// material_finish_id defaults to 1 ("Basic"); material_modifier_id is optional.
|
||||
// Grams are always physically measured values — grams_used is derived, not stored.
|
||||
type FilamentSpool struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
MaterialBaseID int `json:"material_base_id"`
|
||||
MaterialBase *MaterialBase `json:"material_base,omitempty"` // JOIN
|
||||
MaterialFinishID int `json:"material_finish_id"`
|
||||
MaterialFinish *MaterialFinish `json:"material_finish,omitempty"` // JOIN
|
||||
MaterialModifierID *int `json:"material_modifier_id,omitempty"`
|
||||
MaterialModifier *MaterialModifier `json:"material_modifier,omitempty"` // JOIN
|
||||
ColorHex string `json:"color_hex"`
|
||||
Brand *string `json:"brand,omitempty"`
|
||||
DiameterMM float64 `json:"diameter_mm"`
|
||||
InitialGrams int `json:"initial_grams"`
|
||||
RemainingGrams int `json:"remaining_grams"`
|
||||
SpoolWeightGrams *int `json:"spool_weight_grams,omitempty"`
|
||||
CostUSD *float64 `json:"cost_usd,omitempty"`
|
||||
LowStockThresholdGrams int `json:"low_stock_threshold_grams"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
Barcode *string `json:"barcode,omitempty"`
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// PrintJob represents a single print on a specific printer.
|
||||
// The filament_spool_id is a convenience reference; multi-spool jobs track usage in usage_logs.
|
||||
type PrintJob struct {
|
||||
ID int `json:"id"`
|
||||
PrinterID int `json:"printer_id"`
|
||||
Printer *Printer `json:"printer,omitempty"` // JOIN
|
||||
FilamentSpoolID *int `json:"filament_spool_id,omitempty"`
|
||||
FilamentSpool *FilamentSpool `json:"filament_spool,omitempty"` // JOIN
|
||||
JobName string `json:"job_name"`
|
||||
FileName *string `json:"file_name,omitempty"`
|
||||
JobStatusID int `json:"job_status_id"`
|
||||
JobStatus *JobStatus `json:"job_status,omitempty"` // JOIN
|
||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
DurationSeconds *int `json:"duration_seconds,omitempty"`
|
||||
EstimatedDurationSeconds *int `json:"estimated_duration_seconds,omitempty"`
|
||||
TotalMMExtruded *float64 `json:"total_mm_extruded,omitempty"`
|
||||
TotalGramsUsed *float64 `json:"total_grams_used,omitempty"`
|
||||
TotalCostUSD *float64 `json:"total_cost_usd,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// UsageLog records filament consumption for a specific spool during a print job.
|
||||
// This is the atomic unit of filament tracking — grams are derived from mm_extruded.
|
||||
type UsageLog struct {
|
||||
ID int `json:"id"`
|
||||
PrintJobID int `json:"print_job_id"`
|
||||
PrintJob *PrintJob `json:"print_job,omitempty"` // JOIN
|
||||
FilamentSpoolID int `json:"filament_spool_id"`
|
||||
FilamentSpool *FilamentSpool `json:"filament_spool,omitempty"` // JOIN
|
||||
MMExtruded float64 `json:"mm_extruded"`
|
||||
GramsUsed float64 `json:"grams_used"`
|
||||
CostUSD *float64 `json:"cost_usd,omitempty"`
|
||||
LoggedAt time.Time `json:"logged_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Application Settings
|
||||
// ============================================================================
|
||||
|
||||
// Setting represents a key-value application configuration entry.
|
||||
// The value is stored as JSONB in PostgreSQL, allowing flexible typed config.
|
||||
type Setting struct {
|
||||
ID int `json:"id"`
|
||||
Key string `json:"key"`
|
||||
Value []byte `json:"value"` // raw JSON — marshalled/unmarshalled by caller
|
||||
Description *string `json:"description,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
285
backend/internal/repositories/filament_repository.go
Normal file
285
backend/internal/repositories/filament_repository.go
Normal file
@@ -0,0 +1,285 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// FilamentRepository handles database queries for filament_spools.
|
||||
type FilamentRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewFilamentRepository creates a FilamentRepository backed by the given pool.
|
||||
func NewFilamentRepository(pool *pgxpool.Pool) *FilamentRepository {
|
||||
return &FilamentRepository{pool: pool}
|
||||
}
|
||||
|
||||
// FilamentFilter holds query parameters for listing filament spools.
|
||||
type FilamentFilter struct {
|
||||
Material string // filter by material_base name (case-insensitive)
|
||||
Finish string // filter by material_finish name (case-insensitive)
|
||||
Color string // filter by exact color_hex match
|
||||
LowStock bool // if true, filter for remaining_grams <= low_stock_threshold_grams
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// spoolScanFields is the common SELECT column list for filament spools with JOINs.
|
||||
const spoolScanFields = `
|
||||
s.id, s.name,
|
||||
s.material_base_id,
|
||||
COALESCE(mb.name, '') as material_base_name,
|
||||
COALESCE(mb.density_g_cm3, 0) as material_base_density_g_cm3,
|
||||
COALESCE(mb.extrusion_temp_min, NULL::int) as material_base_extrusion_temp_min,
|
||||
COALESCE(mb.extrusion_temp_max, NULL::int) as material_base_extrusion_temp_max,
|
||||
COALESCE(mb.bed_temp_min, NULL::int) as material_base_bed_temp_min,
|
||||
COALESCE(mb.bed_temp_max, NULL::int) as material_base_bed_temp_max,
|
||||
COALESCE(mb.created_at, s.created_at) as material_base_created_at,
|
||||
COALESCE(mb.updated_at, s.created_at) as material_base_updated_at,
|
||||
s.material_finish_id,
|
||||
COALESCE(mf.name, '') as material_finish_name,
|
||||
mf.description as material_finish_description,
|
||||
COALESCE(mf.created_at, s.created_at) as material_finish_created_at,
|
||||
COALESCE(mf.updated_at, s.created_at) as material_finish_updated_at,
|
||||
s.material_modifier_id,
|
||||
mm.name as material_modifier_name,
|
||||
mm.description as material_modifier_description,
|
||||
mm.created_at as material_modifier_created_at,
|
||||
mm.updated_at as material_modifier_updated_at,
|
||||
s.color_hex, s.brand, s.diameter_mm,
|
||||
s.initial_grams, s.remaining_grams, s.spool_weight_grams,
|
||||
s.cost_usd, s.low_stock_threshold_grams,
|
||||
s.notes, s.barcode,
|
||||
s.deleted_at, s.created_at, s.updated_at`
|
||||
|
||||
const spoolFromJoins = `
|
||||
FROM filament_spools s
|
||||
LEFT JOIN material_bases mb ON s.material_base_id = mb.id
|
||||
LEFT JOIN material_finishes mf ON s.material_finish_id = mf.id
|
||||
LEFT JOIN material_modifiers mm ON s.material_modifier_id = mm.id`
|
||||
|
||||
// scanSpoolWithJoins scans a full spool row including all JOINed tables.
|
||||
func scanSpoolWithJoins(row interface{ Scan(...interface{}) error }) (models.FilamentSpool, error) {
|
||||
var s models.FilamentSpool
|
||||
var mb models.MaterialBase
|
||||
var mf models.MaterialFinish
|
||||
var mfDesc *string
|
||||
var modifierID *int
|
||||
var modName, modDesc *string
|
||||
var modCreatedAt, modUpdatedAt *time.Time
|
||||
|
||||
err := row.Scan(
|
||||
&s.ID, &s.Name,
|
||||
&s.MaterialBaseID,
|
||||
&mb.Name, &mb.DensityGCm3,
|
||||
&mb.ExtrusionTempMin, &mb.ExtrusionTempMax,
|
||||
&mb.BedTempMin, &mb.BedTempMax,
|
||||
&mb.CreatedAt, &mb.UpdatedAt,
|
||||
&s.MaterialFinishID,
|
||||
&mf.Name, &mfDesc,
|
||||
&mf.CreatedAt, &mf.UpdatedAt,
|
||||
&modifierID,
|
||||
&modName, &modDesc,
|
||||
&modCreatedAt, &modUpdatedAt,
|
||||
&s.ColorHex, &s.Brand, &s.DiameterMM,
|
||||
&s.InitialGrams, &s.RemainingGrams, &s.SpoolWeightGrams,
|
||||
&s.CostUSD, &s.LowStockThresholdGrams,
|
||||
&s.Notes, &s.Barcode,
|
||||
&s.DeletedAt, &s.CreatedAt, &s.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
|
||||
mb.ID = s.MaterialBaseID
|
||||
s.MaterialBase = &mb
|
||||
|
||||
mf.ID = s.MaterialFinishID
|
||||
if mfDesc != nil {
|
||||
mf.Description = mfDesc
|
||||
}
|
||||
s.MaterialFinish = &mf
|
||||
|
||||
s.MaterialModifierID = modifierID
|
||||
if modifierID != nil && modName != nil {
|
||||
mm := models.MaterialModifier{
|
||||
ID: *modifierID,
|
||||
Name: *modName,
|
||||
}
|
||||
if modDesc != nil {
|
||||
mm.Description = modDesc
|
||||
}
|
||||
if modCreatedAt != nil {
|
||||
mm.CreatedAt = *modCreatedAt
|
||||
}
|
||||
if modUpdatedAt != nil {
|
||||
mm.UpdatedAt = *modUpdatedAt
|
||||
}
|
||||
s.MaterialModifier = &mm
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// GetAll returns filament spools matching the given filters, with pagination.
|
||||
// Returns results, total matching count, and any error.
|
||||
func (r *FilamentRepository) GetAll(ctx context.Context, filter FilamentFilter) ([]models.FilamentSpool, int, error) {
|
||||
conditions := []string{"s.deleted_at IS NULL"}
|
||||
args := []interface{}{}
|
||||
argIdx := 1
|
||||
|
||||
if filter.Material != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("LOWER(mb.name) = LOWER($%d)", argIdx))
|
||||
args = append(args, filter.Material)
|
||||
argIdx++
|
||||
}
|
||||
if filter.Finish != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("LOWER(mf.name) = LOWER($%d)", argIdx))
|
||||
args = append(args, filter.Finish)
|
||||
argIdx++
|
||||
}
|
||||
if filter.Color != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("s.color_hex = $%d", argIdx))
|
||||
args = append(args, filter.Color)
|
||||
argIdx++
|
||||
}
|
||||
if filter.LowStock {
|
||||
conditions = append(conditions, "s.remaining_grams <= s.low_stock_threshold_grams")
|
||||
}
|
||||
|
||||
whereClause := ""
|
||||
if len(conditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
|
||||
// Count total.
|
||||
var total int
|
||||
countQuery := "SELECT COUNT(*) " + spoolFromJoins + " " + whereClause
|
||||
if err := r.pool.QueryRow(ctx, countQuery, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Query with pagination.
|
||||
dataQuery := "SELECT " + spoolScanFields + " " + spoolFromJoins + " " +
|
||||
whereClause +
|
||||
" ORDER BY s.name ASC" +
|
||||
fmt.Sprintf(" LIMIT $%d OFFSET $%d", argIdx, argIdx+1)
|
||||
|
||||
dataArgs := make([]interface{}, len(args))
|
||||
copy(dataArgs, args)
|
||||
dataArgs = append(dataArgs, filter.Limit, filter.Offset)
|
||||
|
||||
rows, err := r.pool.Query(ctx, dataQuery, dataArgs...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var spools []models.FilamentSpool
|
||||
for rows.Next() {
|
||||
s, err := scanSpoolWithJoins(rows)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
spools = append(spools, s)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if spools == nil {
|
||||
spools = []models.FilamentSpool{}
|
||||
}
|
||||
|
||||
return spools, total, nil
|
||||
}
|
||||
|
||||
// GetByID returns a single filament spool by ID with JOINed data.
|
||||
// Returns nil if not found or soft-deleted.
|
||||
func (r *FilamentRepository) GetByID(ctx context.Context, id int) (*models.FilamentSpool, error) {
|
||||
query := "SELECT " + spoolScanFields + " " + spoolFromJoins +
|
||||
" WHERE s.id = $1 AND s.deleted_at IS NULL"
|
||||
|
||||
row := r.pool.QueryRow(ctx, query, id)
|
||||
s, err := scanSpoolWithJoins(row)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// Create inserts a new filament spool and returns the created spool with JOINed data.
|
||||
func (r *FilamentRepository) Create(ctx context.Context, spool *models.FilamentSpool) (*models.FilamentSpool, error) {
|
||||
var id int
|
||||
err := r.pool.QueryRow(ctx, `
|
||||
INSERT INTO filament_spools (
|
||||
name, material_base_id, material_finish_id, material_modifier_id,
|
||||
color_hex, brand, diameter_mm, initial_grams, remaining_grams,
|
||||
spool_weight_grams, cost_usd, low_stock_threshold_grams,
|
||||
notes, barcode
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
|
||||
RETURNING id
|
||||
`,
|
||||
spool.Name, spool.MaterialBaseID, spool.MaterialFinishID, spool.MaterialModifierID,
|
||||
spool.ColorHex, spool.Brand, spool.DiameterMM, spool.InitialGrams, spool.RemainingGrams,
|
||||
spool.SpoolWeightGrams, spool.CostUSD, spool.LowStockThresholdGrams,
|
||||
spool.Notes, spool.Barcode,
|
||||
).Scan(&id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return r.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// Update applies partial updates to an existing filament spool.
|
||||
// Only non-nil fields in the update map are applied.
|
||||
// Returns the updated spool.
|
||||
func (r *FilamentRepository) Update(ctx context.Context, id int, updates map[string]interface{}) (*models.FilamentSpool, error) {
|
||||
if len(updates) == 0 {
|
||||
return r.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
setClauses := []string{"updated_at = NOW()"}
|
||||
args := []interface{}{}
|
||||
argIdx := 1
|
||||
|
||||
for col, val := range updates {
|
||||
setClauses = append(setClauses, fmt.Sprintf("%s = $%d", col, argIdx))
|
||||
args = append(args, val)
|
||||
argIdx++
|
||||
}
|
||||
|
||||
args = append(args, id)
|
||||
query := fmt.Sprintf("UPDATE filament_spools SET %s WHERE id = $%d AND deleted_at IS NULL",
|
||||
strings.Join(setClauses, ", "), argIdx)
|
||||
|
||||
result, err := r.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return nil, nil // not found or deleted
|
||||
}
|
||||
|
||||
return r.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// SoftDelete marks a filament spool as deleted by setting deleted_at = NOW().
|
||||
// Returns true if a row was affected.
|
||||
func (r *FilamentRepository) SoftDelete(ctx context.Context, id int) (bool, error) {
|
||||
result, err := r.pool.Exec(ctx, `
|
||||
UPDATE filament_spools
|
||||
SET deleted_at = NOW(), updated_at = NOW()
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
`, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return result.RowsAffected() > 0, nil
|
||||
}
|
||||
50
backend/internal/repositories/material_finish_repository.go
Normal file
50
backend/internal/repositories/material_finish_repository.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// MaterialFinishRepository handles database queries for material finishes.
|
||||
type MaterialFinishRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewMaterialFinishRepository creates a MaterialFinishRepository backed by the given pool.
|
||||
func NewMaterialFinishRepository(pool *pgxpool.Pool) *MaterialFinishRepository {
|
||||
return &MaterialFinishRepository{pool: pool}
|
||||
}
|
||||
|
||||
// GetAll returns all material finishes ordered by name.
|
||||
func (r *MaterialFinishRepository) GetAll(ctx context.Context) ([]models.MaterialFinish, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT id, name, description, created_at, updated_at
|
||||
FROM material_finishes
|
||||
ORDER BY name
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var finishes []models.MaterialFinish
|
||||
for rows.Next() {
|
||||
var f models.MaterialFinish
|
||||
if err := rows.Scan(
|
||||
&f.ID, &f.Name, &f.Description,
|
||||
&f.CreatedAt, &f.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
finishes = append(finishes, f)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if finishes == nil {
|
||||
finishes = []models.MaterialFinish{}
|
||||
}
|
||||
return finishes, nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// MaterialModifierRepository handles database queries for material modifiers.
|
||||
type MaterialModifierRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewMaterialModifierRepository creates a MaterialModifierRepository backed by the given pool.
|
||||
func NewMaterialModifierRepository(pool *pgxpool.Pool) *MaterialModifierRepository {
|
||||
return &MaterialModifierRepository{pool: pool}
|
||||
}
|
||||
|
||||
// GetAll returns all material modifiers ordered by name.
|
||||
func (r *MaterialModifierRepository) GetAll(ctx context.Context) ([]models.MaterialModifier, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT id, name, description, created_at, updated_at
|
||||
FROM material_modifiers
|
||||
ORDER BY name
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var modifiers []models.MaterialModifier
|
||||
for rows.Next() {
|
||||
var m models.MaterialModifier
|
||||
if err := rows.Scan(
|
||||
&m.ID, &m.Name, &m.Description,
|
||||
&m.CreatedAt, &m.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
modifiers = append(modifiers, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if modifiers == nil {
|
||||
modifiers = []models.MaterialModifier{}
|
||||
}
|
||||
return modifiers, nil
|
||||
}
|
||||
54
backend/internal/repositories/material_repository.go
Normal file
54
backend/internal/repositories/material_repository.go
Normal file
@@ -0,0 +1,54 @@
|
||||
// Package repositories provides data access logic backed by PostgreSQL via pgxpool.
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// MaterialRepository handles database queries for material lookup tables.
|
||||
type MaterialRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewMaterialRepository creates a MaterialRepository backed by the given pool.
|
||||
func NewMaterialRepository(pool *pgxpool.Pool) *MaterialRepository {
|
||||
return &MaterialRepository{pool: pool}
|
||||
}
|
||||
|
||||
// GetAll returns all material bases ordered by name.
|
||||
func (r *MaterialRepository) GetAll(ctx context.Context) ([]models.MaterialBase, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT id, name, density_g_cm3, extrusion_temp_min, extrusion_temp_max,
|
||||
bed_temp_min, bed_temp_max, created_at, updated_at
|
||||
FROM material_bases
|
||||
ORDER BY name
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var materials []models.MaterialBase
|
||||
for rows.Next() {
|
||||
var m models.MaterialBase
|
||||
if err := rows.Scan(
|
||||
&m.ID, &m.Name, &m.DensityGCm3,
|
||||
&m.ExtrusionTempMin, &m.ExtrusionTempMax,
|
||||
&m.BedTempMin, &m.BedTempMax,
|
||||
&m.CreatedAt, &m.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
materials = append(materials, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if materials == nil {
|
||||
materials = []models.MaterialBase{}
|
||||
}
|
||||
return materials, nil
|
||||
}
|
||||
157
backend/internal/repositories/print_job_repository.go
Normal file
157
backend/internal/repositories/print_job_repository.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// PrintJobRepository handles database queries for print_jobs.
|
||||
type PrintJobRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewPrintJobRepository creates a PrintJobRepository backed by the given pool.
|
||||
func NewPrintJobRepository(pool *pgxpool.Pool) *PrintJobRepository {
|
||||
return &PrintJobRepository{pool: pool}
|
||||
}
|
||||
|
||||
// PrintJobFilter holds query parameters for listing print jobs.
|
||||
type PrintJobFilter struct {
|
||||
Status string // filter by job_status name (case-insensitive)
|
||||
PrinterID *int // filter by printer_id
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// scanPrintJobWithJoins scans a print_job row with JOINed tables.
|
||||
func (r *PrintJobRepository) scanPrintJobWithJoins(row interface{ Scan(...interface{}) error }) (models.PrintJob, error) {
|
||||
var pj models.PrintJob
|
||||
var js models.JobStatus
|
||||
|
||||
err := row.Scan(
|
||||
&pj.ID, &pj.PrinterID, &pj.FilamentSpoolID,
|
||||
&pj.JobName, &pj.FileName,
|
||||
&pj.JobStatusID,
|
||||
&pj.StartedAt, &pj.CompletedAt,
|
||||
&pj.DurationSeconds, &pj.EstimatedDurationSeconds,
|
||||
&pj.TotalMMExtruded, &pj.TotalGramsUsed, &pj.TotalCostUSD,
|
||||
&pj.Notes,
|
||||
&pj.DeletedAt, &pj.CreatedAt, &pj.UpdatedAt,
|
||||
&js.ID, &js.Name,
|
||||
&js.CreatedAt, &js.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return pj, err
|
||||
}
|
||||
|
||||
pj.JobStatus = &js
|
||||
return pj, nil
|
||||
}
|
||||
|
||||
// GetAll returns print jobs matching the given filters, with pagination.
|
||||
func (r *PrintJobRepository) GetAll(ctx context.Context, filter PrintJobFilter) ([]models.PrintJob, int, error) {
|
||||
conditions := []string{"pj.deleted_at IS NULL"}
|
||||
args := []interface{}{}
|
||||
argIdx := 1
|
||||
|
||||
if filter.Status != "" {
|
||||
conditions = append(conditions, fmt.Sprintf("LOWER(js.name) = LOWER($%d)", argIdx))
|
||||
args = append(args, filter.Status)
|
||||
argIdx++
|
||||
}
|
||||
if filter.PrinterID != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("pj.printer_id = $%d", argIdx))
|
||||
args = append(args, *filter.PrinterID)
|
||||
argIdx++
|
||||
}
|
||||
|
||||
whereClause := ""
|
||||
if len(conditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
|
||||
// Count.
|
||||
var total int
|
||||
countQuery := `SELECT COUNT(*)
|
||||
FROM print_jobs pj
|
||||
LEFT JOIN job_statuses js ON pj.job_status_id = js.id
|
||||
` + " " + whereClause
|
||||
if err := r.pool.QueryRow(ctx, countQuery, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Query with pagination.
|
||||
dataQuery := `SELECT
|
||||
pj.id, pj.printer_id, pj.filament_spool_id,
|
||||
pj.job_name, pj.file_name,
|
||||
pj.job_status_id,
|
||||
pj.started_at, pj.completed_at,
|
||||
pj.duration_seconds, pj.estimated_duration_seconds,
|
||||
pj.total_mm_extruded, pj.total_grams_used, pj.total_cost_usd,
|
||||
pj.notes,
|
||||
pj.deleted_at, pj.created_at, pj.updated_at,
|
||||
js.id, js.name,
|
||||
js.created_at, js.updated_at
|
||||
FROM print_jobs pj
|
||||
LEFT JOIN job_statuses js ON pj.job_status_id = js.id
|
||||
` + whereClause +
|
||||
" ORDER BY pj.created_at DESC" +
|
||||
fmt.Sprintf(" LIMIT $%d OFFSET $%d", argIdx, argIdx+1)
|
||||
|
||||
dataArgs := make([]interface{}, len(args))
|
||||
copy(dataArgs, args)
|
||||
dataArgs = append(dataArgs, filter.Limit, filter.Offset)
|
||||
|
||||
rows, err := r.pool.Query(ctx, dataQuery, dataArgs...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var jobs []models.PrintJob
|
||||
for rows.Next() {
|
||||
pj, err := r.scanPrintJobWithJoins(rows)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
jobs = append(jobs, pj)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if jobs == nil {
|
||||
jobs = []models.PrintJob{}
|
||||
}
|
||||
|
||||
return jobs, total, nil
|
||||
}
|
||||
|
||||
// GetByID returns a single print job by ID with JOINed job_status.
|
||||
func (r *PrintJobRepository) GetByID(ctx context.Context, id int) (*models.PrintJob, error) {
|
||||
row := r.pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
pj.id, pj.printer_id, pj.filament_spool_id,
|
||||
pj.job_name, pj.file_name,
|
||||
pj.job_status_id,
|
||||
pj.started_at, pj.completed_at,
|
||||
pj.duration_seconds, pj.estimated_duration_seconds,
|
||||
pj.total_mm_extruded, pj.total_grams_used, pj.total_cost_usd,
|
||||
pj.notes,
|
||||
pj.deleted_at, pj.created_at, pj.updated_at,
|
||||
js.id, js.name,
|
||||
js.created_at, js.updated_at
|
||||
FROM print_jobs pj
|
||||
LEFT JOIN job_statuses js ON pj.job_status_id = js.id
|
||||
WHERE pj.id = $1 AND pj.deleted_at IS NULL
|
||||
`, id)
|
||||
|
||||
pj, err := r.scanPrintJobWithJoins(row)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pj, nil
|
||||
}
|
||||
78
backend/internal/repositories/printer_repository.go
Normal file
78
backend/internal/repositories/printer_repository.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// PrinterRepository handles database queries for printers.
|
||||
type PrinterRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewPrinterRepository creates a PrinterRepository backed by the given pool.
|
||||
func NewPrinterRepository(pool *pgxpool.Pool) *PrinterRepository {
|
||||
return &PrinterRepository{pool: pool}
|
||||
}
|
||||
|
||||
// scanPrinterWithType scans a printer row with JOINed printer_type.
|
||||
func (r *PrinterRepository) scanPrinterWithType(row interface{ Scan(...interface{}) error }) (models.Printer, error) {
|
||||
var p models.Printer
|
||||
var pt models.PrinterType
|
||||
|
||||
err := row.Scan(
|
||||
&p.ID, &p.Name, &p.PrinterTypeID,
|
||||
&p.Manufacturer, &p.Model,
|
||||
&p.MoonrakerURL, &p.MoonrakerAPIKey,
|
||||
&p.MQTTBrokerHost, &p.MQTTTopicPrefix,
|
||||
&p.MQTTTLSEnabled, &p.IsActive,
|
||||
&p.CreatedAt, &p.UpdatedAt,
|
||||
&pt.ID, &pt.Name,
|
||||
&pt.CreatedAt, &pt.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
|
||||
p.PrinterType = &pt
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// GetAll returns all printers joined with their printer_type, ordered by name.
|
||||
func (r *PrinterRepository) GetAll(ctx context.Context) ([]models.Printer, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT p.id, p.name, p.printer_type_id,
|
||||
p.manufacturer, p.model,
|
||||
p.moonraker_url, p.moonraker_api_key,
|
||||
p.mqtt_broker_host, p.mqtt_topic_prefix,
|
||||
p.mqtt_tls_enabled, p.is_active,
|
||||
p.created_at, p.updated_at,
|
||||
pt.id, pt.name,
|
||||
pt.created_at, pt.updated_at
|
||||
FROM printers p
|
||||
JOIN printer_types pt ON p.printer_type_id = pt.id
|
||||
ORDER BY p.name
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var printers []models.Printer
|
||||
for rows.Next() {
|
||||
p, err := r.scanPrinterWithType(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
printers = append(printers, p)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if printers == nil {
|
||||
printers = []models.Printer{}
|
||||
}
|
||||
return printers, nil
|
||||
}
|
||||
96
backend/internal/repositories/usage_log_repository.go
Normal file
96
backend/internal/repositories/usage_log_repository.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// UsageLogRepository handles database queries for usage_logs.
|
||||
type UsageLogRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewUsageLogRepository creates a UsageLogRepository backed by the given pool.
|
||||
func NewUsageLogRepository(pool *pgxpool.Pool) *UsageLogRepository {
|
||||
return &UsageLogRepository{pool: pool}
|
||||
}
|
||||
|
||||
// UsageLogFilter holds query parameters for listing usage logs.
|
||||
type UsageLogFilter struct {
|
||||
SpoolID *int // filter by filament_spool_id
|
||||
JobID *int // filter by print_job_id
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// GetAll returns usage logs matching the given filters, with pagination.
|
||||
func (r *UsageLogRepository) GetAll(ctx context.Context, filter UsageLogFilter) ([]models.UsageLog, int, error) {
|
||||
conditions := []string{"1=1"}
|
||||
args := []interface{}{}
|
||||
argIdx := 1
|
||||
|
||||
if filter.SpoolID != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("ul.filament_spool_id = $%d", argIdx))
|
||||
args = append(args, *filter.SpoolID)
|
||||
argIdx++
|
||||
}
|
||||
if filter.JobID != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("ul.print_job_id = $%d", argIdx))
|
||||
args = append(args, *filter.JobID)
|
||||
argIdx++
|
||||
}
|
||||
|
||||
whereClause := "WHERE " + fmt.Sprintf("%s", conditions[0])
|
||||
for _, c := range conditions[1:] {
|
||||
whereClause += " AND " + c
|
||||
}
|
||||
|
||||
// Count.
|
||||
var total int
|
||||
countQuery := "SELECT COUNT(*) FROM usage_logs ul " + whereClause
|
||||
if err := r.pool.QueryRow(ctx, countQuery, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Query with pagination.
|
||||
dataQuery := `SELECT id, print_job_id, filament_spool_id, mm_extruded,
|
||||
grams_used, cost_usd, logged_at, created_at
|
||||
FROM usage_logs ul
|
||||
` + whereClause +
|
||||
" ORDER BY ul.logged_at DESC" +
|
||||
fmt.Sprintf(" LIMIT $%d OFFSET $%d", argIdx, argIdx+1)
|
||||
|
||||
dataArgs := make([]interface{}, len(args))
|
||||
copy(dataArgs, args)
|
||||
dataArgs = append(dataArgs, filter.Limit, filter.Offset)
|
||||
|
||||
rows, err := r.pool.Query(ctx, dataQuery, dataArgs...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var logs []models.UsageLog
|
||||
for rows.Next() {
|
||||
var l models.UsageLog
|
||||
if err := rows.Scan(
|
||||
&l.ID, &l.PrintJobID, &l.FilamentSpoolID,
|
||||
&l.MMExtruded, &l.GramsUsed, &l.CostUSD,
|
||||
&l.LoggedAt, &l.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
logs = append(logs, l)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if logs == nil {
|
||||
logs = []models.UsageLog{}
|
||||
}
|
||||
|
||||
return logs, total, nil
|
||||
}
|
||||
96
backend/internal/router/router.go
Normal file
96
backend/internal/router/router.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/config"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/handlers"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/services"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/sse"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// New creates and configures a Chi router with all middleware and handlers mounted.
|
||||
func New(cfg *config.Config, dbPool *pgxpool.Pool, sseBC *sse.Broadcaster) chi.Router {
|
||||
r := chi.NewRouter()
|
||||
|
||||
// Middleware
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Logger)
|
||||
r.Use(middleware.Recoverer)
|
||||
// Timeout middleware is applied per-route below to exclude SSE
|
||||
|
||||
// CORS
|
||||
r.Use(func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", cfg.CorsOrigin)
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
})
|
||||
|
||||
// Health check (with timeout)
|
||||
healthHandler := handlers.NewHealthHandler(dbPool)
|
||||
r.With(middleware.Timeout(30 * time.Second)).Get("/health", healthHandler.ServeHTTP)
|
||||
|
||||
// ── Repositories ──────────────────────────────────────────────────────
|
||||
materialRepo := repositories.NewMaterialRepository(dbPool)
|
||||
finishRepo := repositories.NewMaterialFinishRepository(dbPool)
|
||||
modifierRepo := repositories.NewMaterialModifierRepository(dbPool)
|
||||
filamentRepo := repositories.NewFilamentRepository(dbPool)
|
||||
printerRepo := repositories.NewPrinterRepository(dbPool)
|
||||
printJobRepo := repositories.NewPrintJobRepository(dbPool)
|
||||
usageLogRepo := repositories.NewUsageLogRepository(dbPool)
|
||||
|
||||
// ── Services ──────────────────────────────────────────────────────────
|
||||
filamentService := services.NewFilamentService(filamentRepo)
|
||||
printerService := services.NewPrinterService(printerRepo)
|
||||
printJobService := services.NewPrintJobService(printJobRepo)
|
||||
|
||||
// ── Handlers ──────────────────────────────────────────────────────────
|
||||
materialHandler := handlers.NewMaterialHandler(materialRepo)
|
||||
finishHandler := handlers.NewMaterialFinishHandler(finishRepo)
|
||||
modifierHandler := handlers.NewMaterialModifierHandler(modifierRepo)
|
||||
filamentHandler := handlers.NewFilamentHandler(filamentService)
|
||||
printerHandler := handlers.NewPrinterHandler(printerService)
|
||||
printJobHandler := handlers.NewPrintJobHandler(printJobService)
|
||||
usageLogHandler := handlers.NewUsageLogHandler(usageLogRepo)
|
||||
|
||||
// ── API Routes (with timeout) ─────────────────────────────────────────
|
||||
r.Route("/api", func(r chi.Router) {
|
||||
r.Use(middleware.Timeout(60 * time.Second))
|
||||
r.Get("/materials", materialHandler.List)
|
||||
r.Get("/finishes", finishHandler.List)
|
||||
r.Get("/modifiers", modifierHandler.List)
|
||||
|
||||
r.Route("/filaments", func(r chi.Router) {
|
||||
r.Get("/", filamentHandler.List)
|
||||
r.Post("/", filamentHandler.Create)
|
||||
r.Route("/{id}", func(r chi.Router) {
|
||||
r.Get("/", filamentHandler.Get)
|
||||
r.Put("/", filamentHandler.Update)
|
||||
r.Delete("/", filamentHandler.Delete)
|
||||
})
|
||||
})
|
||||
|
||||
r.Get("/printers", printerHandler.List)
|
||||
r.Get("/print-jobs", printJobHandler.List)
|
||||
r.Get("/usage-logs", usageLogHandler.List)
|
||||
|
||||
// SSE Events stream
|
||||
sseHandler := sse.NewHandler(sseBC)
|
||||
r.Get("/events", sseHandler.ServeHTTP)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
82
backend/internal/services/services.go
Normal file
82
backend/internal/services/services.go
Normal file
@@ -0,0 +1,82 @@
|
||||
// Package services contains business logic and application services.
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/repositories"
|
||||
)
|
||||
|
||||
// FilamentService wraps FilamentRepository with business logic and validation.
|
||||
type FilamentService struct {
|
||||
repo *repositories.FilamentRepository
|
||||
}
|
||||
|
||||
// NewFilamentService creates a FilamentService backed by the given repository.
|
||||
func NewFilamentService(repo *repositories.FilamentRepository) *FilamentService {
|
||||
return &FilamentService{repo: repo}
|
||||
}
|
||||
|
||||
// List returns paginated filament spools filtered by the given criteria.
|
||||
func (s *FilamentService) List(ctx context.Context, filter repositories.FilamentFilter) ([]models.FilamentSpool, int, error) {
|
||||
return s.repo.GetAll(ctx, filter)
|
||||
}
|
||||
|
||||
// GetByID returns a single filament spool by ID.
|
||||
func (s *FilamentService) GetByID(ctx context.Context, id int) (*models.FilamentSpool, error) {
|
||||
return s.repo.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// Create validates and creates a new filament spool.
|
||||
func (s *FilamentService) Create(ctx context.Context, spool *models.FilamentSpool) (*models.FilamentSpool, error) {
|
||||
if err := validateFilamentSpool(spool); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.Create(ctx, spool)
|
||||
}
|
||||
|
||||
// Update applies partial updates to a filament spool after validation.
|
||||
func (s *FilamentService) Update(ctx context.Context, id int, updates map[string]interface{}) (*models.FilamentSpool, error) {
|
||||
return s.repo.Update(ctx, id, updates)
|
||||
}
|
||||
|
||||
// SoftDelete marks a filament spool as deleted.
|
||||
func (s *FilamentService) SoftDelete(ctx context.Context, id int) (bool, error) {
|
||||
return s.repo.SoftDelete(ctx, id)
|
||||
}
|
||||
|
||||
// PrinterService wraps PrinterRepository.
|
||||
type PrinterService struct {
|
||||
repo *repositories.PrinterRepository
|
||||
}
|
||||
|
||||
// NewPrinterService creates a PrinterService backed by the given repository.
|
||||
func NewPrinterService(repo *repositories.PrinterRepository) *PrinterService {
|
||||
return &PrinterService{repo: repo}
|
||||
}
|
||||
|
||||
// List returns all printers.
|
||||
func (s *PrinterService) List(ctx context.Context) ([]models.Printer, error) {
|
||||
return s.repo.GetAll(ctx)
|
||||
}
|
||||
|
||||
// PrintJobService wraps PrintJobRepository.
|
||||
type PrintJobService struct {
|
||||
repo *repositories.PrintJobRepository
|
||||
}
|
||||
|
||||
// NewPrintJobService creates a PrintJobService backed by the given repository.
|
||||
func NewPrintJobService(repo *repositories.PrintJobRepository) *PrintJobService {
|
||||
return &PrintJobService{repo: repo}
|
||||
}
|
||||
|
||||
// List returns paginated print jobs filtered by the given criteria.
|
||||
func (s *PrintJobService) List(ctx context.Context, filter repositories.PrintJobFilter) ([]models.PrintJob, int, error) {
|
||||
return s.repo.GetAll(ctx, filter)
|
||||
}
|
||||
|
||||
// GetByID returns a single print job by ID.
|
||||
func (s *PrintJobService) GetByID(ctx context.Context, id int) (*models.PrintJob, error) {
|
||||
return s.repo.GetByID(ctx, id)
|
||||
}
|
||||
74
backend/internal/services/validation.go
Normal file
74
backend/internal/services/validation.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/dtos"
|
||||
"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
|
||||
)
|
||||
|
||||
// colorHexPattern validates hex color strings like #FF0000 or #ff0000.
|
||||
var colorHexPattern = regexp.MustCompile(`^#[0-9A-Fa-f]{6}$`)
|
||||
|
||||
// validateFilamentSpool performs validation on a FilamentSpool entity.
|
||||
// Returns a descriptive error on failure.
|
||||
func validateFilamentSpool(s *models.FilamentSpool) error {
|
||||
if s.Name == "" {
|
||||
return errors.New("name is required")
|
||||
}
|
||||
if s.MaterialBaseID <= 0 {
|
||||
return errors.New("material_base_id is required")
|
||||
}
|
||||
if s.MaterialFinishID <= 0 {
|
||||
return errors.New("material_finish_id is required")
|
||||
}
|
||||
if !colorHexPattern.MatchString(s.ColorHex) {
|
||||
return fmt.Errorf("color_hex must be a valid hex color (e.g., #FF0000)")
|
||||
}
|
||||
if s.InitialGrams <= 0 {
|
||||
return errors.New("initial_grams must be greater than 0")
|
||||
}
|
||||
if s.RemainingGrams < 0 {
|
||||
return errors.New("remaining_grams must be >= 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCreateFilamentRequest validates a creation DTO.
|
||||
func ValidateCreateFilamentRequest(req dtos.CreateFilamentRequest) error {
|
||||
if req.Name == "" {
|
||||
return errors.New("name is required")
|
||||
}
|
||||
if req.MaterialBaseID <= 0 {
|
||||
return errors.New("material_base_id is required")
|
||||
}
|
||||
if req.MaterialFinishID <= 0 {
|
||||
return errors.New("material_finish_id is required")
|
||||
}
|
||||
if !colorHexPattern.MatchString(req.ColorHex) {
|
||||
return fmt.Errorf("color_hex must be a valid hex color (e.g., #FF0000)")
|
||||
}
|
||||
if req.InitialGrams <= 0 {
|
||||
return errors.New("initial_grams must be greater than 0")
|
||||
}
|
||||
if req.RemainingGrams < 0 {
|
||||
return errors.New("remaining_grams must be >= 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateUpdateFilamentRequest validates partial update fields.
|
||||
func ValidateUpdateFilamentRequest(req dtos.UpdateFilamentRequest) error {
|
||||
if req.ColorHex != nil && !colorHexPattern.MatchString(*req.ColorHex) {
|
||||
return fmt.Errorf("color_hex must be a valid hex color (e.g., #FF0000)")
|
||||
}
|
||||
if req.InitialGrams != nil && *req.InitialGrams <= 0 {
|
||||
return errors.New("initial_grams must be greater than 0")
|
||||
}
|
||||
if req.RemainingGrams != nil && *req.RemainingGrams < 0 {
|
||||
return errors.New("remaining_grams must be >= 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
133
backend/internal/sse/broadcaster.go
Normal file
133
backend/internal/sse/broadcaster.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package sse
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// client represents a single SSE subscriber — identified by its send channel.
|
||||
type client struct {
|
||||
ch chan string
|
||||
}
|
||||
|
||||
// Broadcaster receives Events on its input channel and fans them out to every
|
||||
// connected client. Subscribe adds a new client; Unsubscribe removes one.
|
||||
// Start must be called before the broadcaster accepts events.
|
||||
type Broadcaster struct {
|
||||
input chan Event
|
||||
subscribe chan client
|
||||
unsubscribe chan client
|
||||
clients map[chan string]struct{}
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// NewBroadcaster creates a Broadcaster. bufSize controls the buffer depth for
|
||||
// the input channel as well as for each per-client outbound channel.
|
||||
func NewBroadcaster(bufSize int) *Broadcaster {
|
||||
if bufSize <= 0 {
|
||||
bufSize = 64
|
||||
}
|
||||
return &Broadcaster{
|
||||
input: make(chan Event, bufSize),
|
||||
subscribe: make(chan client),
|
||||
unsubscribe: make(chan client),
|
||||
clients: make(map[chan string]struct{}),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Publish pushes an event into the broadcaster. Safe for concurrent use.
|
||||
func (b *Broadcaster) Publish(ev Event) {
|
||||
select {
|
||||
case b.input <- ev:
|
||||
case <-b.done:
|
||||
// Silently drop during shutdown.
|
||||
}
|
||||
}
|
||||
|
||||
// Start launches the broadcaster's fan-out loop in a goroutine.
|
||||
// It must be called before Publish is used.
|
||||
func (b *Broadcaster) Start() {
|
||||
go b.loop()
|
||||
}
|
||||
|
||||
// Stop terminates the fan-out loop and closes all client channels.
|
||||
// It is safe to call multiple times.
|
||||
func (b *Broadcaster) Stop() {
|
||||
b.once.Do(func() {
|
||||
close(b.done)
|
||||
})
|
||||
}
|
||||
|
||||
// Subscribe returns a new client channel that receives SSE-formatted strings.
|
||||
func (b *Broadcaster) Subscribe() chan string {
|
||||
c := client{ch: make(chan string, 64)}
|
||||
select {
|
||||
case b.subscribe <- c:
|
||||
case <-b.done:
|
||||
// Broadcaster already stopped — return a closed chan so the handler
|
||||
// can bail out quickly.
|
||||
ch := make(chan string)
|
||||
close(ch)
|
||||
return ch
|
||||
}
|
||||
return c.ch
|
||||
}
|
||||
|
||||
// Unsubscribe removes a client channel and closes it.
|
||||
func (b *Broadcaster) Unsubscribe(ch chan string) {
|
||||
c := client{ch: ch}
|
||||
select {
|
||||
case b.unsubscribe <- c:
|
||||
case <-b.done:
|
||||
// Already shutting down — channels will be cleaned up by Stop.
|
||||
}
|
||||
}
|
||||
|
||||
// loop is the core fan-out goroutine.
|
||||
func (b *Broadcaster) loop() {
|
||||
for {
|
||||
select {
|
||||
case ev := <-b.input:
|
||||
sse := ev.toSSE()
|
||||
for ch := range b.clients {
|
||||
// Non-blocking send — slow clients are dropped.
|
||||
select {
|
||||
case ch <- sse:
|
||||
default:
|
||||
slog.Warn("sse broadcaster: dropping event for slow client", "type", ev.Type)
|
||||
}
|
||||
}
|
||||
|
||||
case c := <-b.subscribe:
|
||||
b.clients[c.ch] = struct{}{}
|
||||
slog.Debug("sse broadcaster: client connected", "total_clients", len(b.clients))
|
||||
|
||||
case c := <-b.unsubscribe:
|
||||
if _, ok := b.clients[c.ch]; ok {
|
||||
delete(b.clients, c.ch)
|
||||
close(c.ch)
|
||||
slog.Debug("sse broadcaster: client disconnected", "total_clients", len(b.clients))
|
||||
}
|
||||
|
||||
case <-b.done:
|
||||
// Drain remaining events in input before shutting down.
|
||||
for ev := range b.input {
|
||||
sse := ev.toSSE()
|
||||
for ch := range b.clients {
|
||||
select {
|
||||
case ch <- sse:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
// Close all remaining client channels.
|
||||
for ch := range b.clients {
|
||||
close(ch)
|
||||
}
|
||||
b.clients = nil
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
92
backend/internal/sse/events.go
Normal file
92
backend/internal/sse/events.go
Normal file
@@ -0,0 +1,92 @@
|
||||
// Package sse provides Server-Sent Events infrastructure for real-time updates.
|
||||
// Includes event types, a central broadcaster, and an HTTP handler.
|
||||
package sse
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// EventType identifies the category of an SSE event.
|
||||
type EventType string
|
||||
|
||||
const (
|
||||
EventPrinterStatus EventType = "printer.status"
|
||||
EventJobStarted EventType = "job.started"
|
||||
EventJobCompleted EventType = "job.completed"
|
||||
EventFilamentLow EventType = "filament.low"
|
||||
)
|
||||
|
||||
// Event is a JSON-serializable SSE event pushed through the broadcaster.
|
||||
type Event struct {
|
||||
Type EventType `json:"type"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// PrinterStatusPayload carries printer online/offline/printing state.
|
||||
type PrinterStatusPayload struct {
|
||||
PrinterID int `json:"printer_id"`
|
||||
PrinterName string `json:"printer_name"`
|
||||
Status string `json:"status"` // "online", "offline", "printing"
|
||||
}
|
||||
|
||||
// JobStartedPayload carries initial print job info.
|
||||
type JobStartedPayload struct {
|
||||
JobID int `json:"job_id"`
|
||||
JobName string `json:"job_name"`
|
||||
PrinterID int `json:"printer_id"`
|
||||
SpoolID *int `json:"spool_id,omitempty"`
|
||||
}
|
||||
|
||||
// JobCompletedPayload carries final print job data including usage.
|
||||
type JobCompletedPayload struct {
|
||||
JobID int `json:"job_id"`
|
||||
JobName string `json:"job_name"`
|
||||
PrinterID int `json:"printer_id"`
|
||||
DurationSeconds *int `json:"duration_seconds,omitempty"`
|
||||
TotalGramsUsed *float64 `json:"total_grams_used,omitempty"`
|
||||
TotalCostUSD *float64 `json:"total_cost_usd,omitempty"`
|
||||
}
|
||||
|
||||
// FilamentLowPayload alerts that a spool is below its threshold.
|
||||
type FilamentLowPayload struct {
|
||||
SpoolID int `json:"spool_id"`
|
||||
SpoolName string `json:"spool_name"`
|
||||
RemainingGrams int `json:"remaining_grams"`
|
||||
ThresholdGrams int `json:"threshold_grams"`
|
||||
}
|
||||
|
||||
// NewEvent creates an Event with the current timestamp from a typed payload.
|
||||
func NewEvent(eventType EventType, payload any) (Event, error) {
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
return Event{
|
||||
Type: eventType,
|
||||
Payload: raw,
|
||||
Timestamp: time.Now().UTC(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MustEvent creates an Event and panics on marshal failure (for use with
|
||||
// known-good payloads in tests and internal wiring).
|
||||
func MustEvent(eventType EventType, payload any) Event {
|
||||
ev, err := NewEvent(eventType, payload)
|
||||
if err != nil {
|
||||
panic("sse.MustEvent: failed to marshal payload: " + err.Error())
|
||||
}
|
||||
return ev
|
||||
}
|
||||
|
||||
// toSSE formats this Event as a standard SSE message string ready to be
|
||||
// written to a response writer. The format is:
|
||||
//
|
||||
// event: <type>
|
||||
// data: <json>
|
||||
//
|
||||
func (e Event) toSSE() string {
|
||||
data, _ := json.Marshal(e)
|
||||
return "event: " + string(e.Type) + "\n" + "data: " + string(data) + "\n\n"
|
||||
}
|
||||
59
backend/internal/sse/handler.go
Normal file
59
backend/internal/sse/handler.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package sse
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Handler is the HTTP handler for the GET /api/events SSE stream.
|
||||
// It registers a client with the broadcaster, streams events as they arrive,
|
||||
// and unregisters on disconnect.
|
||||
type Handler struct {
|
||||
bc *Broadcaster
|
||||
}
|
||||
|
||||
// NewHandler creates a Handler backed by the given Broadcaster.
|
||||
func NewHandler(bc *Broadcaster) *Handler {
|
||||
return &Handler{bc: bc}
|
||||
}
|
||||
|
||||
// ServeHTTP implements the SSE streaming endpoint.
|
||||
// Flusher is required; clients that do not support flushing receive a 501.
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming not supported", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
// SSE-specific headers
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("X-Accel-Buffering", "no") // Disable nginx buffering
|
||||
|
||||
// Write headers immediately
|
||||
flusher.Flush()
|
||||
|
||||
// Subscribe to the broadcaster
|
||||
ch := h.bc.Subscribe()
|
||||
defer h.bc.Unsubscribe(ch)
|
||||
|
||||
// Use request context for cancellation when the client disconnects.
|
||||
ctx := r.Context()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case msg, ok := <-ch:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
_, err := w.Write([]byte(msg))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
19
backend/migrations/000001_initial_schema.down.sql
Normal file
19
backend/migrations/000001_initial_schema.down.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
-- Migration: 000001_initial_schema (rollback)
|
||||
-- Description: Drop all tables and indexes created in the initial schema migration
|
||||
-- Author: Hex
|
||||
-- Date: 2026-05-06
|
||||
|
||||
BEGIN;
|
||||
|
||||
DROP TABLE IF EXISTS usage_logs CASCADE;
|
||||
DROP TABLE IF EXISTS print_jobs CASCADE;
|
||||
DROP TABLE IF EXISTS filament_spools CASCADE;
|
||||
DROP TABLE IF EXISTS printers CASCADE;
|
||||
DROP TABLE IF EXISTS settings CASCADE;
|
||||
DROP TABLE IF EXISTS material_modifiers CASCADE;
|
||||
DROP TABLE IF EXISTS material_finishes CASCADE;
|
||||
DROP TABLE IF EXISTS material_bases CASCADE;
|
||||
DROP TABLE IF EXISTS job_statuses CASCADE;
|
||||
DROP TABLE IF EXISTS printer_types CASCADE;
|
||||
|
||||
COMMIT;
|
||||
231
backend/migrations/000001_initial_schema.up.sql
Normal file
231
backend/migrations/000001_initial_schema.up.sql
Normal file
@@ -0,0 +1,231 @@
|
||||
-- Migration: 000001_initial_schema
|
||||
-- Description: Create initial Extrudex schema — lookup tables, core entities, and settings
|
||||
-- Author: Hex
|
||||
-- Date: 2026-05-06
|
||||
--
|
||||
-- Design decisions:
|
||||
-- - Lookup tables for material_base, material_finish, material_modifier (no free-text enums)
|
||||
-- - Lookup tables for printer_type and job_status (extensible, no hard-coded enum values)
|
||||
-- - FK ON DELETE: RESTRICT on critical parents (material_base, material_finish, printer),
|
||||
-- SET NULL on optional parents (modifier, spool on print_jobs),
|
||||
-- CASCADE for usage_logs when parent job is deleted
|
||||
-- - Soft-delete (deleted_at) on spools and print_jobs for safety
|
||||
-- - JSONB config column on settings for flexible app-wide configuration
|
||||
-- - All identifiers snake_case per project convention
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- ============================================================================
|
||||
-- Lookup Tables
|
||||
-- ============================================================================
|
||||
|
||||
-- Printer types (fdm, resin, etc.) — extensible, not a raw enum
|
||||
CREATE TABLE printer_types (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(50) NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Job statuses (pending, printing, paused, completed, failed, cancelled)
|
||||
CREATE TABLE job_statuses (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(50) NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Material base types (PLA, PETG, ABS, TPU, ASA, Nylon, PC)
|
||||
CREATE TABLE material_bases (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL UNIQUE,
|
||||
density_g_cm3 DECIMAL(5,3) NOT NULL,
|
||||
extrusion_temp_min INT,
|
||||
extrusion_temp_max INT,
|
||||
bed_temp_min INT,
|
||||
bed_temp_max INT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Material finishes (Basic, Silk, Matte, Glossy, Satin)
|
||||
CREATE TABLE material_finishes (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL UNIQUE,
|
||||
description TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Material modifiers (Wood-Filled, Carbon Fiber, Glow-in-Dark, Marble)
|
||||
CREATE TABLE material_modifiers (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL UNIQUE,
|
||||
description TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- ============================================================================
|
||||
-- Core Entity Tables
|
||||
-- ============================================================================
|
||||
|
||||
-- 3D printers in the fleet
|
||||
CREATE TABLE printers (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
printer_type_id INT NOT NULL,
|
||||
manufacturer VARCHAR(255),
|
||||
model VARCHAR(255),
|
||||
moonraker_url VARCHAR(512),
|
||||
moonraker_api_key VARCHAR(512),
|
||||
mqtt_broker_host VARCHAR(255),
|
||||
mqtt_topic_prefix VARCHAR(255),
|
||||
mqtt_tls_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT fk_printers_printer_type
|
||||
FOREIGN KEY (printer_type_id) REFERENCES printer_types(id)
|
||||
ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
-- Filament spools — the core inventory item
|
||||
CREATE TABLE filament_spools (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
material_base_id INT NOT NULL,
|
||||
material_finish_id INT NOT NULL DEFAULT 1, -- "Basic" (seed data populates this first)
|
||||
material_modifier_id INT,
|
||||
color_hex VARCHAR(7) NOT NULL CHECK (color_hex ~ '^#[0-9A-Fa-f]{6}$'),
|
||||
brand VARCHAR(255),
|
||||
diameter_mm DECIMAL(4,2) NOT NULL DEFAULT 1.75,
|
||||
initial_grams INT NOT NULL CHECK (initial_grams > 0),
|
||||
remaining_grams INT NOT NULL CHECK (remaining_grams >= 0),
|
||||
spool_weight_grams INT, -- measured empty-spool weight (tare), nullable
|
||||
cost_usd DECIMAL(10,2),
|
||||
low_stock_threshold_grams INT NOT NULL DEFAULT 50,
|
||||
notes TEXT,
|
||||
barcode VARCHAR(255) UNIQUE,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT fk_spools_material_base
|
||||
FOREIGN KEY (material_base_id) REFERENCES material_bases(id)
|
||||
ON DELETE RESTRICT,
|
||||
|
||||
CONSTRAINT fk_spools_material_finish
|
||||
FOREIGN KEY (material_finish_id) REFERENCES material_finishes(id)
|
||||
ON DELETE RESTRICT,
|
||||
|
||||
CONSTRAINT fk_spools_material_modifier
|
||||
FOREIGN KEY (material_modifier_id) REFERENCES material_modifiers(id)
|
||||
ON DELETE SET NULL
|
||||
);
|
||||
|
||||
-- Print jobs — each job is one print on one printer
|
||||
CREATE TABLE print_jobs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
printer_id INT NOT NULL,
|
||||
filament_spool_id INT, -- nullable: a job may use multiple spools (captured in usage_logs)
|
||||
job_name VARCHAR(255) NOT NULL,
|
||||
file_name VARCHAR(512),
|
||||
job_status_id INT NOT NULL DEFAULT 1, -- "pending"
|
||||
started_at TIMESTAMPTZ,
|
||||
completed_at TIMESTAMPTZ,
|
||||
duration_seconds INT,
|
||||
estimated_duration_seconds INT,
|
||||
total_mm_extruded DECIMAL(12,2),
|
||||
total_grams_used DECIMAL(10,2),
|
||||
total_cost_usd DECIMAL(10,4),
|
||||
notes TEXT,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT fk_print_jobs_printer
|
||||
FOREIGN KEY (printer_id) REFERENCES printers(id)
|
||||
ON DELETE RESTRICT,
|
||||
|
||||
CONSTRAINT fk_print_jobs_spool
|
||||
FOREIGN KEY (filament_spool_id) REFERENCES filament_spools(id)
|
||||
ON DELETE SET NULL,
|
||||
|
||||
CONSTRAINT fk_print_jobs_status
|
||||
FOREIGN KEY (job_status_id) REFERENCES job_statuses(id)
|
||||
ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
-- Usage logs — granular tracking of filament consumed per job, per spool
|
||||
CREATE TABLE usage_logs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
print_job_id INT NOT NULL,
|
||||
filament_spool_id INT NOT NULL,
|
||||
mm_extruded DECIMAL(12,2) NOT NULL CHECK (mm_extruded > 0),
|
||||
grams_used DECIMAL(10,2) NOT NULL CHECK (grams_used > 0),
|
||||
cost_usd DECIMAL(10,4),
|
||||
logged_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT fk_usage_logs_print_job
|
||||
FOREIGN KEY (print_job_id) REFERENCES print_jobs(id)
|
||||
ON DELETE CASCADE,
|
||||
|
||||
CONSTRAINT fk_usage_logs_spool
|
||||
FOREIGN KEY (filament_spool_id) REFERENCES filament_spools(id)
|
||||
ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
-- ============================================================================
|
||||
-- Application Settings
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE settings (
|
||||
id SERIAL PRIMARY KEY,
|
||||
key VARCHAR(255) NOT NULL UNIQUE,
|
||||
value JSONB NOT NULL,
|
||||
description TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- ============================================================================
|
||||
-- Indexes
|
||||
-- ============================================================================
|
||||
|
||||
-- Filament spools — query patterns: lookup by material, low-stock scans, barcode scans
|
||||
CREATE INDEX ix_spools_material_base_id ON filament_spools(material_base_id);
|
||||
CREATE INDEX ix_spools_material_finish_id ON filament_spools(material_finish_id);
|
||||
CREATE INDEX ix_spools_material_modifier_id ON filament_spools(material_modifier_id);
|
||||
CREATE INDEX ix_spools_remaining_grams ON filament_spools(remaining_grams)
|
||||
WHERE deleted_at IS NULL; -- partial index: only active spools for low-stock queries
|
||||
CREATE INDEX ix_spools_barcode ON filament_spools(barcode)
|
||||
WHERE barcode IS NOT NULL AND deleted_at IS NULL;
|
||||
CREATE INDEX ix_spools_deleted_at ON filament_spools(deleted_at)
|
||||
WHERE deleted_at IS NOT NULL; -- small index for soft-delete filtering
|
||||
|
||||
-- Printers
|
||||
CREATE INDEX ix_printers_printer_type_id ON printers(printer_type_id);
|
||||
CREATE INDEX ix_printers_is_active ON printers(is_active)
|
||||
WHERE is_active = TRUE; -- partial index for fleet dashboard queries
|
||||
|
||||
-- Print jobs — query by printer, status, date range, and soft-delete filter
|
||||
CREATE INDEX ix_print_jobs_printer_id ON print_jobs(printer_id);
|
||||
CREATE INDEX ix_print_jobs_spool_id ON print_jobs(filament_spool_id)
|
||||
WHERE filament_spool_id IS NOT NULL;
|
||||
CREATE INDEX ix_print_jobs_status_id ON print_jobs(job_status_id);
|
||||
CREATE INDEX ix_print_jobs_created_at ON print_jobs(created_at DESC);
|
||||
CREATE INDEX ix_print_jobs_deleted_at ON print_jobs(deleted_at)
|
||||
WHERE deleted_at IS NOT NULL;
|
||||
|
||||
-- Usage logs — always queried by job or spool
|
||||
CREATE INDEX ix_usage_logs_print_job_id ON usage_logs(print_job_id);
|
||||
CREATE INDEX ix_usage_logs_spool_id ON usage_logs(filament_spool_id);
|
||||
CREATE INDEX ix_usage_logs_logged_at ON usage_logs(logged_at DESC);
|
||||
|
||||
-- Settings — key lookups
|
||||
CREATE INDEX ix_settings_key ON settings(key);
|
||||
|
||||
COMMIT;
|
||||
15
backend/migrations/000002_seed_data.down.sql
Normal file
15
backend/migrations/000002_seed_data.down.sql
Normal file
@@ -0,0 +1,15 @@
|
||||
-- Migration: 000002_seed_data (rollback)
|
||||
-- Description: Remove seed data inserted in 000002
|
||||
-- Author: Hex
|
||||
-- Date: 2026-05-06
|
||||
|
||||
BEGIN;
|
||||
|
||||
DELETE FROM settings WHERE key IN ('default_low_stock_threshold_grams', 'default_diameter_mm', 'filament_cross_section_area_mm2');
|
||||
DELETE FROM material_modifiers WHERE id IN (1, 2, 3, 4);
|
||||
DELETE FROM material_finishes WHERE id IN (1, 2, 3, 4, 5);
|
||||
DELETE FROM material_bases WHERE id IN (1, 2, 3, 4, 5, 6, 7);
|
||||
DELETE FROM job_statuses WHERE id IN (1, 2, 3, 4, 5, 6);
|
||||
DELETE FROM printer_types WHERE id IN (1, 2);
|
||||
|
||||
COMMIT;
|
||||
95
backend/migrations/000002_seed_data.up.sql
Normal file
95
backend/migrations/000002_seed_data.up.sql
Normal file
@@ -0,0 +1,95 @@
|
||||
-- Seed Data: Extrudex common reference data
|
||||
-- Author: Hex
|
||||
-- Date: 2026-05-06
|
||||
--
|
||||
-- IMPORTANT: IDs are explicitly assigned to satisfy the DEFAULT constraints:
|
||||
-- - filament_spools.material_finish_id DEFAULT 1 ("Basic")
|
||||
-- - print_jobs.job_status_id DEFAULT 1 ("pending")
|
||||
--
|
||||
-- Density values sourced from common manufacturer specifications.
|
||||
-- Temperature ranges are conservative/typical; users can override per-spool.
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- ============================================================================
|
||||
-- Printer Types
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO printer_types (id, name) VALUES
|
||||
(1, 'fdm'),
|
||||
(2, 'resin')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Reset the sequence so future inserts start after our explicit IDs
|
||||
SELECT setval('printer_types_id_seq', GREATEST(2, (SELECT MAX(id) FROM printer_types)));
|
||||
|
||||
-- ============================================================================
|
||||
-- Job Statuses
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO job_statuses (id, name) VALUES
|
||||
(1, 'pending'),
|
||||
(2, 'printing'),
|
||||
(3, 'paused'),
|
||||
(4, 'completed'),
|
||||
(5, 'failed'),
|
||||
(6, 'cancelled')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT setval('job_statuses_id_seq', GREATEST(6, (SELECT MAX(id) FROM job_statuses)));
|
||||
|
||||
-- ============================================================================
|
||||
-- Material Bases (common filament types)
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO material_bases (id, name, density_g_cm3, extrusion_temp_min, extrusion_temp_max, bed_temp_min, bed_temp_max) VALUES
|
||||
(1, 'PLA', 1.24, 190, 220, 0, 60),
|
||||
(2, 'PETG', 1.27, 230, 250, 70, 90),
|
||||
(3, 'ABS', 1.04, 230, 260, 90, 110),
|
||||
(4, 'TPU', 1.21, 220, 250, 0, 60),
|
||||
(5, 'ASA', 1.07, 240, 260, 90, 110),
|
||||
(6, 'Nylon', 1.14, 240, 280, 70, 100),
|
||||
(7, 'PC', 1.20, 260, 310, 90, 120)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT setval('material_bases_id_seq', GREATEST(7, (SELECT MAX(id) FROM material_bases)));
|
||||
|
||||
-- ============================================================================
|
||||
-- Material Finishes
|
||||
-- ============================================================================
|
||||
-- ID 1 = "Basic" is the default for new spools (DEFAULT 1 constraint)
|
||||
|
||||
INSERT INTO material_finishes (id, name, description) VALUES
|
||||
(1, 'Basic', 'Standard solid-color filament with no special finish'),
|
||||
(2, 'Silk', 'Glossy silk-like sheen, often used for decorative prints'),
|
||||
(3, 'Matte', 'Flat non-reflective surface finish'),
|
||||
(4, 'Glossy', 'High-shine reflective surface'),
|
||||
(5, 'Satin', 'Semi-gloss between matte and glossy')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT setval('material_finishes_id_seq', GREATEST(5, (SELECT MAX(id) FROM material_finishes)));
|
||||
|
||||
-- ============================================================================
|
||||
-- Material Modifiers
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO material_modifiers (id, name, description) VALUES
|
||||
(1, 'Wood-Filled', 'Contains wood fibers for natural wood-like appearance and texture'),
|
||||
(2, 'Carbon Fiber', 'Reinforced with carbon fibers for increased stiffness and strength'),
|
||||
(3, 'Glow-in-Dark', 'Phosphorescent additive that glows after exposure to light'),
|
||||
(4, 'Marble', 'Contains specks for a stone-like marble appearance')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT setval('material_modifiers_id_seq', GREATEST(4, (SELECT MAX(id) FROM material_modifiers)));
|
||||
|
||||
-- ============================================================================
|
||||
-- Default Application Settings
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO settings (key, value, description) VALUES
|
||||
('default_low_stock_threshold_grams', '50', 'Default grams threshold for low-stock alerts on new spools'),
|
||||
('default_diameter_mm', '1.75', 'Default filament diameter for new spools (1.75mm is the modern standard)'),
|
||||
('filament_cross_section_area_mm2', '2.405', 'Cross-sectional area for 1.75mm filament: π × (1.75/2)²')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
COMMIT;
|
||||
@@ -1,11 +0,0 @@
|
||||
node_modules
|
||||
dist
|
||||
.git
|
||||
.gitignore
|
||||
.angular
|
||||
.vscode
|
||||
*.md
|
||||
.editorconfig
|
||||
.prettierrc
|
||||
src/test.ts
|
||||
**/*.spec.ts
|
||||
@@ -1,17 +0,0 @@
|
||||
# Editor configuration, see https://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.ts]
|
||||
quote_type = single
|
||||
ij_typescript_use_double_quotes = false
|
||||
|
||||
[*.md]
|
||||
max_line_length = off
|
||||
trim_trailing_whitespace = false
|
||||
44
frontend/.gitignore
vendored
44
frontend/.gitignore
vendored
@@ -1,44 +0,0 @@
|
||||
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
|
||||
|
||||
# Compiled output
|
||||
/dist
|
||||
/tmp
|
||||
/out-tsc
|
||||
/bazel-out
|
||||
|
||||
# Node
|
||||
/node_modules
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
|
||||
# IDEs and editors
|
||||
.idea/
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# Visual Studio Code
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/mcp.json
|
||||
.history/*
|
||||
|
||||
# Miscellaneous
|
||||
/.angular/cache
|
||||
.sass-cache/
|
||||
/connect.lock
|
||||
/coverage
|
||||
/libpeerconnection.log
|
||||
testem.log
|
||||
/typings
|
||||
__screenshots__/
|
||||
|
||||
# System files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"singleQuote": true,
|
||||
"overrides": [
|
||||
{
|
||||
"files": "*.html",
|
||||
"options": {
|
||||
"parser": "angular"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
4
frontend/.vscode/extensions.json
vendored
4
frontend/.vscode/extensions.json
vendored
@@ -1,4 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
|
||||
"recommendations": ["angular.ng-template"]
|
||||
}
|
||||
20
frontend/.vscode/launch.json
vendored
20
frontend/.vscode/launch.json
vendored
@@ -1,20 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "ng serve",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: start",
|
||||
"url": "http://localhost:4200/"
|
||||
},
|
||||
{
|
||||
"name": "ng test",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: test",
|
||||
"url": "http://localhost:9876/debug.html"
|
||||
}
|
||||
]
|
||||
}
|
||||
9
frontend/.vscode/mcp.json
vendored
9
frontend/.vscode/mcp.json
vendored
@@ -1,9 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://angular.dev/ai/mcp
|
||||
"servers": {
|
||||
"angular-cli": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@angular/cli", "mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
42
frontend/.vscode/tasks.json
vendored
42
frontend/.vscode/tasks.json
vendored
@@ -1,42 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "start",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"owner": "typescript",
|
||||
"pattern": "$tsc",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": {
|
||||
"regexp": "Changes detected"
|
||||
},
|
||||
"endsPattern": {
|
||||
"regexp": "bundle generation (complete|failed)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "test",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"owner": "typescript",
|
||||
"pattern": "$tsc",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": {
|
||||
"regexp": "Changes detected"
|
||||
},
|
||||
"endsPattern": {
|
||||
"regexp": "bundle generation (complete|failed)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,28 +1,14 @@
|
||||
# Stage 1: Build the Angular application
|
||||
FROM node:22-alpine AS build
|
||||
|
||||
# Build stage
|
||||
FROM node:22-alpine AS builder
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files first for better layer caching
|
||||
COPY package.json package-lock.json ./
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
# Copy source and build
|
||||
COPY . .
|
||||
RUN npx ng build --configuration production
|
||||
RUN npm run build
|
||||
|
||||
# Stage 2: Serve static files with nginx
|
||||
# Serve stage
|
||||
FROM nginx:alpine
|
||||
|
||||
# Remove default nginx config
|
||||
RUN rm /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Copy custom nginx config
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Copy built Angular artifacts from build stage
|
||||
COPY --from=build /app/dist/frontend/browser /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
# Frontend
|
||||
|
||||
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 21.2.8.
|
||||
|
||||
## Development server
|
||||
|
||||
To start a local development server, run:
|
||||
|
||||
```bash
|
||||
ng serve
|
||||
```
|
||||
|
||||
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
|
||||
|
||||
## Code scaffolding
|
||||
|
||||
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
|
||||
|
||||
```bash
|
||||
ng generate component component-name
|
||||
```
|
||||
|
||||
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
|
||||
|
||||
```bash
|
||||
ng generate --help
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To build the project run:
|
||||
|
||||
```bash
|
||||
ng build
|
||||
```
|
||||
|
||||
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
|
||||
|
||||
## Running unit tests
|
||||
|
||||
To execute unit tests with the [Vitest](https://vitest.dev/) test runner, use the following command:
|
||||
|
||||
```bash
|
||||
ng test
|
||||
```
|
||||
|
||||
## Running end-to-end tests
|
||||
|
||||
For end-to-end (e2e) testing, run:
|
||||
|
||||
```bash
|
||||
ng e2e
|
||||
```
|
||||
|
||||
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
||||
@@ -1,78 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"cli": {
|
||||
"packageManager": "npm"
|
||||
},
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
"frontend": {
|
||||
"projectType": "application",
|
||||
"schematics": {
|
||||
"@schematics/angular:component": {
|
||||
"style": "scss"
|
||||
}
|
||||
},
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"prefix": "app",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular/build:application",
|
||||
"options": {
|
||||
"browser": "src/main.ts",
|
||||
"tsConfig": "tsconfig.app.json",
|
||||
"inlineStyleLanguage": "scss",
|
||||
"assets": [
|
||||
{
|
||||
"glob": "**/*",
|
||||
"input": "public"
|
||||
}
|
||||
],
|
||||
"styles": [
|
||||
"src/styles.scss"
|
||||
]
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"budgets": [
|
||||
{
|
||||
"type": "initial",
|
||||
"maximumWarning": "500kB",
|
||||
"maximumError": "1MB"
|
||||
},
|
||||
{
|
||||
"type": "anyComponentStyle",
|
||||
"maximumWarning": "4kB",
|
||||
"maximumError": "8kB"
|
||||
}
|
||||
],
|
||||
"outputHashing": "all"
|
||||
},
|
||||
"development": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "production"
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"configurations": {
|
||||
"production": {
|
||||
"buildTarget": "frontend:build:production"
|
||||
},
|
||||
"development": {
|
||||
"buildTarget": "frontend:build:development"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
},
|
||||
"test": {
|
||||
"builder": "@angular/build:unit-test"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
28
frontend/eslint.config.js
Normal file
28
frontend/eslint.config.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist'] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Extrudex</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,42 +1,23 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
|
||||
gzip_min_length 256;
|
||||
|
||||
# Angular SPA — fallback to index.html for client-side routing
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# Cache static assets aggressively
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# Proxy API requests to backend
|
||||
# Uses resolver so nginx doesn't crash if backend isn't available at startup
|
||||
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||
set $backend "extrudex-api:8080";
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://$backend;
|
||||
proxy_pass http://backend:8080/api/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Health check endpoint
|
||||
location /health {
|
||||
access_log off;
|
||||
return 200 "ok";
|
||||
add_header Content-Type text/plain;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
8689
frontend/package-lock.json
generated
8689
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,35 +1,35 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test"
|
||||
},
|
||||
"name": "extrudex-frontend",
|
||||
"private": true,
|
||||
"packageManager": "npm@11.11.0",
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@angular/cdk": "^21.2.8",
|
||||
"@angular/common": "^21.2.0",
|
||||
"@angular/compiler": "^21.2.0",
|
||||
"@angular/core": "^21.2.0",
|
||||
"@angular/forms": "^21.2.0",
|
||||
"@angular/material": "^21.2.8",
|
||||
"@angular/platform-browser": "^21.2.0",
|
||||
"@angular/router": "^21.2.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
"@tanstack/react-query": "^5.60.0",
|
||||
"axios": "^1.7.0",
|
||||
"lucide-react": "^0.460.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-router-dom": "^7.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^21.2.8",
|
||||
"@angular/cli": "^21.2.8",
|
||||
"@angular/compiler-cli": "^21.2.0",
|
||||
"@vitest/browser-playwright": "^4.1.5",
|
||||
"jsdom": "^28.0.0",
|
||||
"prettier": "^3.8.1",
|
||||
"typescript": "~5.9.2",
|
||||
"vitest": "^4.0.8"
|
||||
"@tailwindcss/postcss": "^4.2.4",
|
||||
"@tailwindcss/vite": "^4.2.4",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.3.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.15.0",
|
||||
"eslint-plugin-react-hooks": "^5.0.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.14",
|
||||
"postcss": "^8.4.49",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "~5.6.0",
|
||||
"vite": "^6.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
5
frontend/postcss.config.js
Normal file
5
frontend/postcss.config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
export default {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
27
frontend/src/App.tsx
Normal file
27
frontend/src/App.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter, Routes, Route } from 'react-router-dom'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import InventoryPage from './pages/InventoryPage'
|
||||
|
||||
const queryClient = new QueryClient()
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<div className="min-h-screen bg-slate-900 text-slate-50">
|
||||
<header className="bg-slate-800 border-b border-slate-700 px-4 py-3 flex items-center gap-3 sticky top-0 z-20">
|
||||
<div className="w-8 h-8 rounded bg-emerald-500 flex items-center justify-center text-slate-900 font-bold text-lg">E</div>
|
||||
<h1 className="text-lg font-semibold">Extrudex</h1>
|
||||
</header>
|
||||
<main className="p-4">
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route path="/inventory" element={<InventoryPage />} />
|
||||
</Routes>
|
||||
</main>
|
||||
</div>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
]
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
<!-- Extrudex — Homepage (Main Hub) -->
|
||||
<main class="main-content">
|
||||
<h1 class="sr-only">Extrudex Dashboard</h1>
|
||||
|
||||
<!-- Status Summary Bar — fleet-wide health at a glance -->
|
||||
<app-dashboard-summary></app-dashboard-summary>
|
||||
|
||||
<!-- Inventory Summary — filament metrics at a glance -->
|
||||
<app-inventory-summary></app-inventory-summary>
|
||||
|
||||
<!-- Filament Inventory — routed view -->
|
||||
<router-outlet />
|
||||
</main>
|
||||
@@ -1,9 +0,0 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { FilamentTableComponent } from './components/filament-table/filament-table.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
component: FilamentTableComponent,
|
||||
},
|
||||
];
|
||||
@@ -1,27 +0,0 @@
|
||||
:host {
|
||||
display: block;
|
||||
min-height: 100vh;
|
||||
background: #1a1a2e;
|
||||
color: #e0e0e0;
|
||||
font-family: 'Inter', 'Segoe UI', Roboto, sans-serif;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
padding: 16px;
|
||||
|
||||
@media (min-width: 800px) {
|
||||
padding: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { App } from './app';
|
||||
|
||||
describe('App', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
it('should create the app', () => {
|
||||
const fixture = TestBed.createComponent(App);
|
||||
const app = fixture.componentInstance;
|
||||
expect(app).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should render title', async () => {
|
||||
const fixture = TestBed.createComponent(App);
|
||||
await fixture.whenStable();
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
expect(compiled.querySelector('h1')?.textContent).toContain('Extrudex Dashboard');
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Component, ViewChild } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { DashboardSummaryComponent } from './components/dashboard-summary/dashboard-summary.component';
|
||||
import { InventorySummaryComponent } from './components/inventory-summary/inventory-summary.component';
|
||||
import { AgentSummary, SystemHealth } from './models/agent.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [RouterOutlet, DashboardSummaryComponent, InventorySummaryComponent],
|
||||
templateUrl: './app.html',
|
||||
styleUrl: './app.scss'
|
||||
})
|
||||
export class App {
|
||||
@ViewChild(DashboardSummaryComponent) summaryComponent!: DashboardSummaryComponent;
|
||||
|
||||
/** Sample data for development — will be replaced by real service data */
|
||||
readonly sampleSummary: AgentSummary = {
|
||||
total: 7,
|
||||
active: 4,
|
||||
idle: 1,
|
||||
thinking: 1,
|
||||
error: 1,
|
||||
};
|
||||
|
||||
readonly sampleHealth: SystemHealth = {
|
||||
connected: true,
|
||||
status: 'healthy',
|
||||
};
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
<!-- Dashboard Summary Bar — Fleet-wide health at a glance -->
|
||||
<section class="dashboard-summary" role="status" aria-label="Dashboard summary">
|
||||
|
||||
<!-- System Health Indicator -->
|
||||
<div class="summary-item health-indicator"
|
||||
[class.healthy]="health().status === 'healthy'"
|
||||
[class.degraded]="isDegraded()"
|
||||
[class.down]="isDown()"
|
||||
[matTooltip]="statusLabel()"
|
||||
matTooltipPosition="below">
|
||||
<span class="connection-dot" [class.connected]="health().connected"></span>
|
||||
<span class="health-label">{{ statusLabel() }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Total Active Agents -->
|
||||
<div class="summary-item" matTooltip="Total active agents" matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true">smart_toy</mat-icon>
|
||||
<span class="metric-value">{{ summary().active }} / {{ summary().total }}</span>
|
||||
<span class="metric-label">Active</span>
|
||||
</div>
|
||||
|
||||
<!-- Status Breakdown -->
|
||||
<div class="summary-item status-breakdown">
|
||||
<mat-chip-set aria-label="Agent status breakdown">
|
||||
<mat-chip
|
||||
class="status-chip chip-active"
|
||||
[class.has-count]="summary().active > 0"
|
||||
matTooltip="Active agents">
|
||||
<mat-icon matChipStart>check_circle</mat-icon>
|
||||
<span class="chip-count">{{ summary().active }}</span>
|
||||
<span class="chip-label">Active</span>
|
||||
</mat-chip>
|
||||
|
||||
<mat-chip
|
||||
class="status-chip chip-idle"
|
||||
[class.has-count]="summary().idle > 0"
|
||||
matTooltip="Idle agents">
|
||||
<mat-icon matChipStart>pause_circle</mat-icon>
|
||||
<span class="chip-count">{{ summary().idle }}</span>
|
||||
<span class="chip-label">Idle</span>
|
||||
</mat-chip>
|
||||
|
||||
<mat-chip
|
||||
class="status-chip chip-thinking"
|
||||
[class.has-count]="summary().thinking > 0"
|
||||
matTooltip="Thinking agents">
|
||||
<mat-icon matChipStart>psychology</mat-icon>
|
||||
<span class="chip-count">{{ summary().thinking }}</span>
|
||||
<span class="chip-label">Thinking</span>
|
||||
</mat-chip>
|
||||
|
||||
<mat-chip
|
||||
class="status-chip chip-error"
|
||||
[class.has-count]="hasErrors()"
|
||||
matTooltip="Agents in error">
|
||||
<mat-icon matChipStart>error</mat-icon>
|
||||
<span class="chip-count">{{ summary().error }}</span>
|
||||
<span class="chip-label">Error</span>
|
||||
</mat-chip>
|
||||
</mat-chip-set>
|
||||
</div>
|
||||
|
||||
</section>
|
||||
@@ -1,174 +0,0 @@
|
||||
/**
|
||||
* Dashboard Summary Component Styles
|
||||
* Touch-optimized for kiosk (Raspberry Pi 5) and mobile PWA
|
||||
* Uses Angular Material utility classes where possible
|
||||
*/
|
||||
|
||||
// Touch-optimized sizing
|
||||
$touch-target-min: 48px;
|
||||
$kiosk-font-primary: 20px;
|
||||
$mobile-font-primary: 16px;
|
||||
$spacing-unit: 8px;
|
||||
|
||||
// Status colors — high contrast for workshop/bright environments
|
||||
$color-active: #4ade70; // Green — printing/active
|
||||
$color-idle: #94a3b8; // Gray — idle/offline
|
||||
$color-thinking: #60a5fa; // Blue — thinking/processing
|
||||
$color-error: #f87171; // Red — error/failed
|
||||
$color-connected: #4ade70; // Green — SignalR connected
|
||||
$color-disconnected: #f87171; // Red — disconnected
|
||||
|
||||
.dashboard-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit * 2;
|
||||
padding: $spacing-unit * 2;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
|
||||
// Responsive: on mobile, allow horizontal scroll
|
||||
@media (max-width: 480px) {
|
||||
padding: $spacing-unit;
|
||||
gap: $spacing-unit;
|
||||
}
|
||||
}
|
||||
|
||||
.summary-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit;
|
||||
min-height: $touch-target-min;
|
||||
white-space: nowrap;
|
||||
|
||||
.metric-value {
|
||||
font-size: $kiosk-font-primary;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
font-size: $mobile-font-primary;
|
||||
}
|
||||
}
|
||||
|
||||
.metric-label {
|
||||
font-size: 12px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
font-size: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Health indicator
|
||||
.health-indicator {
|
||||
padding: $spacing-unit $spacing-unit * 2;
|
||||
border-radius: 24px;
|
||||
transition: background-color 0.3s ease;
|
||||
|
||||
&.healthy {
|
||||
background-color: rgba($color-active, 0.15);
|
||||
}
|
||||
|
||||
&.degraded {
|
||||
background-color: rgba($color-thinking, 0.15);
|
||||
}
|
||||
|
||||
&.down {
|
||||
background-color: rgba($color-error, 0.15);
|
||||
}
|
||||
|
||||
.connection-dot {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
transition: background-color 0.3s ease;
|
||||
|
||||
&.connected {
|
||||
background-color: $color-connected;
|
||||
box-shadow: 0 0 6px $color-connected;
|
||||
}
|
||||
|
||||
&:not(.connected) {
|
||||
background-color: $color-disconnected;
|
||||
box-shadow: 0 0 6px $color-disconnected;
|
||||
}
|
||||
}
|
||||
|
||||
.health-label {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Status breakdown chips
|
||||
.status-breakdown {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-chip {
|
||||
min-height: $touch-target-min !important;
|
||||
font-size: 14px !important;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
min-height: 40px !important;
|
||||
font-size: 12px !important;
|
||||
padding: 0 8px !important;
|
||||
}
|
||||
|
||||
.chip-count {
|
||||
font-weight: 700;
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
.chip-label {
|
||||
font-size: 12px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px !important;
|
||||
width: 18px !important;
|
||||
height: 18px !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Status chip color variants
|
||||
.chip-active {
|
||||
--mdc-chip-outline-color: #{$color-active};
|
||||
|
||||
&.has-count {
|
||||
background-color: rgba($color-active, 0.15) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.chip-idle {
|
||||
--mdc-chip-outline-color: #{$color-idle};
|
||||
|
||||
&.has-count {
|
||||
background-color: rgba($color-idle, 0.15) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.chip-thinking {
|
||||
--mdc-chip-outline-color: #{$color-thinking};
|
||||
|
||||
&.has-count {
|
||||
background-color: rgba($color-thinking, 0.15) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.chip-error {
|
||||
--mdc-chip-outline-color: #{$color-error};
|
||||
|
||||
&.has-count {
|
||||
background-color: rgba($color-error, 0.2) !important;
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { DashboardSummaryComponent } from './dashboard-summary.component';
|
||||
import { AgentSummary, SystemHealth } from '../../models/agent.model';
|
||||
|
||||
describe('DashboardSummaryComponent', () => {
|
||||
let component: DashboardSummaryComponent;
|
||||
let fixture: ComponentFixture<DashboardSummaryComponent>;
|
||||
|
||||
const mockSummary: AgentSummary = {
|
||||
total: 7,
|
||||
active: 4,
|
||||
idle: 1,
|
||||
thinking: 1,
|
||||
error: 1,
|
||||
};
|
||||
|
||||
const mockHealthy: SystemHealth = {
|
||||
connected: true,
|
||||
status: 'healthy',
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [DashboardSummaryComponent],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(DashboardSummaryComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should default to zeroed summary', () => {
|
||||
const summary = component.summary();
|
||||
expect(summary.total).toBe(0);
|
||||
expect(summary.active).toBe(0);
|
||||
expect(summary.idle).toBe(0);
|
||||
expect(summary.thinking).toBe(0);
|
||||
expect(summary.error).toBe(0);
|
||||
});
|
||||
|
||||
it('should default to disconnected/down health', () => {
|
||||
const health = component.health();
|
||||
expect(health.connected).toBe(false);
|
||||
expect(health.status).toBe('down');
|
||||
});
|
||||
|
||||
it('should update summary data', () => {
|
||||
component.updateSummary(mockSummary);
|
||||
expect(component.summary()).toEqual(mockSummary);
|
||||
});
|
||||
|
||||
it('should update health data', () => {
|
||||
component.updateHealth(mockHealthy);
|
||||
expect(component.health()).toEqual(mockHealthy);
|
||||
});
|
||||
|
||||
it('should compute hasErrors correctly', () => {
|
||||
expect(component.hasErrors()).toBe(false);
|
||||
component.updateSummary({ ...mockSummary, error: 2 });
|
||||
expect(component.hasErrors()).toBe(true);
|
||||
});
|
||||
|
||||
it('should compute connectionColor correctly', () => {
|
||||
expect(component.connectionColor()).toBe('disconnected');
|
||||
component.updateHealth({ connected: true, status: 'healthy' });
|
||||
expect(component.connectionColor()).toBe('connected');
|
||||
});
|
||||
|
||||
it('should compute statusLabel for each state', () => {
|
||||
component.updateHealth({ connected: true, status: 'healthy' });
|
||||
expect(component.statusLabel()).toBe('All Systems Go');
|
||||
|
||||
component.updateHealth({ connected: true, status: 'degraded' });
|
||||
expect(component.statusLabel()).toBe('Degraded');
|
||||
|
||||
component.updateHealth({ connected: false, status: 'down' });
|
||||
expect(component.statusLabel()).toBe('Offline');
|
||||
});
|
||||
|
||||
it('should render summary values in template', () => {
|
||||
component.updateSummary(mockSummary);
|
||||
component.updateHealth(mockHealthy);
|
||||
fixture.detectChanges();
|
||||
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
expect(compiled.textContent).toContain('4 / 7');
|
||||
expect(compiled.textContent).toContain('Active');
|
||||
expect(compiled.textContent).toContain('All Systems Go');
|
||||
});
|
||||
|
||||
it('should render status breakdown chips', () => {
|
||||
component.updateSummary(mockSummary);
|
||||
fixture.detectChanges();
|
||||
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
expect(compiled.textContent).toContain('4'); // active count
|
||||
expect(compiled.textContent).toContain('1'); // idle count (multiple)
|
||||
expect(compiled.textContent).toContain('Error');
|
||||
});
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
import { ChangeDetectionStrategy, Component, Input, OnDestroy, signal, computed } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatChipsModule } from '@angular/material/chips';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { AgentSummary, SystemHealth } from '../../models/agent.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-dashboard-summary',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatChipsModule,
|
||||
MatTooltipModule,
|
||||
],
|
||||
templateUrl: './dashboard-summary.component.html',
|
||||
styleUrls: ['./dashboard-summary.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class DashboardSummaryComponent implements OnDestroy {
|
||||
/** Agent summary data — reactive signal, updatable via updateSummary() */
|
||||
readonly summary = signal<AgentSummary>({
|
||||
total: 0,
|
||||
active: 0,
|
||||
idle: 0,
|
||||
thinking: 0,
|
||||
error: 0,
|
||||
});
|
||||
|
||||
/** System health data — reactive signal, updatable via updateHealth() */
|
||||
readonly health = signal<SystemHealth>({
|
||||
connected: false,
|
||||
status: 'down',
|
||||
});
|
||||
|
||||
/** Computed signal: whether there are errors to highlight */
|
||||
readonly hasErrors = computed(() => this.summary().error > 0);
|
||||
|
||||
/** Computed signal: whether system is degraded */
|
||||
readonly isDegraded = computed(() => this.health().status === 'degraded');
|
||||
|
||||
/** Computed signal: whether system is down */
|
||||
readonly isDown = computed(() => this.health().status === 'down');
|
||||
|
||||
/** Computed signal: connection indicator color */
|
||||
readonly connectionColor = computed(() =>
|
||||
this.health().connected ? 'connected' : 'disconnected'
|
||||
);
|
||||
|
||||
/** Computed signal: overall status label */
|
||||
readonly statusLabel = computed(() => {
|
||||
const h = this.health();
|
||||
if (h.status === 'healthy') return 'All Systems Go';
|
||||
if (h.status === 'degraded') return 'Degraded';
|
||||
return 'Offline';
|
||||
});
|
||||
|
||||
/**
|
||||
* Update the agent summary. Called by the parent or a service
|
||||
* when new data arrives (e.g., via SignalR).
|
||||
*/
|
||||
updateSummary(data: AgentSummary): void {
|
||||
this.summary.set(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the system health. Called by the parent or a service
|
||||
* when the connection state changes.
|
||||
*/
|
||||
updateHealth(data: SystemHealth): void {
|
||||
this.health.set(data);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Cleanup handled by signals — no manual subscription teardown needed
|
||||
}
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
<!-- Filament Add/Edit Dialog — Angular Material Dialog -->
|
||||
<mat-dialog-content class="filament-dialog-content">
|
||||
|
||||
<!-- Dialog Title -->
|
||||
<h2 mat-dialog-title>{{ dialogTitle() }}</h2>
|
||||
|
||||
<!-- Loading state for lookup data -->
|
||||
@if (lookupsLoading()) {
|
||||
<div class="dialog-loading" role="status" aria-label="Loading material options">
|
||||
<mat-spinner diameter="32"></mat-spinner>
|
||||
<p>Loading material options…</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Form -->
|
||||
@if (!lookupsLoading()) {
|
||||
<form [formGroup]="form" class="filament-form" (ngSubmit)="save()">
|
||||
|
||||
<!-- Server Error Banner -->
|
||||
@if (serverError()) {
|
||||
<div class="error-banner" role="alert">
|
||||
<mat-icon aria-hidden="true">error</mat-icon>
|
||||
<span>{{ serverError() }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- ── Material Section ──────────────────────────────── -->
|
||||
<div class="form-section">
|
||||
<h3 class="section-title">Material</h3>
|
||||
|
||||
<!-- Base Material -->
|
||||
<mat-form-field appearance="outline" class="form-field full-width">
|
||||
<mat-label>Base Material</mat-label>
|
||||
<mat-select formControlName="materialBaseId" required aria-label="Base material">
|
||||
@for (base of materialBases(); track base.id) {
|
||||
<mat-option [value]="base.id">{{ base.name }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (form.get('materialBaseId')!.hasError('required') && form.get('materialBaseId')!.touched) {
|
||||
<mat-error>Base material is required</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<!-- Finish -->
|
||||
<mat-form-field appearance="outline" class="form-field full-width">
|
||||
<mat-label>Finish</mat-label>
|
||||
<mat-select formControlName="materialFinishId" required aria-label="Material finish">
|
||||
<mat-option [value]="''" disabled>Select a base material first</mat-option>
|
||||
@for (finish of filteredFinishes(); track finish.id) {
|
||||
<mat-option [value]="finish.id">{{ finish.name }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (form.get('materialFinishId')!.hasError('required') && form.get('materialFinishId')!.touched) {
|
||||
<mat-error>Finish is required</mat-error>
|
||||
}
|
||||
@if (filteredFinishes().length === 0 && form.get('materialBaseId')!.value) {
|
||||
<mat-hint>No finishes available for this material</mat-hint>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<!-- Modifier (optional) -->
|
||||
<mat-form-field appearance="outline" class="form-field full-width">
|
||||
<mat-label>Modifier (optional)</mat-label>
|
||||
<mat-select formControlName="materialModifierId" aria-label="Material modifier">
|
||||
<mat-option [value]="null">None</mat-option>
|
||||
@for (modifier of filteredModifiers(); track modifier.id) {
|
||||
<mat-option [value]="modifier.id">{{ modifier.name }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (filteredModifiers().length === 0 && form.get('materialBaseId')!.value) {
|
||||
<mat-hint>No modifiers available for this material</mat-hint>
|
||||
}
|
||||
</mat-form-field>
|
||||
</div>
|
||||
|
||||
<!-- ── Spool Details Section ──────────────────────────── -->
|
||||
<div class="form-section">
|
||||
<h3 class="section-title">Spool Details</h3>
|
||||
|
||||
<!-- Brand -->
|
||||
<mat-form-field appearance="outline" class="form-field full-width">
|
||||
<mat-label>Brand</mat-label>
|
||||
<input matInput formControlName="brand" required maxlength="200"
|
||||
placeholder="e.g., Bambu Lab, Polymaker" aria-label="Brand" />
|
||||
@if (form.get('brand')!.hasError('required') && form.get('brand')!.touched) {
|
||||
<mat-error>Brand is required</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<!-- Serial -->
|
||||
<mat-form-field appearance="outline" class="form-field full-width">
|
||||
<mat-label>Serial Number</mat-label>
|
||||
<input matInput formControlName="spoolSerial" required maxlength="200"
|
||||
placeholder="e.g., SN-001" aria-label="Serial number" />
|
||||
@if (form.get('spoolSerial')!.hasError('required') && form.get('spoolSerial')!.touched) {
|
||||
<mat-error>Serial number is required</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<!-- Color Name + Color Hex (side by side) -->
|
||||
<div class="form-row">
|
||||
<mat-form-field appearance="outline" class="form-field">
|
||||
<mat-label>Color Name</mat-label>
|
||||
<input matInput formControlName="colorName" required maxlength="200"
|
||||
placeholder="e.g., Fire Engine Red" aria-label="Color name" />
|
||||
@if (form.get('colorName')!.hasError('required') && form.get('colorName')!.touched) {
|
||||
<mat-error>Color name is required</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline" class="form-field color-hex-field">
|
||||
<mat-label>Color Hex</mat-label>
|
||||
<input matInput formControlName="colorHex" required
|
||||
placeholder="#FF0000" maxlength="7" aria-label="Color hex code" />
|
||||
<span matTextSuffix class="color-preview">
|
||||
<span class="color-swatch-mini" [style.background-color]="form.get('colorHex')!.value"></span>
|
||||
</span>
|
||||
@if (form.get('colorHex')!.hasError('required') && form.get('colorHex')!.touched) {
|
||||
<mat-error>Color hex is required</mat-error>
|
||||
}
|
||||
@if (form.get('colorHex')!.hasError('pattern') && form.get('colorHex')!.touched) {
|
||||
<mat-error>Must be #RRGGBB format</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Weight & Dimensions Section ────────────────────── -->
|
||||
<div class="form-section">
|
||||
<h3 class="section-title">Weight & Dimensions</h3>
|
||||
|
||||
<div class="form-row">
|
||||
<!-- Diameter -->
|
||||
<mat-form-field appearance="outline" class="form-field">
|
||||
<mat-label>Diameter (mm)</mat-label>
|
||||
<input matInput type="number" formControlName="filamentDiameterMm" required
|
||||
min="0.1" max="10" step="0.01" aria-label="Filament diameter in mm" />
|
||||
@if (form.get('filamentDiameterMm')!.hasError('required') && form.get('filamentDiameterMm')!.touched) {
|
||||
<mat-error>Diameter is required</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<!-- Total Weight -->
|
||||
<mat-form-field appearance="outline" class="form-field">
|
||||
<mat-label>Total Weight (g)</mat-label>
|
||||
<input matInput type="number" formControlName="weightTotalGrams" required
|
||||
min="0.01" max="100000" step="1" aria-label="Total spool weight in grams" />
|
||||
<mat-hint>Full spool weight</mat-hint>
|
||||
@if (form.get('weightTotalGrams')!.hasError('required') && form.get('weightTotalGrams')!.touched) {
|
||||
<mat-error>Total weight is required</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<!-- Remaining Weight -->
|
||||
<mat-form-field appearance="outline" class="form-field">
|
||||
<mat-label>Remaining Weight (g)</mat-label>
|
||||
<input matInput type="number" formControlName="weightRemainingGrams" required
|
||||
min="0" max="100000" step="1" aria-label="Remaining weight in grams" />
|
||||
<mat-hint>Current remaining</mat-hint>
|
||||
@if (form.get('weightRemainingGrams')!.hasError('required') && form.get('weightRemainingGrams')!.touched) {
|
||||
<mat-error>Remaining weight is required</mat-error>
|
||||
}
|
||||
@if (form.get('weightRemainingGrams')!.hasError('exceedsTotal')) {
|
||||
<mat-error>Cannot exceed total weight</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Purchase & Status Section ──────────────────────── -->
|
||||
<div class="form-section">
|
||||
<h3 class="section-title">Purchase & Status</h3>
|
||||
|
||||
<div class="form-row">
|
||||
<!-- Purchase Price -->
|
||||
<mat-form-field appearance="outline" class="form-field">
|
||||
<mat-label>Price</mat-label>
|
||||
<input matInput type="number" formControlName="purchasePrice"
|
||||
min="0" max="1000000" step="0.01"
|
||||
placeholder="e.g., 25.00" aria-label="Purchase price" />
|
||||
<span matTextSuffix>$</span>
|
||||
@if (form.get('purchasePrice')!.hasError('min') && form.get('purchasePrice')!.touched) {
|
||||
<mat-error>Price must be non-negative</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<!-- Purchase Date -->
|
||||
<mat-form-field appearance="outline" class="form-field">
|
||||
<mat-label>Purchase Date</mat-label>
|
||||
<input matInput [matDatepicker]="picker" formControlName="purchaseDate"
|
||||
aria-label="Purchase date" />
|
||||
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
|
||||
<mat-datepicker #picker></mat-datepicker>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
|
||||
<!-- Active Status -->
|
||||
<div class="checkbox-row">
|
||||
<mat-checkbox formControlName="isActive" aria-label="Active status">
|
||||
Spool is active and available for use
|
||||
</mat-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
}
|
||||
|
||||
</mat-dialog-content>
|
||||
|
||||
<!-- Dialog Actions -->
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" (click)="cancel()" [disabled]="saving()"
|
||||
aria-label="Cancel">
|
||||
Cancel
|
||||
</button>
|
||||
<button mat-raised-button color="primary" type="button" (click)="save()"
|
||||
[disabled]="saving() || form.invalid" aria-label="Save filament">
|
||||
@if (saving()) {
|
||||
<mat-spinner diameter="20" class="btn-spinner"></mat-spinner>
|
||||
}
|
||||
{{ isEditMode() ? 'Save Changes' : 'Add Filament' }}
|
||||
</button>
|
||||
</mat-dialog-actions>
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* Filament Dialog Styles
|
||||
* Touch-optimized for kiosk (Raspberry Pi 5) and mobile PWA
|
||||
*/
|
||||
|
||||
$touch-target-min: 48px;
|
||||
$spacing-unit: 8px;
|
||||
$color-error: #ef4444;
|
||||
|
||||
// ── Dialog Layout ──────────────────────────────────────────
|
||||
|
||||
.filament-dialog-content {
|
||||
overflow-y: auto;
|
||||
max-height: 70vh;
|
||||
padding: 0 $spacing-unit * 2;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
padding: 0 $spacing-unit;
|
||||
}
|
||||
}
|
||||
|
||||
[mat-dialog-title] {
|
||||
margin: 0 0 $spacing-unit * 2 0;
|
||||
padding: $spacing-unit * 2 0 0 0;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
// ── Loading State ──────────────────────────────────────────
|
||||
|
||||
.dialog-loading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 48px $spacing-unit * 2;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
|
||||
p {
|
||||
margin-top: $spacing-unit * 2;
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Error Banner ───────────────────────────────────────────
|
||||
|
||||
.error-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit;
|
||||
padding: $spacing-unit * 1.5 $spacing-unit * 2;
|
||||
border-radius: 8px;
|
||||
margin-bottom: $spacing-unit * 2;
|
||||
background-color: rgba($color-error, 0.12);
|
||||
color: $color-error;
|
||||
border: 1px solid rgba($color-error, 0.3);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
|
||||
mat-icon {
|
||||
font-size: 20px !important;
|
||||
width: 20px !important;
|
||||
height: 20px !important;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Form Sections ──────────────────────────────────────────
|
||||
|
||||
.form-section {
|
||||
margin-bottom: $spacing-unit * 3;
|
||||
|
||||
.section-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
margin: 0 0 $spacing-unit * 1.5 0;
|
||||
padding-bottom: $spacing-unit * 0.5;
|
||||
border-bottom: 1px solid var(--mat-sys-outline-variant);
|
||||
}
|
||||
}
|
||||
|
||||
.filament-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: $spacing-unit;
|
||||
}
|
||||
|
||||
// ── Form Fields ────────────────────────────────────────────
|
||||
|
||||
.form-field {
|
||||
width: 100%;
|
||||
|
||||
// Touch target sizing
|
||||
.mat-mdc-form-field-subscript-wrapper {
|
||||
min-height: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: $spacing-unit * 2;
|
||||
width: 100%;
|
||||
|
||||
.form-field {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Color Hex Preview ──────────────────────────────────────
|
||||
|
||||
.color-hex-field {
|
||||
max-width: 180px;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.color-preview {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.color-swatch-mini {
|
||||
display: inline-block;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid rgba(0, 0, 0, 0.12);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
// ── Checkbox Row ───────────────────────────────────────────
|
||||
|
||||
.checkbox-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: $spacing-unit 0;
|
||||
|
||||
mat-checkbox {
|
||||
min-height: $touch-target-min;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Save Button Spinner ────────────────────────────────────
|
||||
|
||||
mat-dialog-actions {
|
||||
padding: $spacing-unit $spacing-unit * 2 $spacing-unit * 2;
|
||||
gap: $spacing-unit;
|
||||
|
||||
button {
|
||||
min-height: $touch-target-min;
|
||||
min-width: 100px;
|
||||
}
|
||||
}
|
||||
|
||||
.btn-spinner {
|
||||
display: inline-block;
|
||||
margin-right: $spacing-unit;
|
||||
vertical-align: middle;
|
||||
|
||||
circle {
|
||||
stroke: currentColor;
|
||||
}
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
inject,
|
||||
signal,
|
||||
computed,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatDatepickerModule } from '@angular/material/datepicker';
|
||||
import { MatNativeDateModule } from '@angular/material/core';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
|
||||
import { Filament } from '../../models/filament.model';
|
||||
import {
|
||||
MaterialBase,
|
||||
MaterialFinish,
|
||||
MaterialModifier,
|
||||
} from '../../models/material.model';
|
||||
import {
|
||||
FilamentService,
|
||||
CreateFilamentRequest,
|
||||
UpdateFilamentRequest,
|
||||
} from '../../services/filament.service';
|
||||
|
||||
/** Data passed into the dialog from the opener. */
|
||||
export interface FilamentDialogData {
|
||||
/** If provided, the dialog opens in edit mode with pre-populated fields. */
|
||||
filament?: Filament;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-filament-dialog',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
ReactiveFormsModule,
|
||||
MatDialogModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatSelectModule,
|
||||
MatDatepickerModule,
|
||||
MatNativeDateModule,
|
||||
MatCheckboxModule,
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatTooltipModule,
|
||||
],
|
||||
templateUrl: './filament-dialog.component.html',
|
||||
styleUrl: './filament-dialog.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class FilamentDialogComponent {
|
||||
private readonly dialogRef = inject(MatDialogRef<FilamentDialogComponent>);
|
||||
private readonly data = inject<FilamentDialogData>(MAT_DIALOG_DATA);
|
||||
private readonly fb = inject(FormBuilder);
|
||||
private readonly filamentService = inject(FilamentService);
|
||||
|
||||
/** Whether this dialog is in edit mode (has existing filament data). */
|
||||
readonly isEditMode = computed(() => !!this.data.filament);
|
||||
|
||||
/** Dialog title based on mode. */
|
||||
readonly dialogTitle = computed(() =>
|
||||
this.isEditMode() ? 'Edit Filament' : 'Add Filament'
|
||||
);
|
||||
|
||||
// ── Lookup data signals ──────────────────────────────────
|
||||
|
||||
/** All material bases for the base material dropdown. */
|
||||
readonly materialBases = signal<MaterialBase[]>([]);
|
||||
|
||||
/** Material finishes filtered by selected base material. */
|
||||
readonly filteredFinishes = signal<MaterialFinish[]>([]);
|
||||
|
||||
/** Material modifiers filtered by selected base material. */
|
||||
readonly filteredModifiers = signal<MaterialModifier[]>([]);
|
||||
|
||||
/** Whether material lookups are loading. */
|
||||
readonly lookupsLoading = signal(true);
|
||||
|
||||
/** Whether the save operation is in progress. */
|
||||
readonly saving = signal(false);
|
||||
|
||||
/** Server error message, if any. */
|
||||
readonly serverError = signal<string | null>(null);
|
||||
|
||||
// ── Form ─────────────────────────────────────────────────
|
||||
|
||||
readonly form: FormGroup = this.fb.group({
|
||||
materialBaseId: ['', Validators.required],
|
||||
materialFinishId: ['', Validators.required],
|
||||
materialModifierId: [null],
|
||||
brand: ['', [Validators.required, Validators.maxLength(200)]],
|
||||
colorName: ['', [Validators.required, Validators.maxLength(200)]],
|
||||
colorHex: ['#000000', [Validators.required, Validators.pattern(/^#[0-9A-Fa-f]{6}$/)]],
|
||||
weightTotalGrams: [1000, [Validators.required, Validators.min(0.01), Validators.max(100000)]],
|
||||
weightRemainingGrams: [1000, [Validators.required, Validators.min(0), Validators.max(100000)]],
|
||||
filamentDiameterMm: [1.75, [Validators.required, Validators.min(0.1), Validators.max(10)]],
|
||||
spoolSerial: ['', [Validators.required, Validators.maxLength(200)]],
|
||||
purchasePrice: [null, [Validators.min(0), Validators.max(1000000)]],
|
||||
purchaseDate: [null],
|
||||
isActive: [true],
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.loadLookups();
|
||||
this.patchFormIfEditing();
|
||||
this.setupCascadingFilters();
|
||||
}
|
||||
|
||||
// ── Data loading ─────────────────────────────────────────
|
||||
|
||||
/** Load material bases, finishes, and modifiers for dropdowns. */
|
||||
private loadLookups(): void {
|
||||
this.lookupsLoading.set(true);
|
||||
this.filamentService.getMaterialBases().subscribe({
|
||||
next: (bases) => {
|
||||
this.materialBases.set(bases);
|
||||
this.lookupsLoading.set(false);
|
||||
},
|
||||
error: () => {
|
||||
this.lookupsLoading.set(false);
|
||||
this.serverError.set('Failed to load material options. Please try again.');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Pre-populate form fields when editing an existing filament. */
|
||||
private patchFormIfEditing(): void {
|
||||
if (this.data.filament) {
|
||||
const f = this.data.filament;
|
||||
this.form.patchValue({
|
||||
materialBaseId: f.materialBaseId,
|
||||
materialFinishId: f.materialFinishId,
|
||||
materialModifierId: f.materialModifierId,
|
||||
brand: f.brand,
|
||||
colorName: f.colorName,
|
||||
colorHex: f.colorHex,
|
||||
weightTotalGrams: f.weightTotalGrams,
|
||||
weightRemainingGrams: f.weightRemainingGrams,
|
||||
filamentDiameterMm: f.filamentDiameterMm,
|
||||
spoolSerial: f.spoolSerial,
|
||||
purchasePrice: f.purchasePrice,
|
||||
purchaseDate: f.purchaseDate ? new Date(f.purchaseDate) : null,
|
||||
isActive: f.isActive,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Set up cascading filter: when base material changes, reload finishes & modifiers. */
|
||||
private setupCascadingFilters(): void {
|
||||
this.form.get('materialBaseId')!.valueChanges.subscribe((baseId: string | null) => {
|
||||
// Clear dependent selections when base changes
|
||||
this.form.get('materialFinishId')!.setValue('');
|
||||
this.form.get('materialModifierId')!.setValue(null);
|
||||
this.filteredFinishes.set([]);
|
||||
this.filteredModifiers.set([]);
|
||||
|
||||
if (!baseId) return;
|
||||
|
||||
this.filamentService.getMaterialFinishes(baseId).subscribe({
|
||||
next: (finishes) => this.filteredFinishes.set(finishes),
|
||||
error: () => this.filteredFinishes.set([]),
|
||||
});
|
||||
|
||||
this.filamentService.getMaterialModifiers(baseId).subscribe({
|
||||
next: (modifiers) => this.filteredModifiers.set(modifiers),
|
||||
error: () => this.filteredModifiers.set([]),
|
||||
});
|
||||
});
|
||||
|
||||
// If editing, trigger the cascading load for the pre-selected base
|
||||
if (this.data.filament) {
|
||||
const baseId = this.data.filament.materialBaseId;
|
||||
// We need to load finishes and modifiers for the pre-selected base
|
||||
// but also re-select the original finish and modifier after loading
|
||||
this.filamentService.getMaterialFinishes(baseId).subscribe({
|
||||
next: (finishes) => {
|
||||
this.filteredFinishes.set(finishes);
|
||||
// Re-patch finish after load
|
||||
this.form.get('materialFinishId')!.setValue(this.data.filament!.materialFinishId);
|
||||
},
|
||||
});
|
||||
this.filamentService.getMaterialModifiers(baseId).subscribe({
|
||||
next: (modifiers) => {
|
||||
this.filteredModifiers.set(modifiers);
|
||||
// Re-patch modifier after load
|
||||
this.form.get('materialModifierId')!.setValue(this.data.filament!.materialModifierId);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────
|
||||
|
||||
/** Cancel and close the dialog without saving. */
|
||||
cancel(): void {
|
||||
this.dialogRef.close(false);
|
||||
}
|
||||
|
||||
/** Submit the form — creates or updates the filament. */
|
||||
save(): void {
|
||||
if (this.form.invalid) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
// Cross-field validation: remaining weight must not exceed total weight
|
||||
const total = this.form.value.weightTotalGrams;
|
||||
const remaining = this.form.value.weightRemainingGrams;
|
||||
if (remaining > total) {
|
||||
this.form.get('weightRemainingGrams')!.setErrors({ exceedsTotal: true });
|
||||
return;
|
||||
}
|
||||
|
||||
this.saving.set(true);
|
||||
this.serverError.set(null);
|
||||
|
||||
const formValue = this.form.value;
|
||||
const request: CreateFilamentRequest | UpdateFilamentRequest = {
|
||||
materialBaseId: formValue.materialBaseId,
|
||||
materialFinishId: formValue.materialFinishId,
|
||||
materialModifierId: formValue.materialModifierId || null,
|
||||
brand: formValue.brand.trim(),
|
||||
colorName: formValue.colorName.trim(),
|
||||
colorHex: formValue.colorHex,
|
||||
weightTotalGrams: formValue.weightTotalGrams,
|
||||
weightRemainingGrams: formValue.weightRemainingGrams,
|
||||
filamentDiameterMm: formValue.filamentDiameterMm,
|
||||
spoolSerial: formValue.spoolSerial.trim(),
|
||||
purchasePrice: formValue.purchasePrice ?? null,
|
||||
purchaseDate: formValue.purchaseDate
|
||||
? new Date(formValue.purchaseDate).toISOString()
|
||||
: null,
|
||||
isActive: formValue.isActive,
|
||||
};
|
||||
|
||||
if (this.isEditMode()) {
|
||||
const id = this.data.filament!.id;
|
||||
this.filamentService.updateFilament(id, request).subscribe({
|
||||
next: (updated) => {
|
||||
this.saving.set(false);
|
||||
this.dialogRef.close(true);
|
||||
},
|
||||
error: (err) => {
|
||||
this.saving.set(false);
|
||||
this.serverError.set(
|
||||
err?.error?.error || err?.message || 'Failed to update filament. Please try again.'
|
||||
);
|
||||
},
|
||||
});
|
||||
} else {
|
||||
this.filamentService.createFilament(request).subscribe({
|
||||
next: (created) => {
|
||||
this.saving.set(false);
|
||||
this.dialogRef.close(true);
|
||||
},
|
||||
error: (err) => {
|
||||
this.saving.set(false);
|
||||
this.serverError.set(
|
||||
err?.error?.error || err?.message || 'Failed to create filament. Please try again.'
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
<!-- Filament Filter Bar — material type, color search, low stock, active-only -->
|
||||
<div class="filament-filter-bar" role="search" aria-label="Filter filament inventory">
|
||||
|
||||
<!-- Material Type Multi-Select -->
|
||||
<mat-form-field appearance="outline" class="filter-field material-filter">
|
||||
<mat-label>Material</mat-label>
|
||||
<mat-select multiple
|
||||
[value]="selectedMaterials()"
|
||||
(selectionChange)="onMaterialChange($event.value)"
|
||||
aria-label="Filter by material type">
|
||||
@for (material of materialOptions(); track material) {
|
||||
<mat-option [value]="material">{{ material }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (selectedMaterials().length > 0) {
|
||||
<mat-chip-set class="selected-chips" matSuffix>
|
||||
@for (mat of selectedMaterials(); track mat) {
|
||||
<mat-chip (removed)="removeMaterial(mat)"
|
||||
class="filter-chip">
|
||||
<span>{{ mat }}</span>
|
||||
<mat-icon matChipRemove>cancel</mat-icon>
|
||||
</mat-chip>
|
||||
}
|
||||
</mat-chip-set>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<!-- Color Search -->
|
||||
<mat-form-field appearance="outline" class="filter-field color-filter">
|
||||
<mat-label>Color</mat-label>
|
||||
<input matInput
|
||||
type="text"
|
||||
[value]="colorSearch()"
|
||||
(input)="onColorSearchChange($any($event.target).value)"
|
||||
placeholder="Search color..."
|
||||
aria-label="Filter by color name" />
|
||||
@if (colorSearch().trim()) {
|
||||
<mat-icon matSuffix class="filter-active-icon">filter_list</mat-icon>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<!-- Low Stock Toggle -->
|
||||
<mat-checkbox [checked]="lowStockOnly()"
|
||||
(change)="onLowStockToggle($event.checked)"
|
||||
class="filter-checkbox"
|
||||
aria-label="Show low stock only"
|
||||
matTooltip="Show only spools at 25% or less remaining"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon class="checkbox-icon" [class.active]="lowStockOnly()">warning</mat-icon>
|
||||
Low Stock
|
||||
</mat-checkbox>
|
||||
|
||||
<!-- Active Only Toggle -->
|
||||
<mat-checkbox [checked]="activeOnly()"
|
||||
(change)="onActiveOnlyToggle($event.checked)"
|
||||
class="filter-checkbox"
|
||||
aria-label="Show active spools only"
|
||||
matTooltip="Show only spools currently in use"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon class="checkbox-icon" [class.active]="activeOnly()">check_circle</mat-icon>
|
||||
Active Only
|
||||
</mat-checkbox>
|
||||
|
||||
<!-- Clear All Filters -->
|
||||
@if (hasActiveFilters()) {
|
||||
<button mat-button
|
||||
class="clear-filters-btn"
|
||||
(click)="clearAll()"
|
||||
aria-label="Clear all filters"
|
||||
matTooltip="Remove all filters"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon>filter_alt_off</mat-icon>
|
||||
Clear
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@@ -1,134 +0,0 @@
|
||||
/**
|
||||
* Filament Filter Bar Styles
|
||||
* Responsive filter layout for kiosk and mobile
|
||||
*/
|
||||
|
||||
$spacing-unit: 8px;
|
||||
|
||||
.filament-filter-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit * 2;
|
||||
flex-wrap: wrap;
|
||||
padding: $spacing-unit * 2 0;
|
||||
margin-bottom: $spacing-unit * 2;
|
||||
}
|
||||
|
||||
// Form field sizing
|
||||
.filter-field {
|
||||
flex: 0 1 auto;
|
||||
min-width: 160px;
|
||||
|
||||
&.material-filter {
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
&.color-filter {
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
// Reduce vertical spacing inside filter fields
|
||||
.mat-mdc-form-field-subscript-wrapper {
|
||||
display: none; // No hint/error text needed for filters
|
||||
}
|
||||
}
|
||||
|
||||
// Selected material chips
|
||||
.selected-chips {
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.filter-chip {
|
||||
font-size: 12px !important;
|
||||
min-height: 24px !important;
|
||||
|
||||
mat-icon {
|
||||
font-size: 14px !important;
|
||||
width: 14px !important;
|
||||
height: 14px !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Active filter icon
|
||||
.filter-active-icon {
|
||||
color: var(--mat-sys-primary);
|
||||
font-size: 18px !important;
|
||||
width: 18px !important;
|
||||
height: 18px !important;
|
||||
}
|
||||
|
||||
// Checkbox styling
|
||||
.filter-checkbox {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
touch-action: manipulation; // Prevent zoom on double-tap
|
||||
|
||||
.checkbox-icon {
|
||||
font-size: 18px !important;
|
||||
width: 18px !important;
|
||||
height: 18px !important;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
transition: color 0.2s ease;
|
||||
|
||||
&.active {
|
||||
color: var(--mat-sys-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clear filters button
|
||||
.clear-filters-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px !important;
|
||||
width: 18px !important;
|
||||
height: 18px !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Responsive: stack filters vertically on small screens
|
||||
@media (max-width: 768px) {
|
||||
.filament-filter-bar {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: $spacing-unit;
|
||||
}
|
||||
|
||||
.filter-field {
|
||||
width: 100%;
|
||||
min-width: unset;
|
||||
|
||||
&.material-filter,
|
||||
&.color-filter {
|
||||
min-width: unset;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-checkbox {
|
||||
padding: $spacing-unit 0;
|
||||
}
|
||||
|
||||
.clear-filters-btn {
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
// Extra-small screens (phone portrait)
|
||||
@media (max-width: 480px) {
|
||||
.filament-filter-bar {
|
||||
padding: $spacing-unit 0;
|
||||
margin-bottom: $spacing-unit;
|
||||
}
|
||||
|
||||
.filter-checkbox {
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
EventEmitter,
|
||||
Input,
|
||||
Output,
|
||||
computed,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatChipsModule } from '@angular/material/chips';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import {
|
||||
Filament,
|
||||
StockLevel,
|
||||
classifyStockLevel,
|
||||
} from '../../models/filament.model';
|
||||
|
||||
/** Filter state emitted by the filament filter component */
|
||||
export interface FilamentFilterState {
|
||||
/** Selected material base names — empty means all */
|
||||
materialBaseNames: string[];
|
||||
|
||||
/** Color search text — empty string means all */
|
||||
colorSearch: string;
|
||||
|
||||
/** Whether to show only low/critical stock */
|
||||
lowStockOnly: boolean;
|
||||
|
||||
/** Whether to show only active spools */
|
||||
activeOnly: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* FilamentFilterComponent — Filter bar for the filament inventory list.
|
||||
*
|
||||
* Provides:
|
||||
* - Material type multi-select filter
|
||||
* - Color name text search
|
||||
* - Low stock toggle (shows only critical/low spools)
|
||||
* - Active-only toggle
|
||||
* - Clear all filters action
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-filament-filter',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
MatFormFieldModule,
|
||||
MatSelectModule,
|
||||
MatInputModule,
|
||||
MatCheckboxModule,
|
||||
MatIconModule,
|
||||
MatChipsModule,
|
||||
MatButtonModule,
|
||||
MatTooltipModule,
|
||||
],
|
||||
templateUrl: './filament-filter.component.html',
|
||||
styleUrl: './filament-filter.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class FilamentFilterComponent {
|
||||
/** Filament data input — used to derive material options */
|
||||
@Input() set filaments(value: Filament[]) {
|
||||
this._filaments.set(value);
|
||||
const materials = [...new Set(value.map((f) => f.materialBaseName))].sort();
|
||||
this.materialOptions.set(materials);
|
||||
}
|
||||
get filaments(): Filament[] {
|
||||
return this._filaments();
|
||||
}
|
||||
private readonly _filaments = signal<Filament[]>([]);
|
||||
|
||||
/** Available material base names derived from filament data */
|
||||
readonly materialOptions = signal<string[]>([]);
|
||||
|
||||
/** Selected material base names */
|
||||
readonly selectedMaterials = signal<string[]>([]);
|
||||
|
||||
/** Color search text */
|
||||
readonly colorSearch = signal('');
|
||||
|
||||
/** Low stock only toggle */
|
||||
readonly lowStockOnly = signal(false);
|
||||
|
||||
/** Active only toggle */
|
||||
readonly activeOnly = signal(false);
|
||||
|
||||
/** Computed: whether any filters are active */
|
||||
readonly hasActiveFilters = computed(
|
||||
() =>
|
||||
this.selectedMaterials().length > 0 ||
|
||||
this.colorSearch().trim().length > 0 ||
|
||||
this.lowStockOnly() ||
|
||||
this.activeOnly()
|
||||
);
|
||||
|
||||
/** Emits the current filter state whenever filters change */
|
||||
@Output() readonly filterChange = new EventEmitter<FilamentFilterState>();
|
||||
|
||||
/** Handle material selection change */
|
||||
onMaterialChange(selected: string[]): void {
|
||||
this.selectedMaterials.set(selected);
|
||||
this.emitFilterState();
|
||||
}
|
||||
|
||||
/** Handle color search input */
|
||||
onColorSearchChange(value: string): void {
|
||||
this.colorSearch.set(value);
|
||||
this.emitFilterState();
|
||||
}
|
||||
|
||||
/** Handle low stock toggle */
|
||||
onLowStockToggle(checked: boolean): void {
|
||||
this.lowStockOnly.set(checked);
|
||||
this.emitFilterState();
|
||||
}
|
||||
|
||||
/** Handle active-only toggle */
|
||||
onActiveOnlyToggle(checked: boolean): void {
|
||||
this.activeOnly.set(checked);
|
||||
this.emitFilterState();
|
||||
}
|
||||
|
||||
/** Remove a single material chip */
|
||||
removeMaterial(material: string): void {
|
||||
const updated = this.selectedMaterials().filter((m) => m !== material);
|
||||
this.selectedMaterials.set(updated);
|
||||
this.emitFilterState();
|
||||
}
|
||||
|
||||
/** Clear all filters */
|
||||
clearAll(): void {
|
||||
this.selectedMaterials.set([]);
|
||||
this.colorSearch.set('');
|
||||
this.lowStockOnly.set(false);
|
||||
this.activeOnly.set(false);
|
||||
this.emitFilterState();
|
||||
}
|
||||
|
||||
/** Emit the current filter state */
|
||||
private emitFilterState(): void {
|
||||
this.filterChange.emit({
|
||||
materialBaseNames: this.selectedMaterials(),
|
||||
colorSearch: this.colorSearch().trim().toLowerCase(),
|
||||
lowStockOnly: this.lowStockOnly(),
|
||||
activeOnly: this.activeOnly(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
<!-- Filament Inventory Table — with filters and low stock indicators -->
|
||||
<div class="filament-table-container" role="region" aria-label="Filament inventory">
|
||||
|
||||
<!-- Filter Bar -->
|
||||
<app-filament-filter
|
||||
[filaments]="allFilaments()"
|
||||
(filterChange)="onFilterChange($event)"
|
||||
aria-label="Filter filament inventory" />
|
||||
|
||||
<!-- Low Stock Alert Banner — shown when critical or low stock spools exist -->
|
||||
@if (criticalCount() > 0) {
|
||||
<div class="alert-banner critical" role="alert">
|
||||
<mat-icon aria-hidden="true">error</mat-icon>
|
||||
<span>{{ criticalCount() }} spool{{ criticalCount() > 1 ? 's' : '' }} critically low (≤10% remaining)</span>
|
||||
</div>
|
||||
} @else if (lowStockCount() > 0) {
|
||||
<div class="alert-banner low" role="alert">
|
||||
<mat-icon aria-hidden="true">warning</mat-icon>
|
||||
<span>{{ lowStockCount() }} spool{{ lowStockCount() > 1 ? 's' : '' }} running low (≤25% remaining)</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Filament Table -->
|
||||
<table mat-table
|
||||
[dataSource]="filteredFilaments()"
|
||||
matSort
|
||||
(matSortChange)="sortData($event)"
|
||||
class="filament-table"
|
||||
aria-label="Filament inventory table">
|
||||
|
||||
<!-- Color Column -->
|
||||
<ng-container matColumnDef="color">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="color">Color</th>
|
||||
<td mat-cell *matCellDef="let filament">
|
||||
<span class="color-swatch"
|
||||
[style.background-color]="filament.colorHex"
|
||||
[matTooltip]="filament.colorName"
|
||||
matTooltipPosition="after"
|
||||
[attr.aria-label]="filament.colorName">
|
||||
</span>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Material Column -->
|
||||
<ng-container matColumnDef="material">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="material">Material</th>
|
||||
<td mat-cell *matCellDef="let filament">
|
||||
<span class="material-name">{{ filament.materialBaseName }}</span>
|
||||
@if (filament.materialModifierName) {
|
||||
<span class="material-modifier"> {{ filament.materialModifierName }}</span>
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Brand Column -->
|
||||
<ng-container matColumnDef="brand">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="brand">Brand</th>
|
||||
<td mat-cell *matCellDef="let filament">{{ filament.brand }}</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Serial Column -->
|
||||
<ng-container matColumnDef="serial">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="serial">Serial</th>
|
||||
<td mat-cell *matCellDef="let filament" class="serial-cell">{{ filament.spoolSerial }}</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Remaining Weight Column -->
|
||||
<ng-container matColumnDef="remaining">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="remaining">Remaining</th>
|
||||
<td mat-cell *matCellDef="let filament">
|
||||
<div class="remaining-cell">
|
||||
<span class="remaining-text">
|
||||
{{ formatWeight(filament.weightRemainingGrams) }} / {{ formatWeight(filament.weightTotalGrams) }}
|
||||
</span>
|
||||
<mat-progress-bar
|
||||
mode="determinate"
|
||||
[value]="getRemainingPercent(filament)"
|
||||
[ngClass]="classifyStockLevel(filament)"
|
||||
[matTooltip]="getRemainingPercent(filament).toFixed(0) + '% remaining'"
|
||||
matTooltipPosition="below">
|
||||
</mat-progress-bar>
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Cost Column -->
|
||||
<ng-container matColumnDef="cost">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="cost">Cost</th>
|
||||
<td mat-cell *matCellDef="let filament">
|
||||
<div class="cost-cell">
|
||||
@if (filament.purchasePrice !== null) {
|
||||
<span class="cost-price">{{ formatCurrency(filament.purchasePrice) }}</span>
|
||||
@let cpg = getCostPerGram(filament);
|
||||
@if (cpg !== null) {
|
||||
<span class="cost-per-gram">${{ cpg.toFixed(2) }}/g</span>
|
||||
}
|
||||
} @else {
|
||||
<span class="cost-unknown">—</span>
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Usage Column -->
|
||||
<ng-container matColumnDef="usage">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="usage">Usage</th>
|
||||
<td mat-cell *matCellDef="let filament">
|
||||
<div class="usage-cell">
|
||||
<span class="usage-grams">{{ formatWeight(getGramsUsed(filament)) }} used</span>
|
||||
<span class="usage-remaining">{{ formatWeight(filament.weightRemainingGrams) }} left</span>
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Stock Level Indicator Column -->
|
||||
<ng-container matColumnDef="stockLevel">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="stockLevel">Stock</th>
|
||||
<td mat-cell *matCellDef="let filament">
|
||||
@let level = classifyStockLevel(filament);
|
||||
<mat-chip-set aria-label="Stock level">
|
||||
<mat-chip
|
||||
[ngClass]="level"
|
||||
[matTooltip]="stockLevelLabel(level) + ' — ' + getRemainingPercent(filament).toFixed(0) + '% remaining'"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon matChipStart [ngClass]="level">{{ stockLevelIcon(level) }}</mat-icon>
|
||||
<span>{{ stockLevelLabel(level) }}</span>
|
||||
</mat-chip>
|
||||
</mat-chip-set>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Status Column -->
|
||||
<ng-container matColumnDef="status">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header="status">Status</th>
|
||||
<td mat-cell *matCellDef="let filament">
|
||||
<span class="status-badge"
|
||||
[class.active]="filament.isActive"
|
||||
[class.inactive]="!filament.isActive">
|
||||
{{ filament.isActive ? 'Active' : 'Inactive' }}
|
||||
</span>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<tr mat-header-row *matHeaderRowDef="columns()"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: columns();"
|
||||
[class.row-critical]="classifyStockLevel(row) === 'critical'"
|
||||
[class.row-low]="classifyStockLevel(row) === 'low'">
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<!-- Filtered empty state -->
|
||||
@if (filteredFilaments().length === 0 && filaments().length > 0) {
|
||||
<div class="empty-state" role="status">
|
||||
<mat-icon aria-hidden="true">filter_alt_off</mat-icon>
|
||||
<p>No filaments match the current filters</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- No data empty state -->
|
||||
@if (filaments().length === 0) {
|
||||
<div class="empty-state" role="status">
|
||||
<mat-icon aria-hidden="true">inventory_2</mat-icon>
|
||||
<p>No filament spools found</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@@ -1,301 +0,0 @@
|
||||
/**
|
||||
* Filament Table Component Styles
|
||||
* Touch-optimized for kiosk (Raspberry Pi 5) and mobile PWA
|
||||
* Low stock indicators use high-contrast colors for workshop visibility
|
||||
*/
|
||||
|
||||
// Touch-optimized sizing
|
||||
$touch-target-min: 48px;
|
||||
$spacing-unit: 8px;
|
||||
|
||||
// Stock level colors — high contrast, accessible
|
||||
$color-critical: #ef4444; // Red — critically low
|
||||
$color-low: #f59e0b; // Amber — running low
|
||||
$color-moderate: #3b82f6; // Blue — moderate
|
||||
$color-healthy: #22c55e; // Green — healthy/OK
|
||||
$color-active: #22c55e; // Green — active spool
|
||||
$color-inactive: #94a3b8; // Gray — inactive spool
|
||||
|
||||
.filament-table-container {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
// Alert banner for low stock warnings
|
||||
.alert-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit;
|
||||
padding: $spacing-unit * 1.5 $spacing-unit * 2;
|
||||
border-radius: 8px;
|
||||
margin-bottom: $spacing-unit * 2;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
|
||||
mat-icon {
|
||||
font-size: 20px !important;
|
||||
width: 20px !important;
|
||||
height: 20px !important;
|
||||
}
|
||||
|
||||
&.critical {
|
||||
background-color: rgba($color-critical, 0.12);
|
||||
color: $color-critical;
|
||||
border: 1px solid rgba($color-critical, 0.3);
|
||||
}
|
||||
|
||||
&.low {
|
||||
background-color: rgba($color-low, 0.12);
|
||||
color: $color-low;
|
||||
border: 1px solid rgba($color-low, 0.3);
|
||||
}
|
||||
}
|
||||
|
||||
// Table styling
|
||||
.filament-table {
|
||||
width: 100%;
|
||||
min-width: 900px;
|
||||
|
||||
th {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
}
|
||||
|
||||
td {
|
||||
font-size: 14px;
|
||||
padding: 12px 16px !important;
|
||||
min-height: $touch-target-min;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
padding: 8px 12px !important;
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
// Row highlight for low stock
|
||||
.mat-mdc-row {
|
||||
transition: background-color 0.2s ease;
|
||||
}
|
||||
|
||||
&.row-critical {
|
||||
background-color: rgba($color-critical, 0.06) !important;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba($color-critical, 0.1) !important;
|
||||
}
|
||||
}
|
||||
|
||||
&.row-low {
|
||||
background-color: rgba($color-low, 0.06) !important;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba($color-low, 0.1) !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Color swatch
|
||||
.color-swatch {
|
||||
display: inline-block;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid rgba(0, 0, 0, 0.12);
|
||||
vertical-align: middle;
|
||||
cursor: default;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
// Material name
|
||||
.material-name {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.material-modifier {
|
||||
font-size: 12px;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
// Serial cell — monospace
|
||||
.serial-cell {
|
||||
font-family: 'JetBrains Mono', 'Roboto Mono', monospace;
|
||||
font-size: 13px;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
// Cost cell
|
||||
.cost-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 80px;
|
||||
|
||||
.cost-price {
|
||||
font-weight: 600;
|
||||
color: var(--mat-sys-on-surface);
|
||||
}
|
||||
|
||||
.cost-per-gram {
|
||||
font-size: 11px;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.cost-unknown {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
|
||||
// Usage cell
|
||||
.usage-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 100px;
|
||||
|
||||
.usage-grams {
|
||||
font-weight: 500;
|
||||
color: var(--mat-sys-on-surface);
|
||||
}
|
||||
|
||||
.usage-remaining {
|
||||
font-size: 12px;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
}
|
||||
}
|
||||
|
||||
// Remaining weight cell
|
||||
.remaining-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 120px;
|
||||
|
||||
.remaining-text {
|
||||
font-size: 13px;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
}
|
||||
}
|
||||
|
||||
// Progress bar stock level variants
|
||||
mat-progress-bar {
|
||||
&.critical {
|
||||
--mat-progress-bar-active-indicator-color: #{$color-critical};
|
||||
}
|
||||
|
||||
&.low {
|
||||
--mat-progress-bar-active-indicator-color: #{$color-low};
|
||||
}
|
||||
|
||||
&.moderate {
|
||||
--mat-progress-bar-active-indicator-color: #{$color-moderate};
|
||||
}
|
||||
|
||||
&.healthy {
|
||||
--mat-progress-bar-active-indicator-color: #{$color-healthy};
|
||||
}
|
||||
}
|
||||
|
||||
// Stock level chip variants
|
||||
mat-chip {
|
||||
min-height: 32px !important;
|
||||
font-size: 12px !important;
|
||||
|
||||
&.critical {
|
||||
background-color: rgba($color-critical, 0.15) !important;
|
||||
color: $color-critical;
|
||||
|
||||
mat-icon {
|
||||
color: $color-critical;
|
||||
}
|
||||
}
|
||||
|
||||
&.low {
|
||||
background-color: rgba($color-low, 0.15) !important;
|
||||
color: $color-low;
|
||||
|
||||
mat-icon {
|
||||
color: $color-low;
|
||||
}
|
||||
}
|
||||
|
||||
&.moderate {
|
||||
background-color: rgba($color-moderate, 0.1) !important;
|
||||
color: $color-moderate;
|
||||
|
||||
mat-icon {
|
||||
color: $color-moderate;
|
||||
}
|
||||
}
|
||||
|
||||
&.healthy {
|
||||
background-color: rgba($color-healthy, 0.1) !important;
|
||||
color: $color-healthy;
|
||||
|
||||
mat-icon {
|
||||
color: $color-healthy;
|
||||
}
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 16px !important;
|
||||
width: 16px !important;
|
||||
height: 16px !important;
|
||||
margin-right: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
// Status badge
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
|
||||
&.active {
|
||||
background-color: rgba($color-active, 0.12);
|
||||
color: $color-active;
|
||||
}
|
||||
|
||||
&.inactive {
|
||||
background-color: rgba($color-inactive, 0.12);
|
||||
color: $color-inactive;
|
||||
}
|
||||
}
|
||||
|
||||
// Empty state
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 48px $spacing-unit * 2;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
|
||||
mat-icon {
|
||||
font-size: 48px !important;
|
||||
width: 48px !important;
|
||||
height: 48px !important;
|
||||
opacity: 0.4;
|
||||
margin-bottom: $spacing-unit * 2;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 16px;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
Filament,
|
||||
StockLevel,
|
||||
getRemainingPercent,
|
||||
classifyStockLevel,
|
||||
} from '../../models/filament.model';
|
||||
|
||||
/** Create a test filament with defaults — override specific fields */
|
||||
function createFilament(overrides: Partial<Filament> = {}): Filament {
|
||||
return {
|
||||
id: '00000000-0000-0000-0000-000000000001',
|
||||
materialBaseId: '10000000-0000-0000-0000-000000000001',
|
||||
materialBaseName: 'PLA',
|
||||
materialFinishId: '20000000-0000-0000-0000-000000000001',
|
||||
materialFinishName: 'Basic',
|
||||
materialModifierId: null,
|
||||
materialModifierName: null,
|
||||
brand: 'Bambu Lab',
|
||||
colorName: 'White',
|
||||
colorHex: '#FFFFFF',
|
||||
weightTotalGrams: 1000,
|
||||
weightRemainingGrams: 750,
|
||||
filamentDiameterMm: 1.75,
|
||||
spoolSerial: 'SN-001',
|
||||
purchasePrice: null,
|
||||
purchaseDate: null,
|
||||
isActive: true,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
qrCodeUrl: '',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('getRemainingPercent', () => {
|
||||
it('should return correct percentage', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 1000, weightRemainingGrams: 250 });
|
||||
expect(getRemainingPercent(filament)).toBe(25);
|
||||
});
|
||||
|
||||
it('should return 0 when total weight is 0', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 0, weightRemainingGrams: 0 });
|
||||
expect(getRemainingPercent(filament)).toBe(0);
|
||||
});
|
||||
|
||||
it('should cap at 100%', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 100, weightRemainingGrams: 200 });
|
||||
expect(getRemainingPercent(filament)).toBe(100);
|
||||
});
|
||||
|
||||
it('should floor at 0%', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 100, weightRemainingGrams: -10 });
|
||||
expect(getRemainingPercent(filament)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('classifyStockLevel', () => {
|
||||
it('should classify as critical when ≤10%', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 1000, weightRemainingGrams: 50 });
|
||||
expect(classifyStockLevel(filament)).toBe('critical');
|
||||
});
|
||||
|
||||
it('should classify as critical at exactly 10%', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 1000, weightRemainingGrams: 100 });
|
||||
expect(classifyStockLevel(filament)).toBe('critical');
|
||||
});
|
||||
|
||||
it('should classify as low when ≤25%', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 1000, weightRemainingGrams: 200 });
|
||||
expect(classifyStockLevel(filament)).toBe('low');
|
||||
});
|
||||
|
||||
it('should classify as moderate when ≤50%', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 1000, weightRemainingGrams: 400 });
|
||||
expect(classifyStockLevel(filament)).toBe('moderate');
|
||||
});
|
||||
|
||||
it('should classify as healthy when >50%', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 1000, weightRemainingGrams: 750 });
|
||||
expect(classifyStockLevel(filament)).toBe('healthy');
|
||||
});
|
||||
|
||||
it('should classify 0 grams remaining as critical', () => {
|
||||
const filament = createFilament({ weightTotalGrams: 1000, weightRemainingGrams: 0 });
|
||||
expect(classifyStockLevel(filament)).toBe('critical');
|
||||
});
|
||||
});
|
||||
@@ -1,304 +0,0 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
Input,
|
||||
OnInit,
|
||||
computed,
|
||||
inject,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { FilamentService } from '../../services/filament.service';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { MatChipsModule } from '@angular/material/chips';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { MatSortModule, Sort } from '@angular/material/sort';
|
||||
import { FilamentFilterComponent, FilamentFilterState } from '../filament-filter/filament-filter.component';
|
||||
import {
|
||||
Filament,
|
||||
StockLevel,
|
||||
getRemainingPercent,
|
||||
classifyStockLevel,
|
||||
} from '../../models/filament.model';
|
||||
|
||||
/** Display column definitions for the filament table */
|
||||
export type FilamentColumn =
|
||||
| 'color'
|
||||
| 'material'
|
||||
| 'brand'
|
||||
| 'serial'
|
||||
| 'remaining'
|
||||
| 'cost'
|
||||
| 'usage'
|
||||
| 'stockLevel'
|
||||
| 'status';
|
||||
|
||||
@Component({
|
||||
selector: 'app-filament-table',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatTableModule,
|
||||
MatChipsModule,
|
||||
MatIconModule,
|
||||
MatProgressBarModule,
|
||||
MatTooltipModule,
|
||||
MatSortModule,
|
||||
FilamentFilterComponent,
|
||||
],
|
||||
templateUrl: './filament-table.component.html',
|
||||
styleUrl: './filament-table.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class FilamentTableComponent implements OnInit {
|
||||
private readonly filamentService = inject(FilamentService);
|
||||
|
||||
/** Filament data — reactive signal driven by FilamentService */
|
||||
readonly filaments = this.filamentService.filaments;
|
||||
|
||||
/** Columns to display — defaults to all columns */
|
||||
@Input()
|
||||
set displayedColumns(cols: FilamentColumn[]) {
|
||||
this._displayedColumns.set(cols);
|
||||
}
|
||||
get displayedColumns(): FilamentColumn[] {
|
||||
return this._displayedColumns();
|
||||
}
|
||||
private readonly _displayedColumns = signal<FilamentColumn[]>([
|
||||
'color',
|
||||
'material',
|
||||
'brand',
|
||||
'serial',
|
||||
'remaining',
|
||||
'cost',
|
||||
'usage',
|
||||
'stockLevel',
|
||||
'status',
|
||||
]);
|
||||
|
||||
/** Default columns for template binding */
|
||||
readonly columns = this._displayedColumns;
|
||||
|
||||
/** Current filter state */
|
||||
readonly filterState = signal<FilamentFilterState>({
|
||||
materialBaseNames: [],
|
||||
colorSearch: '',
|
||||
lowStockOnly: false,
|
||||
activeOnly: false,
|
||||
});
|
||||
|
||||
/** Sorted filament data */
|
||||
readonly sortedFilaments = signal<Filament[]>([]);
|
||||
|
||||
/** Computed: filtered + sorted filament data for display */
|
||||
readonly filteredFilaments = computed(() => {
|
||||
const data = this.sortedFilaments();
|
||||
const filters = this.filterState();
|
||||
return data.filter((f) => this.matchesFilter(f, filters));
|
||||
});
|
||||
|
||||
/** Computed: count of low/critical spools */
|
||||
readonly lowStockCount = computed(() =>
|
||||
this.filaments().filter(
|
||||
(f) => classifyStockLevel(f) === 'low' || classifyStockLevel(f) === 'critical'
|
||||
).length
|
||||
);
|
||||
|
||||
/** Computed: count of critical spools */
|
||||
readonly criticalCount = computed(() =>
|
||||
this.filaments().filter((f) => classifyStockLevel(f) === 'critical').length
|
||||
);
|
||||
|
||||
ngOnInit(): void {
|
||||
// Initialize sorted data from FilamentService
|
||||
this.sortedFilaments.set([...this.filaments()]);
|
||||
}
|
||||
|
||||
/** Update filament data — called externally or from a SignalR handler */
|
||||
updateFilaments(data: Filament[]): void {
|
||||
this.filamentService.setFilaments(data);
|
||||
this.sortedFilaments.set([...data]);
|
||||
}
|
||||
|
||||
/** All filament data — for the filter component to derive material options */
|
||||
readonly allFilaments = this.filaments;
|
||||
|
||||
/** Handle sort changes from MatSort */
|
||||
sortData(sort: Sort): void {
|
||||
const data = [...this.filaments()];
|
||||
if (!sort.active || sort.direction === '') {
|
||||
this.sortedFilaments.set(data);
|
||||
return;
|
||||
}
|
||||
const sorted = data.sort((a, b) => {
|
||||
const isAsc = sort.direction === 'asc';
|
||||
switch (sort.active as FilamentColumn) {
|
||||
case 'material':
|
||||
return compare(a.materialBaseName, b.materialBaseName, isAsc);
|
||||
case 'brand':
|
||||
return compare(a.brand, b.brand, isAsc);
|
||||
case 'serial':
|
||||
return compare(a.spoolSerial, b.spoolSerial, isAsc);
|
||||
case 'remaining':
|
||||
return compare(
|
||||
getRemainingPercent(a),
|
||||
getRemainingPercent(b),
|
||||
isAsc
|
||||
);
|
||||
case 'cost':
|
||||
return compare(
|
||||
a.purchasePrice ?? 0,
|
||||
b.purchasePrice ?? 0,
|
||||
isAsc
|
||||
);
|
||||
case 'usage':
|
||||
return compare(
|
||||
a.weightTotalGrams - a.weightRemainingGrams,
|
||||
b.weightTotalGrams - b.weightRemainingGrams,
|
||||
isAsc
|
||||
);
|
||||
case 'stockLevel':
|
||||
return compare(
|
||||
stockLevelOrder(classifyStockLevel(a)),
|
||||
stockLevelOrder(classifyStockLevel(b)),
|
||||
isAsc
|
||||
);
|
||||
case 'status':
|
||||
return compare(
|
||||
a.isActive ? 0 : 1,
|
||||
b.isActive ? 0 : 1,
|
||||
isAsc
|
||||
);
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
this.sortedFilaments.set(sorted);
|
||||
}
|
||||
|
||||
/** Handle filter changes from FilamentFilterComponent */
|
||||
onFilterChange(state: FilamentFilterState): void {
|
||||
this.filterState.set(state);
|
||||
}
|
||||
|
||||
/** Check if a filament matches the current filter state */
|
||||
private matchesFilter(filament: Filament, filters: FilamentFilterState): boolean {
|
||||
// Material filter — empty means all
|
||||
if (
|
||||
filters.materialBaseNames.length > 0 &&
|
||||
!filters.materialBaseNames.includes(filament.materialBaseName)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Color search — empty means all
|
||||
if (
|
||||
filters.colorSearch &&
|
||||
!filament.colorName.toLowerCase().includes(filters.colorSearch) &&
|
||||
!filament.colorHex.toLowerCase().includes(filters.colorSearch)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Low stock filter — show only critical/low
|
||||
if (filters.lowStockOnly) {
|
||||
const level = classifyStockLevel(filament);
|
||||
if (level !== 'critical' && level !== 'low') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Active only filter
|
||||
if (filters.activeOnly && !filament.isActive) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Template helper: get remaining percent */
|
||||
getRemainingPercent = getRemainingPercent;
|
||||
|
||||
/** Template helper: classify stock level */
|
||||
classifyStockLevel = classifyStockLevel;
|
||||
|
||||
/** Template helper: stock level icon */
|
||||
stockLevelIcon(level: StockLevel): string {
|
||||
switch (level) {
|
||||
case 'critical':
|
||||
return 'error';
|
||||
case 'low':
|
||||
return 'warning';
|
||||
case 'moderate':
|
||||
return 'info';
|
||||
case 'healthy':
|
||||
return 'check_circle';
|
||||
}
|
||||
}
|
||||
|
||||
/** Template helper: stock level label */
|
||||
stockLevelLabel(level: StockLevel): string {
|
||||
switch (level) {
|
||||
case 'critical':
|
||||
return 'Critical';
|
||||
case 'low':
|
||||
return 'Low';
|
||||
case 'moderate':
|
||||
return 'Moderate';
|
||||
case 'healthy':
|
||||
return 'Healthy';
|
||||
}
|
||||
}
|
||||
|
||||
/** Template helper: format remaining weight */
|
||||
formatWeight(grams: number): string {
|
||||
if (grams >= 1000) {
|
||||
return `${(grams / 1000).toFixed(1)}kg`;
|
||||
}
|
||||
return `${Math.round(grams)}g`;
|
||||
}
|
||||
|
||||
/** Template helper: format currency */
|
||||
formatCurrency(value: number): string {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
/** Template helper: compute cost per gram for a filament */
|
||||
getCostPerGram(filament: Filament): number | null {
|
||||
if (filament.purchasePrice === null || filament.purchasePrice === 0 || filament.weightTotalGrams <= 0) {
|
||||
return null;
|
||||
}
|
||||
return filament.purchasePrice / filament.weightTotalGrams;
|
||||
}
|
||||
|
||||
/** Template helper: compute grams used for a filament */
|
||||
getGramsUsed(filament: Filament): number {
|
||||
return filament.weightTotalGrams - filament.weightRemainingGrams;
|
||||
}
|
||||
}
|
||||
|
||||
/** Compare helper for sorting */
|
||||
function compare(a: number | string, b: number | string, isAsc: boolean): number {
|
||||
return (a < b ? -1 : a > b ? 1 : 0) * (isAsc ? 1 : -1);
|
||||
}
|
||||
|
||||
/** Stock level sort order (critical=0, healthy=3) */
|
||||
function stockLevelOrder(level: StockLevel): number {
|
||||
switch (level) {
|
||||
case 'critical':
|
||||
return 0;
|
||||
case 'low':
|
||||
return 1;
|
||||
case 'moderate':
|
||||
return 2;
|
||||
case 'healthy':
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
<!-- Inventory Dashboard Summary — filament metrics at a glance -->
|
||||
<section class="inventory-summary" role="region" aria-label="Inventory summary">
|
||||
|
||||
<!-- Loading State -->
|
||||
@if (loading()) {
|
||||
<div class="summary-loading" role="status" aria-live="polite">
|
||||
<mat-icon aria-hidden="true" class="spin">sync</mat-icon>
|
||||
<span>Loading inventory...</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Error State -->
|
||||
@else if (error()) {
|
||||
<div class="summary-error" role="alert" aria-live="assertive">
|
||||
<mat-icon aria-hidden="true">error_outline</mat-icon>
|
||||
<span>{{ error() }}</span>
|
||||
<button class="retry-btn" (click)="refresh()" aria-label="Retry loading inventory">
|
||||
<mat-icon aria-hidden="true">refresh</mat-icon>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Loaded State -->
|
||||
@else {
|
||||
<!-- Health Status Indicator -->
|
||||
<div class="summary-item health-status"
|
||||
[class]="healthClass()"
|
||||
[matTooltip]="healthLabel()"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true">
|
||||
@switch (healthClass()) {
|
||||
@case ('critical') { error }
|
||||
@case ('low') { warning }
|
||||
@default { check_circle }
|
||||
}
|
||||
</mat-icon>
|
||||
<span class="health-text">{{ healthLabel() }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Total Spool Count -->
|
||||
<div class="summary-item metric-card"
|
||||
matTooltip="Total filament spools in inventory"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true" class="metric-icon">inventory_2</mat-icon>
|
||||
<div class="metric-content">
|
||||
<span class="metric-value">{{ totalCount() }}</span>
|
||||
<span class="metric-label">Total Spools</span>
|
||||
</div>
|
||||
@if (activeCount() < totalCount()) {
|
||||
<span class="metric-detail">{{ activeCount() }} active</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Low Stock Count -->
|
||||
<div class="summary-item metric-card"
|
||||
[class.has-alert]="hasLowStock()"
|
||||
[class.has-critical]="hasCritical()"
|
||||
[matTooltip]="hasCritical()
|
||||
? criticalCount() + ' critical, ' + (lowStockCount() - criticalCount()) + ' low'
|
||||
: hasLowStock()
|
||||
? lowStockCount() + ' spools at or below 25% remaining'
|
||||
: 'All spools above 25% remaining'"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true" class="metric-icon">
|
||||
@if (hasCritical()) { error }
|
||||
@else if (hasLowStock()) { warning }
|
||||
@else { check_circle }
|
||||
</mat-icon>
|
||||
<div class="metric-content">
|
||||
<span class="metric-value">{{ lowStockCount() }}</span>
|
||||
<span class="metric-label">Low Stock</span>
|
||||
</div>
|
||||
@if (hasCritical()) {
|
||||
<span class="metric-detail critical-detail">{{ criticalCount() }} critical</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Estimated Total Value -->
|
||||
<div class="summary-item metric-card"
|
||||
matTooltip="Estimated total value of active spools"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true" class="metric-icon">payments</mat-icon>
|
||||
<div class="metric-content">
|
||||
<span class="metric-value">{{ formatCurrency(totalValue()) }}</span>
|
||||
<span class="metric-label">Est. Value</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Average Cost per Gram -->
|
||||
@if (avgCostPerGram() !== null) {
|
||||
<div class="summary-item metric-card"
|
||||
matTooltip="Average cost per gram across priced, active spools"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true" class="metric-icon">scale</mat-icon>
|
||||
<div class="metric-content">
|
||||
<span class="metric-value">${{ avgCostPerGram()!.toFixed(2) }}/g</span>
|
||||
<span class="metric-label">Avg Cost/g</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Total Usage -->
|
||||
<div class="summary-item metric-card"
|
||||
matTooltip="Total filament used across all spools"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true" class="metric-icon">trending_down</mat-icon>
|
||||
<div class="metric-content">
|
||||
<span class="metric-value">{{ formatWeight(totalGramsUsed()) }}</span>
|
||||
<span class="metric-label">Total Used</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Estimated Used Value -->
|
||||
@if (estimatedUsedValue() !== null) {
|
||||
<div class="summary-item metric-card"
|
||||
matTooltip="Estimated value of filament consumed"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true" class="metric-icon">receipt_long</mat-icon>
|
||||
<div class="metric-content">
|
||||
<span class="metric-value">{{ formatCurrency(estimatedUsedValue()!) }}</span>
|
||||
<span class="metric-label">Used Value</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Overall Remaining Stock Bar -->
|
||||
<div class="summary-item metric-card stock-bar-card"
|
||||
matTooltip="{{ formatWeight(totalRemainingGrams()) }} of {{ formatWeight(totalCapacityGrams()) }} remaining"
|
||||
matTooltipPosition="below">
|
||||
<mat-icon aria-hidden="true" class="metric-icon">line_weight</mat-icon>
|
||||
<div class="metric-content stock-bar-content">
|
||||
<div class="stock-bar-header">
|
||||
<span class="metric-value">{{ overallRemainingPercent() }}%</span>
|
||||
<span class="metric-label">Remaining</span>
|
||||
</div>
|
||||
<mat-progress-bar
|
||||
mode="determinate"
|
||||
[value]="overallRemainingPercent()"
|
||||
[ngClass]="healthClass()">
|
||||
</mat-progress-bar>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
@@ -1,257 +0,0 @@
|
||||
/**
|
||||
* Inventory Summary Component Styles
|
||||
* Touch-optimized for kiosk (Raspberry Pi 5) and mobile PWA
|
||||
* Matches the existing dark theme from app.scss
|
||||
*/
|
||||
|
||||
// Touch-optimized sizing
|
||||
$touch-target-min: 48px;
|
||||
$kiosk-font-primary: 24px;
|
||||
$mobile-font-primary: 18px;
|
||||
$spacing-unit: 8px;
|
||||
|
||||
// Status colors — high contrast for workshop/bright environments
|
||||
$color-healthy: #4ade70; // Green
|
||||
$color-low: #fbbf24; // Amber/Yellow
|
||||
$color-critical: #f87171; // Red
|
||||
$color-bg: #1a1a2e; // Matches app.scss
|
||||
$color-text: #e0e0e0;
|
||||
$color-text-muted: rgba(255, 255, 255, 0.7);
|
||||
$color-card-bg: rgba(255, 255, 255, 0.05);
|
||||
$color-card-border: rgba(255, 255, 255, 0.1);
|
||||
|
||||
.inventory-summary {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: $spacing-unit * 2;
|
||||
padding: $spacing-unit * 2;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: thin;
|
||||
|
||||
@media (max-width: 600px) {
|
||||
flex-wrap: wrap;
|
||||
padding: $spacing-unit;
|
||||
gap: $spacing-unit;
|
||||
}
|
||||
}
|
||||
|
||||
// Health status indicator
|
||||
.health-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit;
|
||||
padding: $spacing-unit $spacing-unit * 2;
|
||||
border-radius: 24px;
|
||||
min-height: $touch-target-min;
|
||||
white-space: nowrap;
|
||||
transition: background-color 0.3s ease;
|
||||
|
||||
&.healthy {
|
||||
background-color: rgba($color-healthy, 0.15);
|
||||
color: $color-healthy;
|
||||
}
|
||||
|
||||
&.low {
|
||||
background-color: rgba($color-low, 0.15);
|
||||
color: $color-low;
|
||||
}
|
||||
|
||||
&.critical {
|
||||
background-color: rgba($color-critical, 0.15);
|
||||
color: $color-critical;
|
||||
}
|
||||
|
||||
.health-text {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 20px !important;
|
||||
width: 20px !important;
|
||||
height: 20px !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Metric card
|
||||
.metric-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit;
|
||||
padding: $spacing-unit $spacing-unit * 2;
|
||||
background-color: $color-card-bg;
|
||||
border: 1px solid $color-card-border;
|
||||
border-radius: 12px;
|
||||
min-height: $touch-target-min;
|
||||
white-space: nowrap;
|
||||
transition: border-color 0.2s ease, background-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
background-color: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
padding: $spacing-unit;
|
||||
}
|
||||
|
||||
&.has-alert {
|
||||
border-color: rgba($color-low, 0.4);
|
||||
}
|
||||
|
||||
&.has-critical {
|
||||
border-color: rgba($color-critical, 0.5);
|
||||
background-color: rgba($color-critical, 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
.metric-icon {
|
||||
color: $color-text-muted;
|
||||
font-size: 22px !important;
|
||||
width: 22px !important;
|
||||
height: 22px !important;
|
||||
|
||||
.has-alert & {
|
||||
color: $color-low;
|
||||
}
|
||||
|
||||
.has-critical & {
|
||||
color: $color-critical;
|
||||
}
|
||||
}
|
||||
|
||||
.metric-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.metric-value {
|
||||
font-size: $kiosk-font-primary;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
color: $color-text;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
font-size: $mobile-font-primary;
|
||||
}
|
||||
}
|
||||
|
||||
.metric-label {
|
||||
font-size: 11px;
|
||||
color: $color-text-muted;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
.metric-detail {
|
||||
font-size: 11px;
|
||||
color: $color-text-muted;
|
||||
margin-left: $spacing-unit;
|
||||
|
||||
&.critical-detail {
|
||||
color: $color-critical;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
// Stock bar card
|
||||
.stock-bar-card {
|
||||
flex: 1 1 200px;
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
.stock-bar-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.stock-bar-header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: $spacing-unit;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
// Progress bar color classes
|
||||
::ng-deep .mat-mdc-progress-bar {
|
||||
&.healthy .mdc-linear-progress__bar-inner {
|
||||
background-color: $color-healthy !important;
|
||||
}
|
||||
|
||||
&.low .mdc-linear-progress__bar-inner {
|
||||
background-color: $color-low !important;
|
||||
}
|
||||
|
||||
&.critical .mdc-linear-progress__bar-inner {
|
||||
background-color: $color-critical !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Loading state
|
||||
.summary-loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit;
|
||||
padding: $spacing-unit * 2;
|
||||
color: $color-text-muted;
|
||||
font-size: 14px;
|
||||
|
||||
.spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
// Error state
|
||||
.summary-error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-unit;
|
||||
padding: $spacing-unit * 2;
|
||||
background-color: rgba($color-critical, 0.1);
|
||||
border: 1px solid rgba($color-critical, 0.3);
|
||||
border-radius: 12px;
|
||||
color: $color-critical;
|
||||
font-size: 14px;
|
||||
|
||||
.retry-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
background: transparent;
|
||||
border: 1px solid rgba($color-critical, 0.4);
|
||||
color: $color-critical;
|
||||
padding: 4px 12px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
min-height: $touch-target-min - 8px;
|
||||
transition: background-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba($color-critical, 0.15);
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 16px !important;
|
||||
width: 16px !important;
|
||||
height: 16px !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Summary item base
|
||||
.summary-item {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@@ -1,207 +0,0 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
OnDestroy,
|
||||
OnInit,
|
||||
computed,
|
||||
inject,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatChipsModule } from '@angular/material/chips';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { FilamentService } from '../../services/filament.service';
|
||||
import {
|
||||
classifyStockLevel,
|
||||
} from '../../models/filament.model';
|
||||
import { Subscription } from 'rxjs';
|
||||
|
||||
/**
|
||||
* Inventory Dashboard Summary — shows filament inventory at a glance.
|
||||
*
|
||||
* Displays:
|
||||
* - Total filament spool count
|
||||
* - Low stock count (spools ≤25% remaining, i.e. "low" or "critical")
|
||||
* - Estimated total filament value (sum of purchase prices for active spools)
|
||||
*
|
||||
* Data is sourced from the shared FilamentService signal,
|
||||
* which is loaded on init and can be refreshed via refresh().
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-inventory-summary',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatIconModule,
|
||||
MatChipsModule,
|
||||
MatTooltipModule,
|
||||
MatProgressBarModule,
|
||||
],
|
||||
templateUrl: './inventory-summary.component.html',
|
||||
styleUrls: ['./inventory-summary.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class InventorySummaryComponent implements OnInit, OnDestroy {
|
||||
private readonly filamentService = inject(FilamentService);
|
||||
private subscription: Subscription | null = null;
|
||||
|
||||
/** All filament data — reactive signal from shared service */
|
||||
readonly filaments = this.filamentService.filaments;
|
||||
|
||||
/** Loading state */
|
||||
readonly loading = signal<boolean>(true);
|
||||
|
||||
/** Error state */
|
||||
readonly error = signal<string | null>(null);
|
||||
|
||||
/** Computed: total number of filament spools */
|
||||
readonly totalCount = computed(() => this.filaments().length);
|
||||
|
||||
/** Computed: count of active spools */
|
||||
readonly activeCount = computed(
|
||||
() => this.filaments().filter((f) => f.isActive).length
|
||||
);
|
||||
|
||||
/** Computed: count of low/critical stock spools (≤25% remaining) */
|
||||
readonly lowStockCount = computed(
|
||||
() =>
|
||||
this.filaments().filter(
|
||||
(f) =>
|
||||
classifyStockLevel(f) === 'low' ||
|
||||
classifyStockLevel(f) === 'critical'
|
||||
).length
|
||||
);
|
||||
|
||||
/** Computed: count of critically low spools (≤10% remaining) */
|
||||
readonly criticalCount = computed(
|
||||
() =>
|
||||
this.filaments().filter((f) => classifyStockLevel(f) === 'critical')
|
||||
.length
|
||||
);
|
||||
|
||||
/** Computed: estimated total value of active spools */
|
||||
readonly totalValue = computed(() =>
|
||||
this.filaments()
|
||||
.filter((f) => f.isActive && f.purchasePrice !== null)
|
||||
.reduce((sum, f) => sum + (f.purchasePrice ?? 0), 0)
|
||||
);
|
||||
|
||||
/** Computed: average cost per gram across active spools with a price */
|
||||
readonly avgCostPerGram = computed(() => {
|
||||
const priced = this.filaments().filter(
|
||||
(f) => f.isActive && f.purchasePrice !== null && f.purchasePrice! > 0 && f.weightTotalGrams > 0
|
||||
);
|
||||
if (priced.length === 0) return null;
|
||||
const totalCost = priced.reduce((sum, f) => sum + f.purchasePrice!, 0);
|
||||
const totalWeight = priced.reduce((sum, f) => sum + f.weightTotalGrams, 0);
|
||||
return totalWeight > 0 ? totalCost / totalWeight : null;
|
||||
});
|
||||
|
||||
/** Computed: total grams used across all spools */
|
||||
readonly totalGramsUsed = computed(() =>
|
||||
this.filaments().reduce(
|
||||
(sum, f) => sum + (f.weightTotalGrams - f.weightRemainingGrams),
|
||||
0
|
||||
)
|
||||
);
|
||||
|
||||
/** Computed: total estimated value of used filament */
|
||||
readonly estimatedUsedValue = computed(() => {
|
||||
const priced = this.filaments().filter(
|
||||
(f) => f.isActive && f.purchasePrice !== null && f.purchasePrice! > 0 && f.weightTotalGrams > 0
|
||||
);
|
||||
if (priced.length === 0) return null;
|
||||
return priced.reduce((sum, f) => {
|
||||
const usedFraction = (f.weightTotalGrams - f.weightRemainingGrams) / f.weightTotalGrams;
|
||||
return sum + f.purchasePrice! * usedFraction;
|
||||
}, 0);
|
||||
});
|
||||
|
||||
/** Computed: total remaining weight across all spools in grams */
|
||||
readonly totalRemainingGrams = computed(() =>
|
||||
this.filaments().reduce((sum, f) => sum + f.weightRemainingGrams, 0)
|
||||
);
|
||||
|
||||
/** Computed: total capacity weight across all spools in grams */
|
||||
readonly totalCapacityGrams = computed(() =>
|
||||
this.filaments().reduce((sum, f) => sum + f.weightTotalGrams, 0)
|
||||
);
|
||||
|
||||
/** Computed: overall remaining percentage */
|
||||
readonly overallRemainingPercent = computed(() => {
|
||||
const capacity = this.totalCapacityGrams();
|
||||
if (capacity <= 0) return 0;
|
||||
return Math.round(
|
||||
(this.totalRemainingGrams() / capacity) * 100
|
||||
);
|
||||
});
|
||||
|
||||
/** Computed: whether to show a low-stock alert */
|
||||
readonly hasLowStock = computed(() => this.lowStockCount() > 0);
|
||||
|
||||
/** Computed: whether to show a critical-stock alert */
|
||||
readonly hasCritical = computed(() => this.criticalCount() > 0);
|
||||
|
||||
/** Computed: status label for the inventory health */
|
||||
readonly healthLabel = computed(() => {
|
||||
if (this.hasCritical()) return 'Critical Stock';
|
||||
if (this.hasLowStock()) return 'Low Stock Alert';
|
||||
return 'Stock Healthy';
|
||||
});
|
||||
|
||||
/** Computed: health status color class */
|
||||
readonly healthClass = computed(() => {
|
||||
if (this.hasCritical()) return 'critical';
|
||||
if (this.hasLowStock()) return 'low';
|
||||
return 'healthy';
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadFilaments();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subscription?.unsubscribe();
|
||||
}
|
||||
|
||||
/** Load filament data from the API via FilamentService */
|
||||
loadFilaments(): void {
|
||||
this.loading.set(true);
|
||||
this.error.set(null);
|
||||
this.subscription = this.filamentService.getFilaments().subscribe({
|
||||
next: () => {
|
||||
this.loading.set(false);
|
||||
},
|
||||
error: (err) => {
|
||||
console.error('Failed to load filaments:', err);
|
||||
this.error.set('Failed to load inventory data');
|
||||
this.loading.set(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Refresh data — called externally when data changes (e.g., SignalR notification) */
|
||||
refresh(): void {
|
||||
this.loadFilaments();
|
||||
}
|
||||
|
||||
/** Format weight for display */
|
||||
formatWeight(grams: number): string {
|
||||
if (grams >= 1000) {
|
||||
return `${(grams / 1000).toFixed(1)}kg`;
|
||||
}
|
||||
return `${Math.round(grams)}g`;
|
||||
}
|
||||
|
||||
/** Format currency for display */
|
||||
formatCurrency(value: number): string {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(value);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
/**
|
||||
* Represents the status of a single agent/printer in the system.
|
||||
*/
|
||||
export type AgentStatus = 'active' | 'idle' | 'thinking' | 'error';
|
||||
|
||||
export interface AgentSummary {
|
||||
/** Total number of agents in the system */
|
||||
total: number;
|
||||
/** Number of currently active agents */
|
||||
active: number;
|
||||
/** Number of currently idle agents */
|
||||
idle: number;
|
||||
/** Number of currently thinking/processing agents */
|
||||
thinking: number;
|
||||
/** Number of agents in error state */
|
||||
error: number;
|
||||
}
|
||||
|
||||
export interface SystemHealth {
|
||||
/** Whether the SignalR connection is live */
|
||||
connected: boolean;
|
||||
/** Overall system health: healthy, degraded, or down */
|
||||
status: 'healthy' | 'degraded' | 'down';
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/**
|
||||
* Filament model matching the Extrudex backend FilamentResponse DTO.
|
||||
* Used for displaying spool inventory in the filament table UI.
|
||||
*/
|
||||
export interface Filament {
|
||||
/** Unique identifier for the filament spool. */
|
||||
id: string;
|
||||
|
||||
/** Foreign key to the base material. */
|
||||
materialBaseId: string;
|
||||
|
||||
/** Name of the base material (e.g., "PLA", "PETG"). */
|
||||
materialBaseName: string;
|
||||
|
||||
/** Foreign key to the material finish. */
|
||||
materialFinishId: string;
|
||||
|
||||
/** Name of the material finish (e.g., "Basic", "Matte"). */
|
||||
materialFinishName: string;
|
||||
|
||||
/** Foreign key to the optional material modifier. */
|
||||
materialModifierId: string | null;
|
||||
|
||||
/** Name of the material modifier (e.g., "Carbon Fiber"). Null if none. */
|
||||
materialModifierName: string | null;
|
||||
|
||||
/** Brand name (e.g., "Bambu Lab", "Polymaker"). */
|
||||
brand: string;
|
||||
|
||||
/** Human-readable color name (e.g., "Fire Engine Red"). */
|
||||
colorName: string;
|
||||
|
||||
/** Hex color code (e.g., "#FF0000"). */
|
||||
colorHex: string;
|
||||
|
||||
/** Total spool weight in grams when full. */
|
||||
weightTotalGrams: number;
|
||||
|
||||
/** Current remaining weight in grams. */
|
||||
weightRemainingGrams: number;
|
||||
|
||||
/** Filament diameter in millimeters. Typically 1.75mm. */
|
||||
filamentDiameterMm: number;
|
||||
|
||||
/** Manufacturer-assigned serial number. */
|
||||
spoolSerial: string;
|
||||
|
||||
/** Purchase price per spool. Null if not tracked. */
|
||||
purchasePrice: number | null;
|
||||
|
||||
/** Date the spool was purchased or received. */
|
||||
purchaseDate: string | null;
|
||||
|
||||
/** Whether the spool is currently active and available. */
|
||||
isActive: boolean;
|
||||
|
||||
/** Timestamp when this record was created (UTC). */
|
||||
createdAt: string;
|
||||
|
||||
/** Timestamp when this record was last updated (UTC). */
|
||||
updatedAt: string;
|
||||
|
||||
/** URL to the QR code image for this spool. */
|
||||
qrCodeUrl: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stock level classification for low stock indicators.
|
||||
* - critical: ≤ 10% remaining
|
||||
* - low: ≤ 25% remaining
|
||||
* - moderate: ≤ 50% remaining
|
||||
* - healthy: > 50% remaining
|
||||
*/
|
||||
export type StockLevel = 'critical' | 'low' | 'moderate' | 'healthy';
|
||||
|
||||
/**
|
||||
* Compute the remaining weight percentage for a filament spool.
|
||||
* Returns a value from 0 to 100.
|
||||
*/
|
||||
export function getRemainingPercent(filament: Filament): number {
|
||||
if (filament.weightTotalGrams <= 0) return 0;
|
||||
const pct = (filament.weightRemainingGrams / filament.weightTotalGrams) * 100;
|
||||
return Math.min(Math.max(pct, 0), 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify the stock level based on remaining percentage.
|
||||
* Thresholds:
|
||||
* critical — ≤ 10% (nearly empty, red alert)
|
||||
* low — ≤ 25% (getting low, amber warning)
|
||||
* moderate — ≤ 50% (half or less, yellow info)
|
||||
* healthy — > 50% (plenty left, green OK)
|
||||
*/
|
||||
export function classifyStockLevel(filament: Filament): StockLevel {
|
||||
const pct = getRemainingPercent(filament);
|
||||
if (pct <= 10) return 'critical';
|
||||
if (pct <= 25) return 'low';
|
||||
if (pct <= 50) return 'moderate';
|
||||
return 'healthy';
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* Material lookup models matching the Extrudex backend Material DTOs.
|
||||
* Used for populating dropdowns in the filament add/edit form.
|
||||
*/
|
||||
|
||||
/** Material base (e.g., PLA, PETG, ABS). */
|
||||
export interface MaterialBase {
|
||||
/** Unique identifier. */
|
||||
id: string;
|
||||
/** Human-readable name (e.g., "PLA", "PETG"). */
|
||||
name: string;
|
||||
/** Density in g/cm³. */
|
||||
densityGperCm3: number;
|
||||
/** Created timestamp (UTC). */
|
||||
createdAt: string;
|
||||
/** Updated timestamp (UTC). */
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** Material finish (e.g., Basic, Matte, Silk). */
|
||||
export interface MaterialFinish {
|
||||
/** Unique identifier. */
|
||||
id: string;
|
||||
/** Human-readable name (e.g., "Basic", "Matte"). */
|
||||
name: string;
|
||||
/** Foreign key to the parent material base. */
|
||||
materialBaseId: string;
|
||||
/** Name of the parent material base (for display). */
|
||||
materialBaseName: string;
|
||||
/** Created timestamp (UTC). */
|
||||
createdAt: string;
|
||||
/** Updated timestamp (UTC). */
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** Material modifier (e.g., Carbon Fiber, Wood Fill). Optional. */
|
||||
export interface MaterialModifier {
|
||||
/** Unique identifier. */
|
||||
id: string;
|
||||
/** Human-readable name (e.g., "Carbon Fiber"). */
|
||||
name: string;
|
||||
/** Foreign key to the parent material base. */
|
||||
materialBaseId: string;
|
||||
/** Name of the parent material base (for display). */
|
||||
materialBaseName: string;
|
||||
/** Created timestamp (UTC). */
|
||||
createdAt: string;
|
||||
/** Updated timestamp (UTC). */
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/**
|
||||
* Generic paged response wrapper matching the Extrudex backend PagedResponse<T>.
|
||||
*/
|
||||
export interface PagedResponse<T> {
|
||||
/** The items in this page. */
|
||||
items: T[];
|
||||
/** Total number of items across all pages. */
|
||||
totalCount: number;
|
||||
/** The current page number (1-based). */
|
||||
pageNumber: number;
|
||||
/** The number of items per page. */
|
||||
pageSize: number;
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, Subscription } from 'rxjs';
|
||||
import { signal } from '@angular/core';
|
||||
import { Filament } from '../models/filament.model';
|
||||
|
||||
/**
|
||||
* API base URL — matches the Extrudex backend.
|
||||
* TODO: Move to environment config when environments are set up.
|
||||
*/
|
||||
const API_BASE_URL = '/api/filaments';
|
||||
|
||||
/**
|
||||
* Service for managing filament inventory data.
|
||||
*
|
||||
* Provides:
|
||||
* - A reactive `filaments` signal for components to bind to
|
||||
* - REST methods for GET, POST, DELETE endpoints
|
||||
* - Real-time updates via SignalR should be layered on top when the hub is ready
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class FilamentService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** Reactive filament data — components read from this signal */
|
||||
readonly filaments = signal<Filament[]>([]);
|
||||
|
||||
/** Fetch all filament spools and update the signal */
|
||||
getFilaments(): Observable<Filament[]> {
|
||||
const req = this.http.get<Filament[]>(API_BASE_URL);
|
||||
req.subscribe({
|
||||
next: (data) => this.filaments.set(data),
|
||||
error: (err) => console.error('Failed to load filaments:', err),
|
||||
});
|
||||
return req;
|
||||
}
|
||||
|
||||
/** Fetch a single filament by ID */
|
||||
getFilament(id: string): Observable<Filament> {
|
||||
return this.http.get<Filament>(`${API_BASE_URL}/${id}`);
|
||||
}
|
||||
|
||||
/** Set filament data directly — used by components or SignalR handlers */
|
||||
setFilaments(data: Filament[]): void {
|
||||
this.filaments.set(data);
|
||||
}
|
||||
|
||||
/** Delete a filament spool by ID */
|
||||
deleteFilament(id: string): Observable<void> {
|
||||
return this.http.delete<void>(`${API_BASE_URL}/${id}`);
|
||||
}
|
||||
}
|
||||
18
frontend/src/components/ColorSwatch.tsx
Normal file
18
frontend/src/components/ColorSwatch.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
interface ColorSwatchProps {
|
||||
colorHex: string
|
||||
size?: number
|
||||
}
|
||||
|
||||
export default function ColorSwatch({ colorHex, size = 24 }: ColorSwatchProps) {
|
||||
return (
|
||||
<div
|
||||
className="rounded-full border border-slate-600 shadow-sm inline-block"
|
||||
style={{
|
||||
backgroundColor: colorHex.startsWith('#') ? colorHex : `#${colorHex}`,
|
||||
width: size,
|
||||
height: size,
|
||||
}}
|
||||
title={colorHex}
|
||||
/>
|
||||
)
|
||||
}
|
||||
360
frontend/src/components/FilamentForm.tsx
Normal file
360
frontend/src/components/FilamentForm.tsx
Normal file
@@ -0,0 +1,360 @@
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { X, Save, AlertCircle } from 'lucide-react'
|
||||
import ColorSwatch from './ColorSwatch'
|
||||
import { createFilament, updateFilament, fetchMaterialBases, fetchMaterialFinishes, fetchMaterialModifiers } from '../services/filamentService'
|
||||
import type { FilamentSpool, MaterialBase, MaterialFinish, MaterialModifier } from '../types/filament'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
interface FilamentFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: FilamentSpool | null
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
export default function FilamentForm({ mode, initialData, onClose, onSuccess }: FilamentFormProps) {
|
||||
const [name, setName] = useState('')
|
||||
const [materialBaseId, setMaterialBaseId] = useState('')
|
||||
const [materialFinishId, setMaterialFinishId] = useState('1')
|
||||
const [materialModifierId, setMaterialModifierId] = useState('')
|
||||
const [colorHex, setColorHex] = useState('#3B82F6')
|
||||
const [brand, setBrand] = useState('')
|
||||
const [diameterMm, setDiameterMm] = useState('1.75')
|
||||
const [initialGrams, setInitialGrams] = useState('')
|
||||
const [remainingGrams, setRemainingGrams] = useState('')
|
||||
const [costUsd, setCostUsd] = useState('')
|
||||
const [lowStockThreshold, setLowStockThreshold] = useState('50')
|
||||
const [notes, setNotes] = useState('')
|
||||
const [barcode, setBarcode] = useState('')
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [submitError, setSubmitError] = useState<string | null>(null)
|
||||
|
||||
const { data: materials } = useQuery({
|
||||
queryKey: ['materials'],
|
||||
queryFn: fetchMaterialBases,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
const { data: finishes } = useQuery({
|
||||
queryKey: ['finishes'],
|
||||
queryFn: fetchMaterialFinishes,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
const { data: modifiers } = useQuery({
|
||||
queryKey: ['modifiers'],
|
||||
queryFn: fetchMaterialModifiers,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && initialData) {
|
||||
setName(initialData.name ?? '')
|
||||
setMaterialBaseId(String(initialData.material_base_id ?? ''))
|
||||
setMaterialFinishId(String(initialData.material_finish_id ?? '1'))
|
||||
setMaterialModifierId(initialData.material_modifier_id ? String(initialData.material_modifier_id) : '')
|
||||
setColorHex(initialData.color_hex ?? '#3B82F6')
|
||||
setBrand(initialData.brand ?? '')
|
||||
setDiameterMm(String(initialData.diameter_mm ?? 1.75))
|
||||
setInitialGrams(String(initialData.initial_grams ?? ''))
|
||||
setRemainingGrams(String(initialData.remaining_grams ?? ''))
|
||||
setCostUsd(initialData.cost_usd != null ? String(initialData.cost_usd) : '')
|
||||
setLowStockThreshold(String(initialData.low_stock_threshold_grams ?? 50))
|
||||
setNotes(initialData.notes ?? '')
|
||||
setBarcode(initialData.barcode ?? '')
|
||||
}
|
||||
}, [mode, initialData])
|
||||
|
||||
const colorHexValid = useMemo(() => {
|
||||
return /^#[0-9A-Fa-f]{6}$/.test(colorHex)
|
||||
}, [colorHex])
|
||||
|
||||
function validate(): FormErrors {
|
||||
const e: FormErrors = {}
|
||||
if (!name.trim()) e.name = 'Name is required'
|
||||
if (!materialBaseId) e.material_base_id = 'Material Base is required'
|
||||
if (!materialFinishId) e.material_finish_id = 'Material Finish is required'
|
||||
if (!colorHexValid) e.color_hex = 'Enter a valid hex color (e.g., #FF0000)'
|
||||
if (!initialGrams || Number(initialGrams) <= 0) e.initial_grams = 'Must be > 0'
|
||||
if (remainingGrams === '' || Number(remainingGrams) < 0) e.remaining_grams = 'Must be >= 0'
|
||||
if (Number(remainingGrams) > Number(initialGrams)) e.remaining_grams = 'Cannot exceed Initial Grams'
|
||||
if (costUsd && Number(costUsd) < 0) e.cost_usd = 'Must be >= 0'
|
||||
if (!diameterMm || Number(diameterMm) <= 0) e.diameter_mm = 'Must be > 0'
|
||||
if (!lowStockThreshold || Number(lowStockThreshold) < 0) e.low_stock_threshold_grams = 'Must be >= 0'
|
||||
return e
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSubmitError(null)
|
||||
const validation = validate()
|
||||
if (Object.keys(validation).length > 0) {
|
||||
setErrors(validation)
|
||||
return
|
||||
}
|
||||
setErrors({})
|
||||
setSubmitting(true)
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
name: name.trim(),
|
||||
material_base_id: Number(materialBaseId),
|
||||
material_finish_id: Number(materialFinishId),
|
||||
color_hex: colorHex,
|
||||
initial_grams: Number(initialGrams),
|
||||
remaining_grams: Number(remainingGrams),
|
||||
diameter_mm: Number(diameterMm),
|
||||
low_stock_threshold_grams: Number(lowStockThreshold),
|
||||
}
|
||||
|
||||
if (materialModifierId) payload.material_modifier_id = Number(materialModifierId)
|
||||
if (brand.trim()) payload.brand = brand.trim()
|
||||
if (costUsd) payload.cost_usd = Number(costUsd)
|
||||
if (notes.trim()) payload.notes = notes.trim()
|
||||
if (barcode.trim()) payload.barcode = barcode.trim()
|
||||
|
||||
try {
|
||||
if (mode === 'edit' && initialData) {
|
||||
await updateFilament(initialData.id, payload)
|
||||
} else {
|
||||
await createFilament(payload)
|
||||
}
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (err: any) {
|
||||
setSubmitError(err?.response?.data?.error || 'Failed to save spool. Please try again.')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-start justify-center sm:items-center bg-black/60 backdrop-blur-sm p-4 overflow-y-auto">
|
||||
<div className="w-full max-w-2xl rounded-xl bg-slate-800 border border-slate-700 shadow-2xl overflow-hidden my-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-700">
|
||||
<h3 className="text-lg font-semibold text-slate-100">
|
||||
{mode === 'edit' ? 'Edit Filament Spool' : 'Add Filament Spool'}
|
||||
</h3>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-100 hover:bg-slate-700 transition-colors"
|
||||
type="button"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Error banner */}
|
||||
{submitError && (
|
||||
<div className="mx-6 mt-4 flex items-start gap-2 rounded-lg bg-red-900/30 border border-red-700 px-4 py-3 text-sm text-red-300">
|
||||
<AlertCircle size={16} className="shrink-0 mt-0.5" />
|
||||
<span>{submitError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form */}
|
||||
<form onSubmit={handleSubmit} className="px-6 py-4 space-y-5">
|
||||
{/* Row 1: Name + Brand */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Name <span className="text-red-400">*</span></label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 ${errors.name ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
placeholder="e.g. Sunlu PLA Silk Red"
|
||||
/>
|
||||
{errors.name && <p className="mt-1 text-xs text-red-400">{errors.name}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Brand</label>
|
||||
<input
|
||||
type="text"
|
||||
value={brand}
|
||||
onChange={e => setBrand(e.target.value)}
|
||||
className="w-full rounded-lg bg-slate-900 border border-slate-600 px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="e.g. Hatchbox"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Row 2: Material Base + Finish + Modifier */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Material Base <span className="text-red-400">*</span></label>
|
||||
<select
|
||||
value={materialBaseId}
|
||||
onChange={e => setMaterialBaseId(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 ${errors.material_base_id ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
>
|
||||
<option value="">Select…</option>
|
||||
{materials?.map((m: MaterialBase) => (
|
||||
<option key={m.id} value={m.id}>{m.name}</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.material_base_id && <p className="mt-1 text-xs text-red-400">{errors.material_base_id}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Finish <span className="text-red-400">*</span></label>
|
||||
<select
|
||||
value={materialFinishId}
|
||||
onChange={e => setMaterialFinishId(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 ${errors.material_finish_id ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
>
|
||||
{finishes?.map((f: MaterialFinish) => (
|
||||
<option key={f.id} value={f.id}>{f.name}</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.material_finish_id && <p className="mt-1 text-xs text-red-400">{errors.material_finish_id}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Modifier</label>
|
||||
<select
|
||||
value={materialModifierId}
|
||||
onChange={e => setMaterialModifierId(e.target.value)}
|
||||
className="w-full rounded-lg bg-slate-900 border border-slate-600 px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
>
|
||||
<option value="">None</option>
|
||||
{modifiers?.map((m: MaterialModifier) => (
|
||||
<option key={m.id} value={m.id}>{m.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Row 3: Color + Diameter */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Color <span className="text-red-400">*</span></label>
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="color"
|
||||
value={colorHex}
|
||||
onChange={e => setColorHex(e.target.value)}
|
||||
className="h-10 w-14 rounded border border-slate-600 bg-slate-900 cursor-pointer"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<input
|
||||
type="text"
|
||||
value={colorHex}
|
||||
onChange={e => setColorHex(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 font-mono uppercase focus:outline-none focus:ring-2 ${errors.color_hex ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
placeholder="#FF0000"
|
||||
maxLength={7}
|
||||
/>
|
||||
</div>
|
||||
<ColorSwatch colorHex={colorHex} size={32} />
|
||||
</div>
|
||||
{errors.color_hex && <p className="mt-1 text-xs text-red-400">{errors.color_hex}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Diameter (mm) <span className="text-red-400">*</span></label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={diameterMm}
|
||||
onChange={e => setDiameterMm(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 ${errors.diameter_mm ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
/>
|
||||
{errors.diameter_mm && <p className="mt-1 text-xs text-red-400">{errors.diameter_mm}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Row 4: Grams */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Initial Grams <span className="text-red-400">*</span></label>
|
||||
<input
|
||||
type="number"
|
||||
value={initialGrams}
|
||||
onChange={e => setInitialGrams(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 ${errors.initial_grams ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
/>
|
||||
{errors.initial_grams && <p className="mt-1 text-xs text-red-400">{errors.initial_grams}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Remaining Grams <span className="text-red-400">*</span></label>
|
||||
<input
|
||||
type="number"
|
||||
value={remainingGrams}
|
||||
onChange={e => setRemainingGrams(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 ${errors.remaining_grams ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
/>
|
||||
{errors.remaining_grams && <p className="mt-1 text-xs text-red-400">{errors.remaining_grams}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Cost (USD)</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={costUsd}
|
||||
onChange={e => setCostUsd(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 ${errors.cost_usd ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Row 5: Threshold + Barcode */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Low Stock Threshold (g) <span className="text-red-400">*</span></label>
|
||||
<input
|
||||
type="number"
|
||||
value={lowStockThreshold}
|
||||
onChange={e => setLowStockThreshold(e.target.value)}
|
||||
className={`w-full rounded-lg bg-slate-900 border px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 ${errors.low_stock_threshold_grams ? 'border-red-500 focus:ring-red-500' : 'border-slate-600 focus:ring-emerald-500'}`}
|
||||
/>
|
||||
{errors.low_stock_threshold_grams && <p className="mt-1 text-xs text-red-400">{errors.low_stock_threshold_grams}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Barcode</label>
|
||||
<input
|
||||
type="text"
|
||||
value={barcode}
|
||||
onChange={e => setBarcode(e.target.value)}
|
||||
className="w-full rounded-lg bg-slate-900 border border-slate-600 px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
placeholder="e.g. 123456789012"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Notes */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-300 mb-1">Notes</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
value={notes}
|
||||
onChange={e => setNotes(e.target.value)}
|
||||
className="w-full rounded-lg bg-slate-900 border border-slate-600 px-3 py-2.5 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500 resize-y"
|
||||
placeholder="Print temperature tips, storage notes, etc."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Footer actions */}
|
||||
<div className="flex justify-end gap-3 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="rounded-lg bg-slate-700 px-4 py-2.5 text-sm font-medium text-slate-200 hover:bg-slate-600 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-emerald-500 active:bg-emerald-700 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
<Save size={16} />
|
||||
{submitting ? 'Saving…' : mode === 'edit' ? 'Update Spool' : 'Create Spool'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
8
frontend/src/components/LoadingSpinner.tsx
Normal file
8
frontend/src/components/LoadingSpinner.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
export default function LoadingSpinner() {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="w-10 h-10 border-4 border-emerald-500/30 border-t-emerald-400 rounded-full animate-spin" />
|
||||
<p className="text-slate-400 text-sm">Loading dashboard…</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
76
frontend/src/components/RecentPrints.tsx
Normal file
76
frontend/src/components/RecentPrints.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import type { PrintJob } from '../types'
|
||||
import { Clock, FileText } from 'lucide-react'
|
||||
|
||||
interface RecentPrintsProps {
|
||||
jobs: PrintJob[]
|
||||
}
|
||||
|
||||
export default function RecentPrints({ jobs }: RecentPrintsProps) {
|
||||
if (jobs.length === 0) {
|
||||
return (
|
||||
<div className="rounded-xl border border-slate-700 bg-slate-800 p-6 text-center text-slate-400">
|
||||
<FileText size={32} className="mx-auto mb-3 text-slate-500" />
|
||||
<p>No recent print jobs</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const statusColor = (status: string) => {
|
||||
switch (status.toLowerCase()) {
|
||||
case 'completed': return 'text-emerald-400 bg-emerald-500/10'
|
||||
case 'in_progress': return 'text-sky-400 bg-sky-500/10'
|
||||
case 'failed': return 'text-red-400 bg-red-500/10'
|
||||
default: return 'text-slate-400 bg-slate-500/10'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-slate-700 bg-slate-800 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-700">
|
||||
<th className="px-4 py-3 text-sm font-medium text-slate-400">Name</th>
|
||||
<th className="px-4 py-3 text-sm font-medium text-slate-400">Status</th>
|
||||
<th className="px-4 py-3 text-sm font-medium text-slate-400">Duration</th>
|
||||
<th className="px-4 py-3 text-sm font-medium text-slate-400">Filament</th>
|
||||
<th className="px-4 py-3 text-sm font-medium text-slate-400">Cost</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{jobs.map((job) => (
|
||||
<tr key={job.id} className="border-b border-slate-700/50 last:border-0 hover:bg-slate-700/30 transition-colors">
|
||||
<td className="px-4 py-3 text-sm text-slate-100 font-medium">{job.name}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${statusColor(job.status)}`}>
|
||||
{job.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-slate-300">
|
||||
<div className="flex items-center gap-1">
|
||||
<Clock size={14} />
|
||||
{formatDuration(job.duration_seconds)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-slate-300">
|
||||
{job.filament_used_grams?.toFixed(1) ?? '-'} g
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-slate-300">
|
||||
${job.cost_usd?.toFixed(2) ?? '-'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
if (!seconds) return '-'
|
||||
const hrs = Math.floor(seconds / 3600)
|
||||
const mins = Math.floor((seconds % 3600) / 60)
|
||||
if (hrs > 0) return `${hrs}h ${mins}m`
|
||||
return `${mins}m`
|
||||
}
|
||||
31
frontend/src/components/SummaryCard.tsx
Normal file
31
frontend/src/components/SummaryCard.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
|
||||
interface SummaryCardProps {
|
||||
title: string
|
||||
value: string | number
|
||||
icon: LucideIcon
|
||||
color: 'emerald' | 'amber' | 'sky' | 'violet'
|
||||
}
|
||||
|
||||
const colorMap = {
|
||||
emerald: { bg: 'bg-emerald-500/10', border: 'border-emerald-500/20', text: 'text-emerald-400', icon: 'text-emerald-400' },
|
||||
amber: { bg: 'bg-amber-500/10', border: 'border-amber-500/20', text: 'text-amber-400', icon: 'text-amber-400' },
|
||||
sky: { bg: 'bg-sky-500/10', border: 'border-sky-500/20', text: 'text-sky-400', icon: 'text-sky-400' },
|
||||
violet: { bg: 'bg-violet-500/10', border: 'border-violet-500/20', text: 'text-violet-400', icon: 'text-violet-400' },
|
||||
}
|
||||
|
||||
export default function SummaryCard({ title, value, icon: Icon, color }: SummaryCardProps) {
|
||||
const c = colorMap[color]
|
||||
|
||||
return (
|
||||
<div className={`rounded-xl border ${c.border} ${c.bg} p-5 flex items-start justify-between`}>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-400 mb-1">{title}</p>
|
||||
<p className={`text-3xl font-bold ${c.text}`}>{value}</p>
|
||||
</div>
|
||||
<div className={`p-2 rounded-lg ${c.bg}`}>
|
||||
<Icon size={24} className={c.icon} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/**
|
||||
* Environment configuration for the Extrudex frontend (production).
|
||||
* Override API URL for deployed environments.
|
||||
*/
|
||||
export const environment = {
|
||||
production: true,
|
||||
apiBaseUrl: '/api',
|
||||
};
|
||||
@@ -1,8 +0,0 @@
|
||||
/**
|
||||
* Environment configuration for the Extrudex frontend.
|
||||
* Replace API URL with the actual backend endpoint in production.
|
||||
*/
|
||||
export const environment = {
|
||||
production: false,
|
||||
apiBaseUrl: 'http://localhost:5000',
|
||||
};
|
||||
0
frontend/src/hooks/.gitkeep
Normal file
0
frontend/src/hooks/.gitkeep
Normal file
8
frontend/src/index.css
Normal file
8
frontend/src/index.css
Normal file
@@ -0,0 +1,8 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background-color: #0f172a; /* slate-900 */
|
||||
color: #f8fafc; /* slate-50 */
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Frontend</title>
|
||||
<base href="/" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,6 +0,0 @@
|
||||
import { bootstrapApplication } from '@angular/platform-browser';
|
||||
import { appConfig } from './app/app.config';
|
||||
import { App } from './app/app';
|
||||
|
||||
bootstrapApplication(App, appConfig)
|
||||
.catch((err) => console.error(err));
|
||||
25
frontend/src/main.tsx
Normal file
25
frontend/src/main.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import './index.css'
|
||||
import App from './App'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
139
frontend/src/pages/Dashboard.tsx
Normal file
139
frontend/src/pages/Dashboard.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getFilaments, getPrintJobs } from '../services/api'
|
||||
import SummaryCard from '../components/SummaryCard'
|
||||
import RecentPrints from '../components/RecentPrints'
|
||||
import LoadingSpinner from '../components/LoadingSpinner'
|
||||
import { Package, AlertTriangle, Printer, DollarSign, Plus, List } from 'lucide-react'
|
||||
|
||||
export default function Dashboard() {
|
||||
const {
|
||||
data: filamentData,
|
||||
isLoading: filamentLoading,
|
||||
error: filamentError,
|
||||
} = useQuery({
|
||||
queryKey: ['filaments', 'count'],
|
||||
queryFn: () => getFilaments({ limit: 1 }),
|
||||
})
|
||||
|
||||
const {
|
||||
data: lowStockData,
|
||||
isLoading: lowStockLoading,
|
||||
error: lowStockError,
|
||||
} = useQuery({
|
||||
queryKey: ['filaments', 'lowStock'],
|
||||
queryFn: () => getFilaments({ low_stock: true, limit: 1 }),
|
||||
})
|
||||
|
||||
const {
|
||||
data: recentPrints,
|
||||
isLoading: printsLoading,
|
||||
error: printsError,
|
||||
} = useQuery({
|
||||
queryKey: ['printJobs', 'recent'],
|
||||
queryFn: () => getPrintJobs({ limit: 5 }),
|
||||
})
|
||||
|
||||
const {
|
||||
data: allPrints,
|
||||
isLoading: costLoading,
|
||||
error: costError,
|
||||
} = useQuery({
|
||||
queryKey: ['printJobs', 'all'],
|
||||
queryFn: () => getPrintJobs({ limit: 1000 }),
|
||||
})
|
||||
|
||||
const totalSpools = filamentData?.total ?? 0
|
||||
const lowStockCount = lowStockData?.total ?? 0
|
||||
const recentPrintJobs = recentPrints?.data ?? []
|
||||
|
||||
// Calculate cost this month from all print jobs
|
||||
const now = new Date()
|
||||
const currentMonth = now.getMonth()
|
||||
const currentYear = now.getFullYear()
|
||||
const monthlyCost =
|
||||
allPrints?.data
|
||||
.filter((job) => {
|
||||
const d = new Date(job.started_at)
|
||||
return d.getMonth() === currentMonth && d.getFullYear() === currentYear
|
||||
})
|
||||
.reduce((sum, job) => sum + (job.cost_usd ?? 0), 0) ?? 0
|
||||
|
||||
const isLoading = filamentLoading || lowStockLoading || printsLoading || costLoading
|
||||
const error = filamentError || lowStockError || printsError || costError
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-900">
|
||||
<LoadingSpinner />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-900">
|
||||
<div className="p-6 rounded-lg bg-red-900/30 border border-red-500 text-red-200 max-w-md">
|
||||
<h2 className="text-xl font-bold mb-2">Error</h2>
|
||||
<p className="text-sm">{(error as Error).message || 'Failed to load dashboard data.'}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-900 p-4 md:p-8">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<header className="mb-8">
|
||||
<h1 className="text-3xl font-bold text-emerald-400 mb-2">Dashboard</h1>
|
||||
<p className="text-slate-400">Overview of your Extrudex inventory and prints</p>
|
||||
</header>
|
||||
|
||||
{/* Summary Cards Grid */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
|
||||
<SummaryCard
|
||||
title="Total Spools"
|
||||
value={totalSpools}
|
||||
icon={Package}
|
||||
color="emerald"
|
||||
/>
|
||||
<SummaryCard
|
||||
title="Low Stock"
|
||||
value={lowStockCount}
|
||||
icon={AlertTriangle}
|
||||
color={lowStockCount > 0 ? 'amber' : 'emerald'}
|
||||
/>
|
||||
<SummaryCard
|
||||
title="Recent Prints"
|
||||
value={recentPrintJobs.length}
|
||||
icon={Printer}
|
||||
color="sky"
|
||||
/>
|
||||
<SummaryCard
|
||||
title="Cost This Month"
|
||||
value={`$${monthlyCost.toFixed(2)}`}
|
||||
icon={DollarSign}
|
||||
color="violet"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Quick Actions */}
|
||||
<div className="flex flex-wrap gap-3 mb-8">
|
||||
<button className="flex items-center gap-2 px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white font-medium transition-colors active:scale-95 touch-manipulation">
|
||||
<Plus size={18} />
|
||||
Add Spool
|
||||
</button>
|
||||
<button className="flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-700 hover:bg-slate-600 text-slate-100 font-medium transition-colors active:scale-95 touch-manipulation">
|
||||
<List size={18} />
|
||||
View Inventory
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Recent Prints Section */}
|
||||
<section>
|
||||
<h2 className="text-xl font-semibold text-slate-100 mb-4">Recent Prints</h2>
|
||||
<RecentPrints jobs={recentPrintJobs} />
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
363
frontend/src/pages/InventoryPage.tsx
Normal file
363
frontend/src/pages/InventoryPage.tsx
Normal file
@@ -0,0 +1,363 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Search, Filter, ChevronLeft, ChevronRight, Trash2, Pencil, Plus, AlertTriangle } from 'lucide-react'
|
||||
import ColorSwatch from '../components/ColorSwatch'
|
||||
import FilamentForm from '../components/FilamentForm'
|
||||
import { fetchFilaments, deleteFilament } from '../services/filamentService'
|
||||
import type { FilamentSpool, FilamentFilter } from '../types/filament'
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
type SortField = 'name' | 'remaining_grams' | 'cost_usd'
|
||||
type SortDir = 'asc' | 'desc'
|
||||
|
||||
export default function InventoryPage() {
|
||||
const [search, setSearch] = useState('')
|
||||
const [material, setMaterial] = useState('')
|
||||
const [finish, setFinish] = useState('')
|
||||
const [lowStockOnly, setLowStockOnly] = useState(false)
|
||||
const [sortBy, setSortBy] = useState<SortField>('name')
|
||||
const [sortDir, setSortDir] = useState<SortDir>('asc')
|
||||
const [page, setPage] = useState(0)
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null)
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [formMode, setFormMode] = useState<'create' | 'edit'>('create')
|
||||
const [formInitial, setFormInitial] = useState<FilamentSpool | null>(null)
|
||||
|
||||
const filter: FilamentFilter = useMemo(() => ({
|
||||
material: material || undefined,
|
||||
finish: finish || undefined,
|
||||
low_stock: lowStockOnly,
|
||||
sort_by: sortBy,
|
||||
sort_dir: sortDir,
|
||||
limit: PAGE_SIZE,
|
||||
offset: page * PAGE_SIZE,
|
||||
}), [material, finish, lowStockOnly, sortBy, sortDir, page])
|
||||
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: ['filaments', filter],
|
||||
queryFn: () => fetchFilaments(filter),
|
||||
})
|
||||
|
||||
const filaments = data?.data ?? []
|
||||
const total = data?.total ?? 0
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
|
||||
|
||||
// Client-side search filter (name/barcode) since backend may not support it yet.
|
||||
const filtered = useMemo(() => {
|
||||
if (!search.trim()) return filaments
|
||||
const q = search.toLowerCase()
|
||||
return filaments.filter(
|
||||
(f: FilamentSpool) =>
|
||||
f.name.toLowerCase().includes(q) ||
|
||||
(f.barcode && f.barcode.toLowerCase().includes(q))
|
||||
)
|
||||
}, [filaments, search])
|
||||
|
||||
const handleSort = (field: SortField) => {
|
||||
if (sortBy === field) {
|
||||
setSortDir(prev => (prev === 'asc' ? 'desc' : 'asc'))
|
||||
} else {
|
||||
setSortBy(field)
|
||||
setSortDir('asc')
|
||||
}
|
||||
setPage(0)
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
await deleteFilament(id)
|
||||
setDeleteId(null)
|
||||
refetch()
|
||||
}
|
||||
|
||||
const SortIndicator = ({ field }: { field: SortField }) => {
|
||||
if (sortBy !== field) return <span className="text-slate-600 ml-1">↕</span>
|
||||
return <span className="text-emerald-400 ml-1">{sortDir === 'asc' ? '↑' : '↓'}</span>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-slate-100">Filament Inventory</h2>
|
||||
<p className="text-sm text-slate-400">{total} spool(s) total</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => { setFormMode('create'); setFormInitial(null); setFormOpen(true) }}
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-500 active:bg-emerald-700 transition-colors"
|
||||
>
|
||||
<Plus size={16} /> Add Spool
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="flex flex-col lg:flex-row gap-3">
|
||||
{/* Search */}
|
||||
<div className="relative flex-1">
|
||||
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by name or barcode…"
|
||||
value={search}
|
||||
onChange={e => { setSearch(e.target.value); setPage(0) }}
|
||||
className="w-full rounded-lg bg-slate-800 border border-slate-700 pl-9 pr-3 py-2 text-sm text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Material filter */}
|
||||
<select
|
||||
value={material}
|
||||
onChange={e => { setMaterial(e.target.value); setPage(0) }}
|
||||
className="rounded-lg bg-slate-800 border border-slate-700 px-3 py-2 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
>
|
||||
<option value="">All Materials</option>
|
||||
<option value="PLA">PLA</option>
|
||||
<option value="PETG">PETG</option>
|
||||
<option value="ABS">ABS</option>
|
||||
<option value="TPU">TPU</option>
|
||||
<option value="ASA">ASA</option>
|
||||
<option value="Nylon">Nylon</option>
|
||||
<option value="PC">PC</option>
|
||||
</select>
|
||||
|
||||
{/* Finish filter */}
|
||||
<select
|
||||
value={finish}
|
||||
onChange={e => { setFinish(e.target.value); setPage(0) }}
|
||||
className="rounded-lg bg-slate-800 border border-slate-700 px-3 py-2 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500"
|
||||
>
|
||||
<option value="">All Finishes</option>
|
||||
<option value="Basic">Basic</option>
|
||||
<option value="Silk">Silk</option>
|
||||
<option value="Matte">Matte</option>
|
||||
<option value="Glossy">Glossy</option>
|
||||
<option value="Wood">Wood</option>
|
||||
<option value="Marble">Marble</option>
|
||||
</select>
|
||||
|
||||
{/* Low stock toggle */}
|
||||
<label className="inline-flex items-center gap-2 rounded-lg bg-slate-800 border border-slate-700 px-3 py-2 text-sm text-slate-100 cursor-pointer select-none hover:bg-slate-750">
|
||||
<Filter size={14} className="text-amber-400" />
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={lowStockOnly}
|
||||
onChange={e => { setLowStockOnly(e.target.checked); setPage(0) }}
|
||||
className="accent-amber-500"
|
||||
/>
|
||||
Low Stock Only
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Loading / Error */}
|
||||
{isLoading && (
|
||||
<div className="text-center py-12 text-slate-400">Loading spools…</div>
|
||||
)}
|
||||
{error && (
|
||||
<div className="text-center py-12 text-red-400">
|
||||
Failed to load inventory.
|
||||
<button onClick={() => refetch()} className="ml-2 underline hover:text-red-300">Retry</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Desktop Table */}
|
||||
{!isLoading && !error && (
|
||||
<>
|
||||
<div className="hidden md:block overflow-x-auto rounded-lg border border-slate-700">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-slate-800 text-slate-300">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-semibold cursor-pointer select-none hover:text-slate-100" onClick={() => handleSort('name')}>
|
||||
Name <SortIndicator field="name" />
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left font-semibold">Material</th>
|
||||
<th className="px-4 py-3 text-left font-semibold">Finish</th>
|
||||
<th className="px-4 py-3 text-left font-semibold">Color</th>
|
||||
<th className="px-4 py-3 text-right font-semibold cursor-pointer select-none hover:text-slate-100" onClick={() => handleSort('remaining_grams')}>
|
||||
Remaining <SortIndicator field="remaining_grams" />
|
||||
</th>
|
||||
<th className="px-4 py-3 text-right font-semibold cursor-pointer select-none hover:text-slate-100" onClick={() => handleSort('cost_usd')}>
|
||||
Cost <SortIndicator field="cost_usd" />
|
||||
</th>
|
||||
<th className="px-4 py-3 text-center font-semibold">Status</th>
|
||||
<th className="px-4 py-3 text-right font-semibold">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-700">
|
||||
{filtered.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-4 py-8 text-center text-slate-500">No spools found.</td>
|
||||
</tr>
|
||||
)}
|
||||
{filtered.map((spool: FilamentSpool) => {
|
||||
const isLow = spool.remaining_grams <= spool.low_stock_threshold_grams
|
||||
return (
|
||||
<tr key={spool.id} className={`${isLow ? 'bg-red-900/20' : 'bg-slate-800/50'} hover:bg-slate-700/50 transition-colors`}>
|
||||
<td className="px-4 py-3 font-medium text-slate-100">{spool.name}</td>
|
||||
<td className="px-4 py-3 text-slate-300">{spool.material_base?.name ?? '—'}</td>
|
||||
<td className="px-4 py-3 text-slate-300">{spool.material_finish?.name ?? '—'}</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<ColorSwatch colorHex={spool.color_hex} size={20} />
|
||||
<span className="text-xs text-slate-400 uppercase">{spool.color_hex}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums text-slate-200">{spool.remaining_grams.toLocaleString()} g</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums text-slate-300">{spool.cost_usd != null ? `$${spool.cost_usd.toFixed(2)}` : '—'}</td>
|
||||
<td className="px-4 py-3 text-center">
|
||||
{isLow ? (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-red-900/50 border border-red-700 px-2 py-0.5 text-xs font-medium text-red-300">
|
||||
<AlertTriangle size={12} /> Low
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center rounded-full bg-emerald-900/30 border border-emerald-700 px-2 py-0.5 text-xs font-medium text-emerald-300">OK</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<button
|
||||
onClick={() => { setFormMode('edit'); setFormInitial(spool); setFormOpen(true) }}
|
||||
className="p-1.5 rounded hover:bg-slate-600 text-slate-400 hover:text-blue-400 transition-colors"
|
||||
title="Edit"
|
||||
>
|
||||
<Pencil size={14} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDeleteId(spool.id)}
|
||||
className="p-1.5 rounded hover:bg-slate-600 text-slate-400 hover:text-red-400 transition-colors"
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Mobile Cards */}
|
||||
<div className="md:hidden space-y-3">
|
||||
{filtered.length === 0 && (
|
||||
<div className="text-center py-12 text-slate-500">No spools found.</div>
|
||||
)}
|
||||
{filtered.map((spool: FilamentSpool) => {
|
||||
const isLow = spool.remaining_grams <= spool.low_stock_threshold_grams
|
||||
return (
|
||||
<div key={spool.id} className={`rounded-lg border ${isLow ? 'border-red-700 bg-red-900/10' : 'border-slate-700 bg-slate-800'} p-4 space-y-2`}>
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<div className="font-semibold text-slate-100">{spool.name}</div>
|
||||
<div className="text-xs text-slate-400 mt-0.5">{spool.material_base?.name ?? '—'} · {spool.material_finish?.name ?? '—'}</div>
|
||||
</div>
|
||||
{isLow ? (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-red-900/50 border border-red-700 px-2 py-0.5 text-xs font-medium text-red-300">
|
||||
<AlertTriangle size={12} /> Low
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center rounded-full bg-emerald-900/30 border border-emerald-700 px-2 py-0.5 text-xs font-medium text-emerald-300">OK</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<ColorSwatch colorHex={spool.color_hex} size={20} />
|
||||
<span className="text-slate-400 uppercase text-xs">{spool.color_hex}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-slate-400">Remaining: <span className="text-slate-200 font-medium tabular-nums">{spool.remaining_grams.toLocaleString()} g</span></span>
|
||||
<span className="text-slate-400">{spool.cost_usd != null ? `$${spool.cost_usd.toFixed(2)}` : '—'}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-1">
|
||||
<button
|
||||
onClick={() => { setFormMode('edit'); setFormInitial(spool); setFormOpen(true) }}
|
||||
className="flex items-center gap-1 rounded-md bg-slate-700 px-3 py-1.5 text-xs font-medium text-slate-200 hover:bg-slate-600"
|
||||
>
|
||||
<Pencil size={12} /> Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDeleteId(spool.id)}
|
||||
className="flex items-center gap-1 rounded-md bg-red-900/30 border border-red-700 px-3 py-1.5 text-xs font-medium text-red-300 hover:bg-red-900/50"
|
||||
>
|
||||
<Trash2 size={12} /> Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<span className="text-sm text-slate-400">
|
||||
Showing {page * PAGE_SIZE + 1}–{Math.min((page + 1) * PAGE_SIZE, total)} of {total}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setPage(p => Math.max(0, p - 1))}
|
||||
disabled={page === 0}
|
||||
className="p-2 rounded-lg bg-slate-800 border border-slate-700 text-slate-300 hover:bg-slate-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<ChevronLeft size={16} />
|
||||
</button>
|
||||
<span className="text-sm text-slate-300 tabular-nums">{page + 1} / {totalPages}</span>
|
||||
<button
|
||||
onClick={() => setPage(p => Math.min(totalPages - 1, p + 1))}
|
||||
disabled={page >= totalPages - 1}
|
||||
className="p-2 rounded-lg bg-slate-800 border border-slate-700 text-slate-300 hover:bg-slate-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<ChevronRight size={16} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Add/Edit Form Modal */}
|
||||
{formOpen && (
|
||||
<FilamentForm
|
||||
mode={formMode}
|
||||
initialData={formInitial}
|
||||
onClose={() => setFormOpen(false)}
|
||||
onSuccess={() => refetch()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Delete confirmation modal */}
|
||||
{deleteId !== null && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||
<div className="w-full max-w-sm rounded-xl bg-slate-800 border border-slate-700 p-6 shadow-2xl space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-red-900/30">
|
||||
<AlertTriangle size={20} className="text-red-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-slate-100">Delete Spool?</h3>
|
||||
<p className="text-sm text-slate-400">This action cannot be undone.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
onClick={() => setDeleteId(null)}
|
||||
className="rounded-lg bg-slate-700 px-4 py-2 text-sm font-medium text-slate-200 hover:bg-slate-600 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(deleteId)}
|
||||
className="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-500 transition-colors"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user