Compare commits
5 Commits
agent/rex/
...
73d8c7b45a
| Author | SHA1 | Date | |
|---|---|---|---|
| 73d8c7b45a | |||
| 4a739cebe1 | |||
| a3297726bd | |||
| 40b4bdd1d6 | |||
| fbddcbdbc5 |
@@ -1,108 +0,0 @@
|
||||
using Extrudex.API.DTOs.PrintJobs;
|
||||
using Extrudex.Domain.Interfaces;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Extrudex.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Controller for cost analysis endpoints. Provides spool-level
|
||||
/// cost breakdowns and aggregated COGS reporting.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/cost-analysis")]
|
||||
public class CostAnalysisController : ControllerBase
|
||||
{
|
||||
private readonly ICostPerPrintService _costService;
|
||||
private readonly ILogger<CostAnalysisController> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CostAnalysisController"/> class.
|
||||
/// </summary>
|
||||
/// <param name="costService">The cost-per-print calculation service.</param>
|
||||
/// <param name="logger">The logger for diagnostic output.</param>
|
||||
public CostAnalysisController(
|
||||
ICostPerPrintService costService,
|
||||
ILogger<CostAnalysisController> logger)
|
||||
{
|
||||
_costService = costService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// ── POST /api/cost-analysis/spool ────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Calculates cost breakdowns for all print jobs associated with a specific spool.
|
||||
/// Returns per-job costs plus an aggregated total. Jobs with missing cost data
|
||||
/// include warnings and null cost fields — the endpoint never throws for missing data.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the spool identifier.</param>
|
||||
/// <returns>A spool-level cost summary with per-job breakdowns.</returns>
|
||||
/// <response code="200">Returns the spool cost breakdown with per-job details.</response>
|
||||
/// <response code="404">If the spool has no print jobs.</response>
|
||||
[HttpPost("spool")]
|
||||
[ProducesResponseType(typeof(SpoolCostResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<SpoolCostResponse>> CalculateSpoolCost([FromBody] SpoolCostRequest request)
|
||||
{
|
||||
_logger.LogDebug("Calculating cost breakdown for spool {SpoolId}", request.SpoolId);
|
||||
|
||||
var results = await _costService.CalculateBySpoolAsync(request.SpoolId);
|
||||
|
||||
if (results.Count == 0)
|
||||
{
|
||||
return NotFound(new { error = $"No print jobs found for spool with ID '{request.SpoolId}'." });
|
||||
}
|
||||
|
||||
// Build the spool-level summary
|
||||
var firstResult = results[0];
|
||||
var jobResponses = results.Select(MapCostToResponse).ToList();
|
||||
|
||||
// Aggregate total cost and grams — only include jobs that have a valid cost
|
||||
var calculableJobs = results.Where(r => r.CostPerPrint.HasValue).ToList();
|
||||
var totalCost = calculableJobs.Count == results.Count
|
||||
? Math.Round(calculableJobs.Sum(r => r.CostPerPrint!.Value), 4)
|
||||
: (decimal?)null;
|
||||
|
||||
var aggregateWarnings = new List<string>();
|
||||
if (calculableJobs.Count < results.Count)
|
||||
{
|
||||
aggregateWarnings.Add(
|
||||
$"{results.Count - calculableJobs.Count} of {results.Count} print jobs have missing cost data. " +
|
||||
"Total cost reflects only jobs with complete data.");
|
||||
}
|
||||
|
||||
var response = new SpoolCostResponse
|
||||
{
|
||||
SpoolId = request.SpoolId,
|
||||
SpoolSerial = firstResult.SpoolSerial,
|
||||
PurchasePrice = firstResult.PurchasePrice,
|
||||
WeightTotalGrams = firstResult.WeightTotalGrams,
|
||||
CostPerGram = firstResult.CostPerGram,
|
||||
TotalGramsConsumed = results.Sum(r => r.GramsDerived),
|
||||
TotalCost = totalCost,
|
||||
JobCount = results.Count,
|
||||
Jobs = jobResponses,
|
||||
Warnings = aggregateWarnings
|
||||
};
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a domain CostPerPrintResult to an API CostPerPrintResponse DTO.
|
||||
/// </summary>
|
||||
private static CostPerPrintResponse MapCostToResponse(CostPerPrintResult r) => new()
|
||||
{
|
||||
PrintJobId = r.PrintJobId,
|
||||
PrintName = r.PrintName,
|
||||
SpoolId = r.SpoolId,
|
||||
SpoolSerial = r.SpoolSerial,
|
||||
MmExtruded = r.MmExtruded,
|
||||
GramsDerived = r.GramsDerived,
|
||||
PurchasePrice = r.PurchasePrice,
|
||||
WeightTotalGrams = r.WeightTotalGrams,
|
||||
CostPerGram = r.CostPerGram,
|
||||
CostPerPrint = r.CostPerPrint,
|
||||
Warnings = r.Warnings
|
||||
};
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Extrudex.API.DTOs.PrintJobs;
|
||||
|
||||
/// <summary>
|
||||
/// Response DTO for cost-per-print calculation. Contains the full cost
|
||||
/// breakdown and any warnings about missing or incomplete data.
|
||||
/// </summary>
|
||||
public class CostPerPrintResponse
|
||||
{
|
||||
/// <summary>The print job identifier this result belongs to.</summary>
|
||||
public Guid PrintJobId { get; set; }
|
||||
|
||||
/// <summary>Human-readable name of the print job.</summary>
|
||||
public string PrintName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The spool identifier that provided filament.</summary>
|
||||
public Guid SpoolId { get; set; }
|
||||
|
||||
/// <summary>Serial number of the spool.</summary>
|
||||
public string SpoolSerial { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Total millimeters of filament extruded.</summary>
|
||||
public decimal MmExtruded { get; set; }
|
||||
|
||||
/// <summary>Derived grams consumed for this print.</summary>
|
||||
public decimal GramsDerived { get; set; }
|
||||
|
||||
/// <summary>The spool's purchase price. Null if not recorded.</summary>
|
||||
public decimal? PurchasePrice { get; set; }
|
||||
|
||||
/// <summary>The spool's total weight in grams when full.</summary>
|
||||
public decimal? WeightTotalGrams { get; set; }
|
||||
|
||||
/// <summary>Cost per gram of filament. Null if purchase price or total weight is missing.</summary>
|
||||
public decimal? CostPerGram { get; set; }
|
||||
|
||||
/// <summary>Calculated cost of this print job. Null if cost data is incomplete.</summary>
|
||||
public decimal? CostPerPrint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Warnings about missing or incomplete data. Empty when all data is available
|
||||
/// and the calculation succeeded.
|
||||
/// </summary>
|
||||
public List<string> Warnings { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request DTO for batch cost calculation by spool. Returns cost breakdowns
|
||||
/// for all print jobs associated with the specified spool.
|
||||
/// </summary>
|
||||
public class SpoolCostRequest
|
||||
{
|
||||
/// <summary>The unique identifier of the spool to calculate costs for.</summary>
|
||||
[Required(ErrorMessage = "SpoolId is required.")]
|
||||
public Guid SpoolId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Response DTO for spool-level cost calculation. Contains cost breakdowns
|
||||
/// for all print jobs on the spool, plus a total cost summary.
|
||||
/// </summary>
|
||||
public class SpoolCostResponse
|
||||
{
|
||||
/// <summary>The spool identifier.</summary>
|
||||
public Guid SpoolId { get; set; }
|
||||
|
||||
/// <summary>Serial number of the spool.</summary>
|
||||
public string SpoolSerial { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The spool's purchase price. Null if not recorded.</summary>
|
||||
public decimal? PurchasePrice { get; set; }
|
||||
|
||||
/// <summary>The spool's total weight in grams when full.</summary>
|
||||
public decimal? WeightTotalGrams { get; set; }
|
||||
|
||||
/// <summary>Cost per gram of filament. Null if cost data is incomplete.</summary>
|
||||
public decimal? CostPerGram { get; set; }
|
||||
|
||||
/// <summary>Total grams consumed across all print jobs on this spool.</summary>
|
||||
public decimal TotalGramsConsumed { get; set; }
|
||||
|
||||
/// <summary>Total calculated cost across all print jobs. Null if any job has missing data.</summary>
|
||||
public decimal? TotalCost { get; set; }
|
||||
|
||||
/// <summary>Number of print jobs included in this calculation.</summary>
|
||||
public int JobCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Individual cost breakdowns per print job. Jobs with missing data
|
||||
/// will have null cost fields and populated warnings.
|
||||
/// </summary>
|
||||
public List<CostPerPrintResponse> Jobs { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Aggregate warnings about missing data across all jobs.
|
||||
/// </summary>
|
||||
public List<string> Warnings { get; set; } = new();
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
using Extrudex.Domain.Interfaces;
|
||||
using Extrudex.Infrastructure.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Extrudex.API.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Background job that periodically syncs filament usage data from
|
||||
/// Moonraker printers. Runs as a hosted service and polls all active
|
||||
/// Moonraker printers on a configurable interval to persist usage
|
||||
/// data to the Extrudex database.
|
||||
///
|
||||
/// Configuration is bound from the "FilamentUsageSync" section in
|
||||
/// appsettings.json. Set Enabled=false to disable without removing
|
||||
/// the service registration.
|
||||
/// </summary>
|
||||
public class FilamentUsageSyncJob : BackgroundService
|
||||
{
|
||||
private readonly IFilamentUsageSyncService _syncService;
|
||||
private readonly FilamentUsageSyncOptions _options;
|
||||
private readonly ILogger<FilamentUsageSyncJob> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new FilamentUsageSyncJob.
|
||||
/// </summary>
|
||||
/// <param name="syncService">The service that performs the actual sync logic.</param>
|
||||
/// <param name="options">Configuration options for polling interval and timeouts.</param>
|
||||
/// <param name="logger">Logger for diagnostic output.</param>
|
||||
public FilamentUsageSyncJob(
|
||||
IFilamentUsageSyncService syncService,
|
||||
IOptions<FilamentUsageSyncOptions> options,
|
||||
ILogger<FilamentUsageSyncJob> logger)
|
||||
{
|
||||
_syncService = syncService;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
_logger.LogInformation("Filament usage sync job is disabled via configuration — exiting");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"Filament usage sync job starting — polling every {Interval}",
|
||||
_options.PollingInterval);
|
||||
|
||||
// Delay briefly on startup to allow the web host to fully initialize
|
||||
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var syncedCount = await _syncService.SyncAllAsync(stoppingToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Filament usage sync completed — {SyncedCount} printer(s) synced. Next sync in {Interval}",
|
||||
syncedCount, _options.PollingInterval);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Error during filament usage sync cycle — will retry in {Interval}",
|
||||
_options.PollingInterval);
|
||||
}
|
||||
|
||||
await Task.Delay(_options.PollingInterval, stoppingToken);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Filament usage sync job shutting down");
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,6 @@ RUN dotnet publish Extrudex.csproj \
|
||||
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/*
|
||||
|
||||
# Non-root user for security
|
||||
RUN adduser --disabled-password --gecos "" appuser
|
||||
USER appuser
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
namespace Extrudex.Domain.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Service interface for calculating the cost of goods sold (COGS) per print job.
|
||||
/// Uses the spool's purchase price and the print job's derived grams consumed
|
||||
/// to produce a cost breakdown. Handles missing cost data gracefully by returning
|
||||
/// warnings rather than throwing exceptions.
|
||||
/// </summary>
|
||||
public interface ICostPerPrintService
|
||||
{
|
||||
/// <summary>
|
||||
/// Calculates the cost per print for a specific print job.
|
||||
/// </summary>
|
||||
/// <param name="printJobId">The unique identifier of the print job.</param>
|
||||
/// <param name="cancellationToken">Optional cancellation token.</param>
|
||||
/// <returns>
|
||||
/// A <see cref="CostPerPrintResult"/> containing the cost breakdown,
|
||||
/// or warnings if cost data is missing or incomplete.
|
||||
/// </returns>
|
||||
Task<CostPerPrintResult> CalculateAsync(Guid printJobId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Calculates cost breakdowns for all print jobs associated with a specific spool.
|
||||
/// Useful for spool-level COGS reporting.
|
||||
/// </summary>
|
||||
/// <param name="spoolId">The unique identifier of the spool.</param>
|
||||
/// <param name="cancellationToken">Optional cancellation token.</param>
|
||||
/// <returns>
|
||||
/// A list of <see cref="CostPerPrintResult"/> for each print job on the spool.
|
||||
/// Jobs with missing cost data will include warnings.
|
||||
/// </returns>
|
||||
Task<IReadOnlyList<CostPerPrintResult>> CalculateBySpoolAsync(Guid spoolId, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of a cost-per-print calculation. Contains the cost breakdown
|
||||
/// and any warnings about missing or incomplete cost data.
|
||||
/// </summary>
|
||||
public class CostPerPrintResult
|
||||
{
|
||||
/// <summary>The print job identifier this result belongs to.</summary>
|
||||
public Guid PrintJobId { get; set; }
|
||||
|
||||
/// <summary>Human-readable name of the print job.</summary>
|
||||
public string PrintName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The spool identifier that provided filament.</summary>
|
||||
public Guid SpoolId { get; set; }
|
||||
|
||||
/// <summary>Serial number of the spool.</summary>
|
||||
public string SpoolSerial { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Total millimeters of filament extruded.</summary>
|
||||
public decimal MmExtruded { get; set; }
|
||||
|
||||
/// <summary>Derived grams consumed for this print.</summary>
|
||||
public decimal GramsDerived { get; set; }
|
||||
|
||||
/// <summary>The spool's purchase price. Null if not recorded.</summary>
|
||||
public decimal? PurchasePrice { get; set; }
|
||||
|
||||
/// <summary>The spool's total weight in grams when full.</summary>
|
||||
public decimal? WeightTotalGrams { get; set; }
|
||||
|
||||
/// <summary>Cost per gram of filament. Null if purchase price or total weight is missing.</summary>
|
||||
public decimal? CostPerGram { get; set; }
|
||||
|
||||
/// <summary>Calculated cost of this print job. Null if cost data is incomplete.</summary>
|
||||
public decimal? CostPerPrint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Warnings about missing or incomplete data that prevented a full calculation.
|
||||
/// Empty when all data is available and the calculation succeeded.
|
||||
/// </summary>
|
||||
public List<string> Warnings { get; set; } = new();
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
namespace Extrudex.Domain.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Service interface for syncing filament usage data from printers
|
||||
/// into the Extrudex database. Handles querying Moonraker printers,
|
||||
/// computing derived usage metrics, and persisting updates to spools
|
||||
/// and print job records.
|
||||
/// </summary>
|
||||
public interface IFilamentUsageSyncService
|
||||
{
|
||||
/// <summary>
|
||||
/// Performs a single sync cycle: queries all active Moonraker printers,
|
||||
/// fetches their current filament usage data, and persists updates to
|
||||
/// the database.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token for graceful shutdown.</param>
|
||||
/// <returns>The number of printers successfully synced.</returns>
|
||||
Task<int> SyncAllAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
namespace Extrudex.Domain.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Client interface for communicating with Moonraker REST API endpoints
|
||||
/// on Klipper-based printers (e.g., Elegoo Centauri Carbon).
|
||||
/// Used to retrieve filament usage data, print job status, and
|
||||
/// remaining spool weight from the printer.
|
||||
/// </summary>
|
||||
public interface IMoonrakerClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Fetches the current filament usage data from the Moonraker server.
|
||||
/// Returns a dictionary of usage metrics reported by the printer.
|
||||
/// </summary>
|
||||
/// <param name="hostnameOrIp">The printer's hostname or IP address.</param>
|
||||
/// <param name="port">The Moonraker API port (default: 7125).</param>
|
||||
/// <param name="apiKey">Optional API key for authentication.</param>
|
||||
/// <param name="cancellationToken">Cancellation token for the HTTP request.</param>
|
||||
/// <returns>A dictionary of usage metric names to their decimal values.</returns>
|
||||
Task<Dictionary<string, decimal>> GetFilamentUsageAsync(
|
||||
string hostnameOrIp,
|
||||
int port,
|
||||
string? apiKey,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the Moonraker server is reachable and responding.
|
||||
/// </summary>
|
||||
/// <param name="hostnameOrIp">The printer's hostname or IP address.</param>
|
||||
/// <param name="port">The Moonraker API port (default: 7125).</param>
|
||||
/// <param name="apiKey">Optional API key for authentication.</param>
|
||||
/// <param name="cancellationToken">Cancellation token for the HTTP request.</param>
|
||||
/// <returns><c>true</c> if the server responded successfully; otherwise <c>false</c>.</returns>
|
||||
Task<bool> IsReachableAsync(
|
||||
string hostnameOrIp,
|
||||
int port,
|
||||
string? apiKey,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
namespace Extrudex.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration options for the FilamentUsageSync background job.
|
||||
/// Bound from appsettings.json under the "FilamentUsageSync" section.
|
||||
/// Controls polling interval and per-printer timeout settings.
|
||||
/// </summary>
|
||||
public class FilamentUsageSyncOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// The section name in appsettings.json where these options are bound.
|
||||
/// </summary>
|
||||
public const string SectionName = "FilamentUsageSync";
|
||||
|
||||
/// <summary>
|
||||
/// How often the background job polls printers for usage data.
|
||||
/// Default: 5 minutes. Minimum recommended: 1 minute.
|
||||
/// </summary>
|
||||
public TimeSpan PollingInterval { get; set; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>
|
||||
/// Timeout for individual HTTP requests to a Moonraker printer.
|
||||
/// Default: 30 seconds.
|
||||
/// </summary>
|
||||
public TimeSpan RequestTimeout { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the sync job is enabled. Set to false to disable
|
||||
/// the background job without removing its registration.
|
||||
/// Default: true.
|
||||
/// </summary>
|
||||
public bool Enabled { get; set; } = true;
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
using Extrudex.Domain.Interfaces;
|
||||
using Extrudex.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Extrudex.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the cost of goods sold (COGS) per print job using the spool's
|
||||
/// purchase price and the print job's derived grams consumed.
|
||||
///
|
||||
/// Formula:
|
||||
/// cost_per_gram = purchase_price / weight_total_grams
|
||||
/// cost_per_print = grams_derived × cost_per_gram
|
||||
///
|
||||
/// Handles missing data gracefully — if the spool has no purchase price or
|
||||
/// weight recorded, the result includes warnings and null cost fields
|
||||
/// instead of throwing exceptions.
|
||||
/// </summary>
|
||||
public class CostPerPrintService : ICostPerPrintService
|
||||
{
|
||||
private readonly ExtrudexDbContext _dbContext;
|
||||
private readonly ILogger<CostPerPrintService> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CostPerPrintService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="dbContext">The database context for data access.</param>
|
||||
/// <param name="logger">The logger for diagnostic output.</param>
|
||||
public CostPerPrintService(ExtrudexDbContext dbContext, ILogger<CostPerPrintService> logger)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<CostPerPrintResult> CalculateAsync(Guid printJobId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_logger.LogDebug("Calculating cost per print for job {PrintJobId}", printJobId);
|
||||
|
||||
var job = await _dbContext.PrintJobs
|
||||
.Include(j => j.Spool)
|
||||
.ThenInclude(s => s!.MaterialBase)
|
||||
.FirstOrDefaultAsync(j => j.Id == printJobId, cancellationToken);
|
||||
|
||||
if (job is null)
|
||||
{
|
||||
_logger.LogWarning("Print job {PrintJobId} not found for cost calculation", printJobId);
|
||||
return new CostPerPrintResult
|
||||
{
|
||||
PrintJobId = printJobId,
|
||||
Warnings = new List<string> { $"Print job with ID '{printJobId}' not found." }
|
||||
};
|
||||
}
|
||||
|
||||
return BuildResult(job);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<CostPerPrintResult>> CalculateBySpoolAsync(
|
||||
Guid spoolId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_logger.LogDebug("Calculating cost per print for all jobs on spool {SpoolId}", spoolId);
|
||||
|
||||
var jobs = await _dbContext.PrintJobs
|
||||
.Include(j => j.Spool)
|
||||
.ThenInclude(s => s!.MaterialBase)
|
||||
.Where(j => j.SpoolId == spoolId)
|
||||
.OrderByDescending(j => j.CreatedAt)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (jobs.Count == 0)
|
||||
{
|
||||
_logger.LogDebug("No print jobs found for spool {SpoolId}", spoolId);
|
||||
return Array.Empty<CostPerPrintResult>();
|
||||
}
|
||||
|
||||
return jobs.Select(BuildResult).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a <see cref="CostPerPrintResult"/> from a print job entity.
|
||||
/// Computes cost_per_gram and cost_per_print when all required data is available.
|
||||
/// Populates warnings when data is missing or incomplete.
|
||||
/// </summary>
|
||||
/// <param name="job">The print job entity with Spool navigation loaded.</param>
|
||||
/// <returns>A cost calculation result with breakdown and any warnings.</returns>
|
||||
private CostPerPrintResult BuildResult(Domain.Entities.PrintJob job)
|
||||
{
|
||||
var warnings = new List<string>();
|
||||
var spool = job.Spool;
|
||||
|
||||
// Map what we always have
|
||||
var result = new CostPerPrintResult
|
||||
{
|
||||
PrintJobId = job.Id,
|
||||
PrintName = job.PrintName,
|
||||
SpoolId = job.SpoolId,
|
||||
SpoolSerial = spool?.SpoolSerial ?? string.Empty,
|
||||
MmExtruded = job.MmExtruded,
|
||||
GramsDerived = job.GramsDerived,
|
||||
};
|
||||
|
||||
// Guard: spool must be loaded
|
||||
if (spool is null)
|
||||
{
|
||||
warnings.Add("Spool data is not available for this print job.");
|
||||
result.Warnings = warnings;
|
||||
return result;
|
||||
}
|
||||
|
||||
// Capture purchase price
|
||||
result.PurchasePrice = spool.PurchasePrice;
|
||||
result.WeightTotalGrams = spool.WeightTotalGrams;
|
||||
|
||||
// Check for missing purchase price
|
||||
if (!spool.PurchasePrice.HasValue)
|
||||
{
|
||||
warnings.Add(
|
||||
"Spool purchase price is not recorded. Cost calculation requires a purchase price on the spool.");
|
||||
}
|
||||
|
||||
// Check for zero or negative weight — prevents division by zero
|
||||
if (spool.WeightTotalGrams <= 0)
|
||||
{
|
||||
warnings.Add(
|
||||
"Spool total weight is zero or not recorded. Cost calculation requires a positive weight_total_grams on the spool.");
|
||||
}
|
||||
|
||||
// Check for zero grams derived
|
||||
if (job.GramsDerived <= 0)
|
||||
{
|
||||
warnings.Add(
|
||||
"Derived grams consumed is zero. Ensure mm_extruded, filament diameter, and material density are recorded for this print job.");
|
||||
}
|
||||
|
||||
// If all data is present and valid, compute the cost
|
||||
if (spool.PurchasePrice.HasValue && spool.WeightTotalGrams > 0 && job.GramsDerived > 0)
|
||||
{
|
||||
var costPerGram = spool.PurchasePrice.Value / spool.WeightTotalGrams;
|
||||
result.CostPerGram = Math.Round(costPerGram, 6);
|
||||
result.CostPerPrint = Math.Round(job.GramsDerived * costPerGram, 4);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Cost calculated for job {PrintJobId}: {GramsDerived}g × {CostPerGram:C}/g = {CostPerPrint:C}",
|
||||
job.Id, job.GramsDerived, result.CostPerGram, result.CostPerPrint);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Cost calculation incomplete for job {PrintJobId}: missing data (warnings: {WarningCount})",
|
||||
job.Id, warnings.Count);
|
||||
}
|
||||
|
||||
result.Warnings = warnings;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
using Extrudex.Domain.Enums;
|
||||
using Extrudex.Domain.Interfaces;
|
||||
using Extrudex.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Extrudex.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Service that syncs filament usage data from Moonraker printers into the
|
||||
/// Extrudex database. Queries all active Moonraker printers, fetches their
|
||||
/// current filament usage metrics, and updates spool remaining weights and
|
||||
/// print job records.
|
||||
/// </summary>
|
||||
public class FilamentUsageSyncService : IFilamentUsageSyncService
|
||||
{
|
||||
private readonly ExtrudexDbContext _dbContext;
|
||||
private readonly IMoonrakerClient _moonrakerClient;
|
||||
private readonly ILogger<FilamentUsageSyncService> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new FilamentUsageSyncService.
|
||||
/// </summary>
|
||||
/// <param name="dbContext">The EF Core database context for persisting updates.</param>
|
||||
/// <param name="moonrakerClient">The Moonraker HTTP client for fetching printer data.</param>
|
||||
/// <param name="logger">Logger for diagnostic output.</param>
|
||||
public FilamentUsageSyncService(
|
||||
ExtrudexDbContext dbContext,
|
||||
IMoonrakerClient moonrakerClient,
|
||||
ILogger<FilamentUsageSyncService> logger)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_moonrakerClient = moonrakerClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> SyncAllAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_logger.LogInformation("Starting filament usage sync cycle");
|
||||
|
||||
var printers = await _dbContext.Printers
|
||||
.Where(p => p.IsActive && p.ConnectionType == ConnectionType.Moonraker)
|
||||
.Include(p => p.AmsUnits)
|
||||
.ThenInclude(u => u.Slots)
|
||||
.ThenInclude(s => s.Spool)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (printers.Count == 0)
|
||||
{
|
||||
_logger.LogInformation("No active Moonraker printers found — skipping sync");
|
||||
return 0;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Found {PrinterCount} active Moonraker printer(s) to sync", printers.Count);
|
||||
|
||||
var syncedCount = 0;
|
||||
|
||||
foreach (var printer in printers)
|
||||
{
|
||||
try
|
||||
{
|
||||
var usageData = await _moonrakerClient.GetFilamentUsageAsync(
|
||||
printer.HostnameOrIp,
|
||||
printer.Port,
|
||||
printer.ApiKey,
|
||||
cancellationToken);
|
||||
|
||||
if (usageData.Count == 0)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"No usage data returned from printer {PrinterName} ({Host}:{Port})",
|
||||
printer.Name, printer.HostnameOrIp, printer.Port);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Update spool remaining weights from AMS data
|
||||
UpdateSpoolWeights(printer, usageData);
|
||||
|
||||
// Mark printer as seen and idle (reachable = idle, not printing)
|
||||
printer.LastSeenAt = DateTime.UtcNow;
|
||||
printer.Status = PrinterStatus.Idle;
|
||||
|
||||
syncedCount++;
|
||||
_logger.LogInformation(
|
||||
"Successfully synced filament usage from printer {PrinterName}",
|
||||
printer.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Error syncing filament usage from printer {PrinterName} ({Host}:{Port})",
|
||||
printer.Name, printer.HostnameOrIp, printer.Port);
|
||||
}
|
||||
}
|
||||
|
||||
await _dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Filament usage sync cycle complete — {SyncedCount}/{TotalCount} printers synced",
|
||||
syncedCount, printers.Count);
|
||||
|
||||
return syncedCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates spool remaining weights based on usage data received from Moonraker.
|
||||
/// For printers with AMS units, updates the remaining weight on each slot's spool.
|
||||
/// </summary>
|
||||
private void UpdateSpoolWeights(
|
||||
Domain.Entities.Printer printer,
|
||||
Dictionary<string, decimal> usageData)
|
||||
{
|
||||
// Update AMS slot remaining weights if available
|
||||
foreach (var amsUnit in printer.AmsUnits)
|
||||
{
|
||||
foreach (var slot in amsUnit.Slots)
|
||||
{
|
||||
if (slot.Spool != null && slot.RemainingWeightG.HasValue)
|
||||
{
|
||||
// Sync the AMS-reported remaining weight to the spool
|
||||
slot.Spool.WeightRemainingGrams = slot.RemainingWeightG.Value;
|
||||
|
||||
_logger.LogDebug(
|
||||
"Updated spool {SpoolSerial} remaining weight to {Weight}g",
|
||||
slot.Spool.SpoolSerial, slot.RemainingWeightG.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If usage data contains extruded mm, log it for observability
|
||||
if (usageData.TryGetValue("mm_extruded", out var mmExtruded) && mmExtruded > 0)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Printer {PrinterName} reports {MmExtruded}mm filament extruded in latest job",
|
||||
printer.Name, mmExtruded);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Extrudex.Domain.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Extrudex.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP client for communicating with Moonraker REST API endpoints
|
||||
/// on Klipper-based printers (e.g., Elegoo Centauri Carbon).
|
||||
/// Retrieves filament usage data and printer status information.
|
||||
/// </summary>
|
||||
public class MoonrakerClient : IMoonrakerClient
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly ILogger<MoonrakerClient> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new MoonrakerClient with the configured HTTP client and logger.
|
||||
/// </summary>
|
||||
/// <param name="httpClient">The HTTP client for making requests to Moonraker endpoints.</param>
|
||||
/// <param name="logger">Logger for diagnostic output.</param>
|
||||
public MoonrakerClient(HttpClient httpClient, ILogger<MoonrakerClient> logger)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Dictionary<string, decimal>> GetFilamentUsageAsync(
|
||||
string hostnameOrIp,
|
||||
int port,
|
||||
string? apiKey,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var baseUrl = BuildBaseUrl(hostnameOrIp, port);
|
||||
var result = new Dictionary<string, decimal>();
|
||||
|
||||
try
|
||||
{
|
||||
// Query Moonraker server info endpoint for filament usage data
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, $"{baseUrl}/server/history/items?limit=1");
|
||||
if (!string.IsNullOrEmpty(apiKey))
|
||||
{
|
||||
request.Headers.Add("X-Api-Key", apiKey);
|
||||
}
|
||||
|
||||
using var response = await _httpClient.SendAsync(request, cancellationToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var json = await response.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: cancellationToken);
|
||||
|
||||
// Extract filament usage from the response
|
||||
// Moonraker returns job history with filament_used and similar fields
|
||||
if (json.TryGetProperty("result", out var resultElement))
|
||||
{
|
||||
if (resultElement.TryGetProperty("items", out var items) && items.GetArrayLength() > 0)
|
||||
{
|
||||
var job = items[0];
|
||||
|
||||
// Moonraker tracks filament_used in millimeters
|
||||
if (job.TryGetProperty("filament_used", out var filamentUsed))
|
||||
{
|
||||
result["mm_extruded"] = filamentUsed.GetDecimal();
|
||||
}
|
||||
|
||||
// Total duration in seconds
|
||||
if (job.TryGetProperty("print_duration", out var duration))
|
||||
{
|
||||
result["print_duration_seconds"] = duration.GetDecimal();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"Retrieved filament usage from Moonraker at {Host}:{Port}: {MetricCount} metrics",
|
||||
hostnameOrIp, port, result.Count);
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Failed to retrieve filament usage from Moonraker at {Host}:{Port}",
|
||||
hostnameOrIp, port);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Failed to parse Moonraker response from {Host}:{Port}",
|
||||
hostnameOrIp, port);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> IsReachableAsync(
|
||||
string hostnameOrIp,
|
||||
int port,
|
||||
string? apiKey,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var baseUrl = BuildBaseUrl(hostnameOrIp, port);
|
||||
|
||||
try
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, $"{baseUrl}/server/info");
|
||||
if (!string.IsNullOrEmpty(apiKey))
|
||||
{
|
||||
request.Headers.Add("X-Api-Key", apiKey);
|
||||
}
|
||||
|
||||
using var response = await _httpClient.SendAsync(request, cancellationToken);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
_logger.LogDebug("Moonraker at {Host}:{Port} is not reachable", hostnameOrIp, port);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the base URL for Moonraker API calls from hostname and port.
|
||||
/// </summary>
|
||||
private static string BuildBaseUrl(string hostnameOrIp, int port)
|
||||
{
|
||||
return $"http://{hostnameOrIp}:{port}";
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
using System.Reflection;
|
||||
using Extrudex.API.Filters;
|
||||
using Extrudex.API.Hubs;
|
||||
using Extrudex.API.Jobs;
|
||||
using Extrudex.Domain.Interfaces;
|
||||
using Extrudex.Infrastructure.Configuration;
|
||||
using Extrudex.Infrastructure.Data;
|
||||
using Extrudex.Infrastructure.Services;
|
||||
using FluentValidation;
|
||||
@@ -52,9 +50,6 @@ builder.Services.AddSwaggerGen(c =>
|
||||
// ── QR Code Generation ──────────────────────────────────────
|
||||
builder.Services.AddSingleton<IQrCodeService, QrCodeService>();
|
||||
|
||||
// ── Cost Per Print Calculation ─────────────────────────────
|
||||
builder.Services.AddScoped<ICostPerPrintService, CostPerPrintService>();
|
||||
|
||||
// ── FluentValidation ──────────────────────────────────────
|
||||
// Registers all validators from the API assembly into DI.
|
||||
builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
|
||||
@@ -82,16 +77,6 @@ builder.Services.AddCors(options =>
|
||||
// ── SignalR (real-time printer updates) ────────────────────
|
||||
builder.Services.AddSignalR();
|
||||
|
||||
// ── Filament Usage Sync (Background Job) ──────────────────
|
||||
builder.Services.Configure<FilamentUsageSyncOptions>(
|
||||
builder.Configuration.GetSection(FilamentUsageSyncOptions.SectionName));
|
||||
builder.Services.AddHttpClient<IMoonrakerClient, MoonrakerClient>(client =>
|
||||
{
|
||||
client.DefaultRequestHeaders.Add("User-Agent", "Extrudex/1.0");
|
||||
});
|
||||
builder.Services.AddScoped<IFilamentUsageSyncService, FilamentUsageSyncService>();
|
||||
builder.Services.AddHostedService<FilamentUsageSyncJob>();
|
||||
|
||||
// ── Health Checks ───────────────────────────────────────────
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddNpgSql(connectionString);
|
||||
|
||||
@@ -8,10 +8,5 @@
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"ExtrudexDb": "Host=localhost;Port=5432;Database=extrudex_dev;Username=extrudex;Password=changeme"
|
||||
},
|
||||
"FilamentUsageSync": {
|
||||
"PollingInterval": "00:01:00",
|
||||
"RequestTimeout": "00:00:30",
|
||||
"Enabled": true
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,5 @@
|
||||
"AllowedHosts": "*",
|
||||
"ConnectionStrings": {
|
||||
"ExtrudexDb": "Host=localhost;Port=5432;Database=extrudex;Username=extrudex;Password=changeme"
|
||||
},
|
||||
"FilamentUsageSync": {
|
||||
"PollingInterval": "00:05:00",
|
||||
"RequestTimeout": "00:00:30",
|
||||
"Enabled": true
|
||||
}
|
||||
}
|
||||
@@ -18,14 +18,13 @@ echo "📦 Building and starting services..."
|
||||
$COMPOSE_CMD -f docker-compose.dev.yml up -d --build
|
||||
|
||||
echo "⏳ Waiting for services to become healthy..."
|
||||
sleep 15
|
||||
sleep 10
|
||||
|
||||
echo "✅ Deployment complete!"
|
||||
echo ""
|
||||
echo "Services running:"
|
||||
echo " • PostgreSQL: localhost:5433"
|
||||
echo " • Extrudex API: http://localhost:5080"
|
||||
echo " • Extrudex Web: http://localhost:5081"
|
||||
echo " • Control Center Web: http://localhost:5081"
|
||||
echo ""
|
||||
echo "To view logs:"
|
||||
echo " $COMPOSE_CMD -f docker-compose.dev.yml logs -f"
|
||||
|
||||
@@ -1,25 +1,6 @@
|
||||
services:
|
||||
extrudex-db:
|
||||
image: postgres:16-alpine
|
||||
container_name: extrudex-db
|
||||
environment:
|
||||
POSTGRES_USER: extrudex
|
||||
POSTGRES_PASSWORD: changeme
|
||||
POSTGRES_DB: extrudex
|
||||
ports:
|
||||
- "5433:5432"
|
||||
volumes:
|
||||
- extrudex-db-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U extrudex"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- extrudex-network
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
extrudex-api:
|
||||
build:
|
||||
context: ./backend
|
||||
@@ -30,14 +11,6 @@ services:
|
||||
environment:
|
||||
- ASPNETCORE_ENVIRONMENT=Development
|
||||
- ASPNETCORE_URLS=http://+:8080
|
||||
- EXTRUDEX_DB_HOST=extrudex-db
|
||||
- EXTRUDEX_DB_PORT=5432
|
||||
- EXTRUDEX_DB_NAME=extrudex
|
||||
- EXTRUDEX_DB_USER=extrudex
|
||||
- EXTRUDEX_DB_PASSWORD=changeme
|
||||
depends_on:
|
||||
extrudex-db:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
|
||||
@@ -48,11 +21,11 @@ services:
|
||||
networks:
|
||||
- extrudex-network
|
||||
|
||||
extrudex-web:
|
||||
control-center-web:
|
||||
build:
|
||||
context: ./frontend
|
||||
context: ../Control-Center/frontend
|
||||
dockerfile: Dockerfile
|
||||
container_name: extrudex-web
|
||||
container_name: control-center-web
|
||||
ports:
|
||||
- "5081:80"
|
||||
depends_on:
|
||||
@@ -62,9 +35,6 @@ services:
|
||||
networks:
|
||||
- extrudex-network
|
||||
|
||||
volumes:
|
||||
extrudex-db-data:
|
||||
|
||||
networks:
|
||||
extrudex-network:
|
||||
driver: bridge
|
||||
@@ -1,11 +1,15 @@
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes)
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
provideAnimationsAsync(),
|
||||
]
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,225 @@
|
||||
<!-- 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>
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
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,11 +1,15 @@
|
||||
<!-- Filament Inventory Table — with filters and low stock indicators -->
|
||||
<!-- Filament Inventory Table — with 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" />
|
||||
<!-- Header Row: title + Add button -->
|
||||
<div class="table-header">
|
||||
<h2 class="table-title">Filament Inventory</h2>
|
||||
<button mat-raised-button color="primary" (click)="openAddDialog()"
|
||||
aria-label="Add filament" class="add-btn">
|
||||
<mat-icon aria-hidden="true">add</mat-icon>
|
||||
Add Filament
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Low Stock Alert Banner — shown when critical or low stock spools exist -->
|
||||
@if (criticalCount() > 0) {
|
||||
@@ -22,7 +26,7 @@
|
||||
|
||||
<!-- Filament Table -->
|
||||
<table mat-table
|
||||
[dataSource]="filteredFilaments()"
|
||||
[dataSource]="sortedFilaments()"
|
||||
matSort
|
||||
(matSortChange)="sortData($event)"
|
||||
class="filament-table"
|
||||
@@ -112,6 +116,20 @@
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<!-- Actions Column -->
|
||||
<ng-container matColumnDef="actions">
|
||||
<th mat-header-cell *matHeaderCellDef></th>
|
||||
<td mat-cell *matCellDef="let filament" class="actions-cell">
|
||||
<button mat-icon-button
|
||||
[matTooltip]="'Edit ' + filament.brand + ' ' + filament.colorName"
|
||||
matTooltipPosition="above"
|
||||
aria-label="Edit filament"
|
||||
(click)="openEditDialog(filament)">
|
||||
<mat-icon>edit</mat-icon>
|
||||
</button>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<tr mat-header-row *matHeaderRowDef="columns()"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: columns();"
|
||||
[class.row-critical]="classifyStockLevel(row) === 'critical'"
|
||||
@@ -119,15 +137,7 @@
|
||||
</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 -->
|
||||
<!-- Empty state -->
|
||||
@if (filaments().length === 0) {
|
||||
<div class="empty-state" role="status">
|
||||
<mat-icon aria-hidden="true">inventory_2</mat-icon>
|
||||
|
||||
@@ -22,6 +22,35 @@ $color-inactive: #94a3b8; // Gray — inactive spool
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
// Header row: title + add button
|
||||
.table-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: $spacing-unit * 2;
|
||||
flex-wrap: wrap;
|
||||
gap: $spacing-unit;
|
||||
|
||||
.table-title {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.add-btn {
|
||||
min-height: $touch-target-min;
|
||||
mat-icon {
|
||||
margin-right: 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actions cell
|
||||
.actions-cell {
|
||||
text-align: center;
|
||||
width: 56px;
|
||||
}
|
||||
|
||||
// Alert banner for low stock warnings
|
||||
.alert-banner {
|
||||
display: flex;
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
Component,
|
||||
Input,
|
||||
computed,
|
||||
inject,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
@@ -12,13 +13,18 @@ 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 { MatButtonModule } from '@angular/material/button';
|
||||
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
|
||||
import {
|
||||
Filament,
|
||||
StockLevel,
|
||||
getRemainingPercent,
|
||||
classifyStockLevel,
|
||||
} from '../../models/filament.model';
|
||||
import {
|
||||
FilamentDialogComponent,
|
||||
FilamentDialogData,
|
||||
} from '../filament-dialog/filament-dialog.component';
|
||||
|
||||
/** Display column definitions for the filament table */
|
||||
export type FilamentColumn =
|
||||
@@ -28,7 +34,8 @@ export type FilamentColumn =
|
||||
| 'serial'
|
||||
| 'remaining'
|
||||
| 'stockLevel'
|
||||
| 'status';
|
||||
| 'status'
|
||||
| 'actions';
|
||||
|
||||
@Component({
|
||||
selector: 'app-filament-table',
|
||||
@@ -41,13 +48,16 @@ export type FilamentColumn =
|
||||
MatProgressBarModule,
|
||||
MatTooltipModule,
|
||||
MatSortModule,
|
||||
FilamentFilterComponent,
|
||||
MatButtonModule,
|
||||
MatDialogModule,
|
||||
],
|
||||
templateUrl: './filament-table.component.html',
|
||||
styleUrl: './filament-table.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class FilamentTableComponent {
|
||||
private readonly dialog = inject(MatDialog);
|
||||
|
||||
/** Filament data input — reactive signal for live updates */
|
||||
readonly filaments = signal<Filament[]>([]);
|
||||
|
||||
@@ -67,29 +77,15 @@ export class FilamentTableComponent {
|
||||
'remaining',
|
||||
'stockLevel',
|
||||
'status',
|
||||
'actions',
|
||||
]);
|
||||
|
||||
/** 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(
|
||||
@@ -228,9 +224,6 @@ export class FilamentTableComponent {
|
||||
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()];
|
||||
@@ -272,46 +265,6 @@ export class FilamentTableComponent {
|
||||
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;
|
||||
|
||||
@@ -353,6 +306,47 @@ export class FilamentTableComponent {
|
||||
}
|
||||
return `${Math.round(grams)}g`;
|
||||
}
|
||||
|
||||
/** Open the add filament dialog. */
|
||||
openAddDialog(): void {
|
||||
const data: FilamentDialogData = {};
|
||||
const ref = this.dialog.open(FilamentDialogComponent, {
|
||||
width: '600px',
|
||||
maxWidth: '95vw',
|
||||
data,
|
||||
autoFocus: 'first-typable',
|
||||
});
|
||||
|
||||
ref.afterClosed().subscribe((result: boolean) => {
|
||||
if (result) {
|
||||
this.onFilamentSaved();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Open the edit filament dialog for a specific spool. */
|
||||
openEditDialog(filament: Filament): void {
|
||||
const data: FilamentDialogData = { filament };
|
||||
const ref = this.dialog.open(FilamentDialogComponent, {
|
||||
width: '600px',
|
||||
maxWidth: '95vw',
|
||||
data,
|
||||
autoFocus: 'first-typable',
|
||||
});
|
||||
|
||||
ref.afterClosed().subscribe((result: boolean) => {
|
||||
if (result) {
|
||||
this.onFilamentSaved();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Called after a successful save — reload filament data. */
|
||||
protected onFilamentSaved(): void {
|
||||
// TODO: Replace with FilamentService.refresh() call when SignalR integration is ready.
|
||||
// For now, this is the hook for refreshing data after a save.
|
||||
// Consumers can override or listen to signal changes.
|
||||
}
|
||||
}
|
||||
|
||||
/** Compare helper for sorting */
|
||||
|
||||
50
frontend/src/app/models/material.model.ts
Normal file
50
frontend/src/app/models/material.model.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
13
frontend/src/app/models/paged-response.model.ts
Normal file
13
frontend/src/app/models/paged-response.model.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
134
frontend/src/app/services/filament.service.ts
Normal file
134
frontend/src/app/services/filament.service.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
import { environment } from '../../environments/environment';
|
||||
import { Filament } from '../models/filament.model';
|
||||
import { PagedResponse } from '../models/paged-response.model';
|
||||
import {
|
||||
MaterialBase,
|
||||
MaterialFinish,
|
||||
MaterialModifier,
|
||||
} from '../models/material.model';
|
||||
|
||||
/**
|
||||
* Request body for creating a new filament spool.
|
||||
* Matches the backend CreateFilamentRequest DTO.
|
||||
*/
|
||||
export interface CreateFilamentRequest {
|
||||
materialBaseId: string;
|
||||
materialFinishId: string;
|
||||
materialModifierId: string | null;
|
||||
brand: string;
|
||||
colorName: string;
|
||||
colorHex: string;
|
||||
weightTotalGrams: number;
|
||||
weightRemainingGrams: number;
|
||||
filamentDiameterMm: number;
|
||||
spoolSerial: string;
|
||||
purchasePrice: number | null;
|
||||
purchaseDate: string | null;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request body for updating an existing filament spool.
|
||||
* Matches the backend UpdateFilamentRequest DTO.
|
||||
*/
|
||||
export interface UpdateFilamentRequest {
|
||||
materialBaseId: string;
|
||||
materialFinishId: string;
|
||||
materialModifierId: string | null;
|
||||
brand: string;
|
||||
colorName: string;
|
||||
colorHex: string;
|
||||
weightTotalGrams: number;
|
||||
weightRemainingGrams: number;
|
||||
filamentDiameterMm: number;
|
||||
spoolSerial: string;
|
||||
purchasePrice: number | null;
|
||||
purchaseDate: string | null;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for interacting with the Extrudex filament and material APIs.
|
||||
* Handles CRUD for filament spools and material lookup data.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class FilamentService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly baseUrl = environment.apiBaseUrl;
|
||||
|
||||
// ── Filament CRUD ────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get a paginated list of filament spools.
|
||||
*/
|
||||
getFilaments(params?: {
|
||||
pageNumber?: number;
|
||||
pageSize?: number;
|
||||
materialBaseId?: string;
|
||||
materialFinishId?: string;
|
||||
materialModifierId?: string;
|
||||
brand?: string;
|
||||
isActive?: boolean;
|
||||
}): Observable<PagedResponse<Filament>> {
|
||||
return this.http.get<PagedResponse<Filament>>(
|
||||
`${this.baseUrl}/api/filaments`,
|
||||
{ params: params as Record<string, string | number | boolean> }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single filament spool by ID.
|
||||
*/
|
||||
getFilament(id: string): Observable<Filament> {
|
||||
return this.http.get<Filament>(`${this.baseUrl}/api/filaments/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new filament spool.
|
||||
*/
|
||||
createFilament(request: CreateFilamentRequest): Observable<Filament> {
|
||||
return this.http.post<Filament>(`${this.baseUrl}/api/filaments`, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing filament spool.
|
||||
*/
|
||||
updateFilament(id: string, request: UpdateFilamentRequest): Observable<Filament> {
|
||||
return this.http.put<Filament>(`${this.baseUrl}/api/filaments/${id}`, request);
|
||||
}
|
||||
|
||||
// ── Material Lookups ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get all material bases (PLA, PETG, ABS, etc.).
|
||||
*/
|
||||
getMaterialBases(): Observable<MaterialBase[]> {
|
||||
return this.http.get<MaterialBase[]>(`${this.baseUrl}/api/materials/bases`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all material finishes, optionally filtered by material base.
|
||||
*/
|
||||
getMaterialFinishes(materialBaseId?: string): Observable<MaterialFinish[]> {
|
||||
const params: Record<string, string> = {};
|
||||
if (materialBaseId) {
|
||||
params['materialBaseId'] = materialBaseId;
|
||||
}
|
||||
return this.http.get<MaterialFinish[]>(`${this.baseUrl}/api/materials/finishes`, { params });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all material modifiers, optionally filtered by material base.
|
||||
*/
|
||||
getMaterialModifiers(materialBaseId?: string): Observable<MaterialModifier[]> {
|
||||
const params: Record<string, string> = {};
|
||||
if (materialBaseId) {
|
||||
params['materialBaseId'] = materialBaseId;
|
||||
}
|
||||
return this.http.get<MaterialModifier[]>(`${this.baseUrl}/api/materials/modifiers`, { params });
|
||||
}
|
||||
}
|
||||
8
frontend/src/environments/environment.prod.ts
Normal file
8
frontend/src/environments/environment.prod.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Environment configuration for the Extrudex frontend (production).
|
||||
* Override API URL for deployed environments.
|
||||
*/
|
||||
export const environment = {
|
||||
production: true,
|
||||
apiBaseUrl: '/api',
|
||||
};
|
||||
8
frontend/src/environments/environment.ts
Normal file
8
frontend/src/environments/environment.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* 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',
|
||||
};
|
||||
Reference in New Issue
Block a user