Compare commits

..

10 Commits

Author SHA1 Message Date
cfd4a81b5f Merge branch 'dev' into agent/rex/CUB-36-delete-confirmation
Some checks failed
Dev Build / build-test (pull_request) Failing after 52s
Dev Build / deploy-dev (pull_request) Has been skipped
Dev Build / notify-success (pull_request) Has been skipped
Dev Build / notify-failure (pull_request) Successful in 3s
2026-04-27 14:17:44 -04:00
8a2f97d2cd Merge pull request 'CUB-40: Add cost summary API endpoint' (#15) from agent/dex/CUB-40-cost-summary-api into dev
Some checks failed
Dev Build / build-test (push) Failing after 52s
Dev Build / deploy-dev (push) Has been skipped
Dev Build / notify-success (push) Has been skipped
Dev Build / notify-failure (push) Successful in 3s
Reviewed-on: #15
2026-04-27 14:17:30 -04:00
b43edad5f0 Merge branch 'dev' into agent/dex/CUB-40-cost-summary-api
Some checks failed
Dev Build / build-test (pull_request) Failing after 52s
Dev Build / deploy-dev (pull_request) Has been skipped
Dev Build / notify-success (pull_request) Has been skipped
Dev Build / notify-failure (pull_request) Successful in 3s
2026-04-27 14:14:13 -04:00
f5ca20307e CUB-36: add delete confirmation dialog for filament spool removal
Some checks failed
Dev Build / build-test (pull_request) Failing after 53s
Dev Build / deploy-dev (pull_request) Has been skipped
Dev Build / notify-success (pull_request) Has been skipped
Dev Build / notify-failure (pull_request) Successful in 3s
2026-04-27 18:12:58 +00:00
12888c4f3f Merge pull request 'CUB-66: Frontend Dockerfile (Angular Static Build)' (#12) from agent/rex/CUB-64-frontend-dockerfile into dev
Some checks failed
Dev Build / build-test (push) Failing after 51s
Dev Build / deploy-dev (push) Has been skipped
Dev Build / notify-success (push) Has been skipped
Dev Build / notify-failure (push) Successful in 3s
Reviewed-on: #12
Reviewed-by: Otto the Minion <otto@code.cubecraftcreations.com>
2026-04-27 14:11:55 -04:00
1411b68a95 Merge branch 'dev' into agent/rex/CUB-64-frontend-dockerfile
Some checks failed
Dev Build / build-test (pull_request) Failing after 50s
Dev Build / deploy-dev (pull_request) Has been skipped
Dev Build / notify-success (pull_request) Has been skipped
Dev Build / notify-failure (pull_request) Successful in 3s
2026-04-27 14:11:50 -04:00
7daa7d637c Merge pull request 'CUB-31: Add filament usage tracking model' (#10) from agent/hex/CUB-31-filament-usage-tracking-model into dev
Some checks failed
Dev Build / build-test (push) Failing after 50s
Dev Build / deploy-dev (push) Has been skipped
Dev Build / notify-success (push) Has been skipped
Dev Build / notify-failure (push) Successful in 3s
Reviewed-on: #10
Reviewed-by: Otto the Minion <otto@code.cubecraftcreations.com>
2026-04-27 14:09:22 -04:00
c1a115c938 feat(CUB-40): [Extrudex] Add cost summary API endpoint
Some checks failed
Dev Build / build-test (pull_request) Failing after 47s
Dev Build / deploy-dev (pull_request) Has been skipped
Dev Build / notify-success (pull_request) Has been skipped
Dev Build / notify-failure (pull_request) Successful in 3s
2026-04-27 17:09:08 +00:00
920042acac fix(CUB-66): Resolve merge conflicts - keep only Docker setup, remove duplicate Angular app files
Some checks failed
Dev Build / build-test (pull_request) Failing after 1m4s
Dev Build / deploy-dev (pull_request) Has been skipped
Dev Build / notify-success (pull_request) Has been skipped
Dev Build / notify-failure (pull_request) Successful in 5s
2026-04-27 02:23:27 +00:00
cubecraft-agents[bot]
1ee7562e81 CUB-66: scaffold Angular frontend and add Dockerfile with nginx
Some checks failed
Dev Build / build-test (pull_request) Failing after 58s
Dev Build / deploy-dev (pull_request) Has been skipped
Dev Build / notify-success (pull_request) Has been skipped
Dev Build / notify-failure (pull_request) Successful in 4s
- Scaffolded Angular 21 app in frontend/ (standalone, routing, scss)
- Multi-stage Dockerfile: node:22-alpine build → nginx:alpine serve
- nginx.conf with SPA routing fallback, API proxy, gzip, asset caching
- .dockerignore excludes node_modules, dist, .angular, spec files
- docker build → PASS, container serves UI on port 80 (HTTP 200)
- Final image: 92.9MB (nginx:alpine)
2026-04-26 20:10:01 +00:00
15 changed files with 686 additions and 6 deletions

View File

@@ -413,6 +413,92 @@ public class PrintJobsController : ControllerBase
return NoContent();
}
// ── GET /api/printjobs/{id}/cost-summary ──────────────────────────
/// <summary>
/// Gets the material cost summary for a specific print job.
/// Calculates total material cost from filament usage (grams derived)
/// and the spool's purchase price. Returns warnings instead of errors
/// when cost data is unavailable.
/// </summary>
/// <param name="id">The unique identifier of the print job.</param>
/// <returns>A cost summary with breakdown and any warnings about missing data.</returns>
/// <response code="200">Returns the cost summary. Warnings field lists any missing data.</response>
/// <response code="404">If the print job with the given ID is not found.</response>
[HttpGet("{id:guid}/cost-summary")]
[ProducesResponseType(typeof(CostSummaryResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<CostSummaryResponse>> GetCostSummary(Guid id)
{
_logger.LogDebug("Getting cost summary for print job {Id}", id);
var job = await _dbContext.PrintJobs
.Include(j => j.Spool)
.ThenInclude(s => s!.MaterialBase)
.FirstOrDefaultAsync(j => j.Id == id);
if (job is null)
{
_logger.LogWarning("Print job {Id} not found for cost summary", id);
return NotFound(new { error = $"Print job with ID '{id}' not found." });
}
var warnings = new List<string>();
var spool = job.Spool;
// Build response with what we have
var response = new CostSummaryResponse
{
PrintJobId = job.Id,
PrintName = job.PrintName,
SpoolId = job.SpoolId,
SpoolSerial = spool?.SpoolSerial ?? string.Empty,
SpoolBrand = spool?.Brand ?? string.Empty,
SpoolColorName = spool?.ColorName ?? string.Empty,
MmExtruded = job.MmExtruded,
GramsDerived = job.GramsDerived,
SpoolPurchasePrice = spool?.PurchasePrice,
SpoolWeightTotalGrams = spool?.WeightTotalGrams,
StoredCostPerPrint = job.CostPerPrint
};
// Validate spool data availability
if (spool is null)
{
warnings.Add("Spool data is not available for this print job. Cost cannot be calculated.");
response.Warnings = warnings;
return Ok(response);
}
// Check if we can calculate cost
if (!spool.PurchasePrice.HasValue)
{
warnings.Add("Spool purchase price is not set. Cost per gram and total material cost cannot be calculated.");
}
if (spool.WeightTotalGrams <= 0)
{
warnings.Add("Spool total weight is zero or invalid. Cost per gram and total material cost cannot be calculated.");
}
// If we have enough data, calculate the cost
if (spool.PurchasePrice.HasValue && spool.WeightTotalGrams > 0)
{
var pricePerGram = spool.PurchasePrice.Value / spool.WeightTotalGrams;
response.PricePerGram = Math.Round(pricePerGram, 4);
response.TotalMaterialCost = Math.Round(job.GramsDerived * pricePerGram, 4);
}
// Warn if grams derived is zero but mm extruded is non-zero
if (job.GramsDerived == 0 && job.MmExtruded > 0)
{
warnings.Add("GramsDerived is zero despite MmExtruded being non-zero. Cost may be inaccurate. Consider re-deriving grams from filament parameters.");
}
response.Warnings = warnings;
return Ok(response);
}
// ── Gram Derivation Formula ────────────────────────────────────
/// <summary>

View File

@@ -0,0 +1,55 @@
namespace Extrudex.API.DTOs.PrintJobs;
/// <summary>
/// Response DTO for the cost summary of a print job.
/// Provides a breakdown of material cost based on filament usage
/// and spool pricing data. If cost data is incomplete, warnings
/// are returned instead of throwing an error.
/// </summary>
public class CostSummaryResponse
{
/// <summary>Unique identifier of the print job.</summary>
public Guid PrintJobId { get; set; }
/// <summary>Human-readable name of the print job.</summary>
public string PrintName { get; set; } = string.Empty;
/// <summary>Foreign key to the spool used for this print job.</summary>
public Guid SpoolId { get; set; }
/// <summary>Serial number of the spool.</summary>
public string SpoolSerial { get; set; } = string.Empty;
/// <summary>Brand of the spool.</summary>
public string SpoolBrand { get; set; } = string.Empty;
/// <summary>Color name of the spool.</summary>
public string SpoolColorName { get; set; } = string.Empty;
/// <summary>Total millimeters of filament extruded during this print.</summary>
public decimal MmExtruded { get; set; }
/// <summary>Derived grams consumed for this print job.</summary>
public decimal GramsDerived { get; set; }
/// <summary>Purchase price of the full spool, if available.</summary>
public decimal? SpoolPurchasePrice { get; set; }
/// <summary>Total weight of the spool in grams when full.</summary>
public decimal? SpoolWeightTotalGrams { get; set; }
/// <summary>Calculated price per gram (purchase price / total weight), if available.</summary>
public decimal? PricePerGram { get; set; }
/// <summary>Calculated total material cost for this print job, if available.</summary>
public decimal? TotalMaterialCost { get; set; }
/// <summary>The CostPerPrint stored on the print job entity, if set.</summary>
public decimal? StoredCostPerPrint { get; set; }
/// <summary>
/// Warnings about missing data that prevent cost calculation.
/// Empty if all data is available and cost was calculated successfully.
/// </summary>
public List<string> Warnings { get; set; } = new();
}

11
frontend/.dockerignore Normal file
View File

@@ -0,0 +1,11 @@
node_modules
dist
.git
.gitignore
.angular
.vscode
*.md
.editorconfig
.prettierrc
src/test.ts
**/*.spec.ts

28
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,28 @@
# Stage 1: Build the Angular application
FROM node:22-alpine AS build
WORKDIR /app
# Copy package files first for better layer caching
COPY package.json package-lock.json ./
RUN npm ci
# Copy source and build
COPY . .
RUN npx ng build --configuration production
# Stage 2: Serve static files with nginx
FROM nginx:alpine
# Remove default nginx config
RUN rm /etc/nginx/conf.d/default.conf
# Copy custom nginx config
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Copy built Angular artifacts from build stage
COPY --from=build /app/dist/frontend/browser /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

42
frontend/nginx.conf Normal file
View File

@@ -0,0 +1,42 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
# Gzip compression
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
gzip_min_length 256;
# Angular SPA — fallback to index.html for client-side routing
location / {
try_files $uri $uri/ /index.html;
}
# Cache static assets aggressively
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Proxy API requests to backend
# Uses resolver so nginx doesn't crash if backend isn't available at startup
resolver 127.0.0.11 valid=30s ipv6=off;
set $backend "extrudex-api:8080";
location /api/ {
proxy_pass http://$backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Health check endpoint
location /health {
access_log off;
return 200 "ok";
add_header Content-Type text/plain;
}
}

View File

@@ -8,6 +8,7 @@
"name": "frontend",
"version": "0.0.0",
"dependencies": {
"@angular/animations": "^21.2.10",
"@angular/cdk": "^21.2.8",
"@angular/common": "^21.2.0",
"@angular/compiler": "^21.2.0",
@@ -326,6 +327,21 @@
"yarn": ">= 1.13.0"
}
},
"node_modules/@angular/animations": {
"version": "21.2.10",
"resolved": "https://registry.npmjs.org/@angular/animations/-/animations-21.2.10.tgz",
"integrity": "sha512-sIzAcxwtRCJ/fu0tK4mo1ooiEaDxJ+Nl6s9nK1D1NP1em12VX03Jx8CMixp/kVtgh4mZnm1x6psBB0FUz3U3Ug==",
"license": "MIT",
"dependencies": {
"tslib": "^2.3.0"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
},
"peerDependencies": {
"@angular/core": "21.2.10"
}
},
"node_modules/@angular/build": {
"version": "21.2.8",
"resolved": "https://registry.npmjs.org/@angular/build/-/build-21.2.8.tgz",

View File

@@ -11,6 +11,7 @@
"private": true,
"packageManager": "npm@11.11.0",
"dependencies": {
"@angular/animations": "^21.2.10",
"@angular/cdk": "^21.2.8",
"@angular/common": "^21.2.0",
"@angular/compiler": "^21.2.0",

View File

@@ -1,11 +1,15 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } 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(withFetch()),
provideAnimationsAsync(),
]
};
};

View File

@@ -0,0 +1,78 @@
<!-- Delete Filament Confirmation Dialog -->
<h2 mat-dialog-title>
<mat-icon aria-hidden="true">warning</mat-icon>
Delete Filament Spool?
</h2>
<mat-dialog-content>
<p class="dialog-description">
You are about to permanently remove this filament spool from inventory.
</p>
<!-- Spool details card -->
<div class="spool-details" role="list" aria-label="Spool details">
<div class="detail-row" role="listitem">
<span class="detail-label">Material</span>
<span class="detail-value">{{ filament.materialBaseName }}{{ filament.materialFinishName ? ' — ' + filament.materialFinishName : '' }}{{ filament.materialModifierName ? ' (' + filament.materialModifierName + ')' : '' }}</span>
</div>
<div class="detail-row" role="listitem">
<span class="detail-label">Brand</span>
<span class="detail-value">{{ filament.brand }}</span>
</div>
<div class="detail-row" role="listitem">
<span class="detail-label">Color</span>
<span class="detail-value color-value">
<span class="color-swatch-inline"
[style.background-color]="filament.colorHex"
[attr.aria-label]="filament.colorName">
</span>
{{ filament.colorName }}
</span>
</div>
<div class="detail-row" role="listitem">
<span class="detail-label">Serial</span>
<span class="detail-value serial-value">{{ filament.spoolSerial }}</span>
</div>
<div class="detail-row" role="listitem">
<span class="detail-label">Remaining</span>
<span class="detail-value">{{ formatWeight(filament.weightRemainingGrams) }} / {{ formatWeight(filament.weightTotalGrams) }}</span>
</div>
<div class="detail-row" role="listitem">
<span class="detail-label">Status</span>
<span class="detail-value">
<span class="status-badge"
[class.active]="filament.isActive"
[class.inactive]="!filament.isActive">
{{ filament.isActive ? 'Active' : 'Inactive' }}
</span>
</span>
</div>
</div>
<p class="dialog-warning">
<mat-icon aria-hidden="true">info</mat-icon>
This action cannot be undone.
</p>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button
type="button"
(click)="onCancel()"
class="cancel-button">
Cancel
</button>
<button mat-flat-button
type="button"
color="warn"
(click)="onConfirm()"
class="confirm-button">
<mat-icon aria-hidden="true">delete</mat-icon>
Delete Spool
</button>
</mat-dialog-actions>

View File

@@ -0,0 +1,150 @@
/**
* Delete Filament Dialog Styles
* Touch-optimized confirmation dialog for spool removal
*/
$spacing-unit: 8px;
$color-critical: #ef4444;
$color-inactive: #94a3b8;
$color-active: #22c55e;
// Dialog title
h2[mat-dialog-title] {
display: flex;
align-items: center;
gap: $spacing-unit;
color: $color-critical;
mat-icon {
font-size: 24px !important;
width: 24px !important;
height: 24px !important;
}
}
// Description text
.dialog-description {
margin: 0 0 $spacing-unit * 2;
font-size: 14px;
line-height: 1.5;
color: var(--mat-sys-on-surface);
}
// Spool details card
.spool-details {
display: flex;
flex-direction: column;
gap: $spacing-unit;
padding: $spacing-unit * 1.5;
background-color: var(--mat-sys-surface-container);
border-radius: 8px;
margin-bottom: $spacing-unit * 2;
}
.detail-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: $spacing-unit * 0.5 0;
font-size: 14px;
&:not(:last-child) {
border-bottom: 1px solid var(--mat-sys-outline-variant);
padding-bottom: $spacing-unit;
}
}
.detail-label {
font-weight: 500;
color: var(--mat-sys-on-surface-variant);
flex-shrink: 0;
}
.detail-value {
font-weight: 400;
color: var(--mat-sys-on-surface);
text-align: right;
}
// Color swatch inline
.color-swatch-inline {
display: inline-block;
width: 18px;
height: 18px;
border-radius: 50%;
border: 1.5px solid rgba(0, 0, 0, 0.12);
vertical-align: middle;
margin-right: 4px;
}
.color-value {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 4px;
}
// Serial value — monospace
.serial-value {
font-family: 'JetBrains Mono', 'Roboto Mono', monospace;
font-size: 13px;
letter-spacing: 0.02em;
}
// Status badge — matches filament table styling
.status-badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 10px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
&.active {
background-color: rgba($color-active, 0.12);
color: $color-active;
}
&.inactive {
background-color: rgba($color-inactive, 0.12);
color: $color-inactive;
}
}
// Warning text
.dialog-warning {
display: flex;
align-items: center;
gap: $spacing-unit;
margin: 0;
font-size: 13px;
color: $color-critical;
mat-icon {
font-size: 18px !important;
width: 18px !important;
height: 18px !important;
}
}
// Dialog action buttons
mat-dialog-actions {
padding-top: $spacing-unit * 2;
.cancel-button {
min-width: 80px;
}
.confirm-button {
min-width: 120px;
mat-icon {
font-size: 18px !important;
width: 18px !important;
height: 18px !important;
margin-right: 4px;
}
}
}

View File

@@ -0,0 +1,68 @@
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
MAT_DIALOG_DATA,
MatDialogRef,
MatDialogModule,
} from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { Filament } from '../../models/filament.model';
/**
* Data passed into the delete confirmation dialog.
*/
export interface DeleteFilamentDialogData {
filament: Filament;
}
/**
* Delete confirmation dialog for filament spool removal.
*
* Displays spool details (material, brand, color, serial, remaining weight)
* and requires the user to confirm before deletion proceeds.
* Cancel dismisses the dialog with no action.
*/
@Component({
selector: 'app-delete-filament-dialog',
standalone: true,
imports: [
CommonModule,
MatDialogModule,
MatButtonModule,
MatIconModule,
MatChipsModule,
],
templateUrl: './delete-filament-dialog.component.html',
styleUrl: './delete-filament-dialog.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeleteFilamentDialogComponent {
private readonly dialogRef = inject(
MatDialogRef<DeleteFilamentDialogComponent, boolean>
);
readonly data: DeleteFilamentDialogData = inject(MAT_DIALOG_DATA);
/** The filament spool being considered for deletion */
readonly filament = this.data.filament;
/** Format weight for display in dialog */
formatWeight(grams: number): string {
if (grams >= 1000) {
return `${(grams / 1000).toFixed(1)}kg`;
}
return `${Math.round(grams)}g`;
}
/** Cancel — close dialog with false (no deletion) */
onCancel(): void {
this.dialogRef.close(false);
}
/** Confirm — close dialog with true (proceed with deletion) */
onConfirm(): void {
this.dialogRef.close(true);
}
}

View File

@@ -1,4 +1,4 @@
<!-- Filament Inventory Table — with low stock indicators -->
<!-- Filament Inventory Table — with low stock indicators and delete actions -->
<div class="filament-table-container" role="region" aria-label="Filament inventory">
<!-- Low Stock Alert Banner — shown when critical or low stock spools exist -->
@@ -106,10 +106,32 @@
</td>
</ng-container>
<!-- Actions Column — delete button -->
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Actions</th>
<td mat-cell *matCellDef="let filament">
<button mat-icon-button
type="button"
color="warn"
[attr.aria-label]="'Delete ' + filament.materialBaseName + ' ' + filament.colorName"
matTooltip="Delete spool"
matTooltipPosition="above"
[disabled]="deleting() === filament.id"
(click)="onDeleteClick(filament)">
@if (deleting() === filament.id) {
<mat-icon aria-hidden="true">hourglass_empty</mat-icon>
} @else {
<mat-icon aria-hidden="true">delete</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'"
[class.row-low]="classifyStockLevel(row) === 'low'">
[class.row-low]="classifyStockLevel(row) === 'low'"
[class.row-deleting]="deleting() === row.id">
</tr>
</table>

View File

@@ -235,6 +235,20 @@ mat-chip {
}
}
// Actions column
.actions-cell {
display: flex;
align-items: center;
justify-content: center;
}
// Row being deleted — subtle fade
:host ::ng-deep .row-deleting {
opacity: 0.5;
pointer-events: none;
transition: opacity 0.3s ease;
}
// Empty state
.empty-state {
display: flex;

View File

@@ -3,6 +3,7 @@ import {
Component,
Input,
computed,
inject,
signal,
} from '@angular/core';
import { CommonModule } from '@angular/common';
@@ -12,12 +13,21 @@ 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 { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import {
Filament,
StockLevel,
getRemainingPercent,
classifyStockLevel,
} from '../../models/filament.model';
import { FilamentService } from '../../services/filament.service';
import {
DeleteFilamentDialogComponent,
DeleteFilamentDialogData,
} from '../delete-filament-dialog/delete-filament-dialog.component';
/** Display column definitions for the filament table */
export type FilamentColumn =
@@ -27,7 +37,8 @@ export type FilamentColumn =
| 'serial'
| 'remaining'
| 'stockLevel'
| 'status';
| 'status'
| 'actions';
@Component({
selector: 'app-filament-table',
@@ -40,16 +51,26 @@ export type FilamentColumn =
MatProgressBarModule,
MatTooltipModule,
MatSortModule,
MatButtonModule,
MatDialogModule,
MatSnackBarModule,
],
templateUrl: './filament-table.component.html',
styleUrl: './filament-table.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FilamentTableComponent {
private readonly dialog = inject(MatDialog);
private readonly snackBar = inject(MatSnackBar);
private readonly filamentService = inject(FilamentService);
/** Filament data input — reactive signal for live updates */
readonly filaments = signal<Filament[]>([]);
/** Columns to display — defaults to all columns */
/** Whether a delete operation is in progress */
readonly deleting = signal<string | null>(null);
/** Columns to display — defaults to all columns including actions */
@Input()
set displayedColumns(cols: FilamentColumn[]) {
this._displayedColumns.set(cols);
@@ -65,6 +86,7 @@ export class FilamentTableComponent {
'remaining',
'stockLevel',
'status',
'actions',
]);
/** Default columns for template binding */
@@ -252,6 +274,52 @@ export class FilamentTableComponent {
this.sortedFilaments.set(sorted);
}
/**
* Open the delete confirmation dialog for a filament spool.
* On confirm: calls DELETE endpoint and removes the row on success.
* On cancel: dialog dismissed, no action taken.
*/
onDeleteClick(filament: Filament): void {
const dialogData: DeleteFilamentDialogData = { filament };
const dialogRef = this.dialog.open(DeleteFilamentDialogComponent, {
data: dialogData,
width: '480px',
disableClose: true,
});
dialogRef.afterClosed().subscribe((confirmed: boolean | undefined) => {
if (!confirmed) {
return; // User cancelled — no action
}
// Mark as deleting for UI feedback
this.deleting.set(filament.id);
this.filamentService.deleteFilament(filament.id).subscribe({
next: () => {
// Remove the deleted filament from local data
const updated = this.filaments().filter((f) => f.id !== filament.id);
this.updateFilaments(updated);
this.deleting.set(null);
this.snackBar.open(
`Deleted ${filament.materialBaseName}${filament.colorName}`,
'Dismiss',
{ duration: 4000 }
);
},
error: () => {
this.deleting.set(null);
this.snackBar.open(
`Failed to delete ${filament.materialBaseName}${filament.colorName}. Please try again.`,
'Dismiss',
{ duration: 6000 }
);
},
});
});
}
/** Template helper: get remaining percent */
getRemainingPercent = getRemainingPercent;

View File

@@ -0,0 +1,37 @@
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Filament } from '../models/filament.model';
/**
* API base URL — matches the Extrudex backend default.
* TODO: Move to environment config when multi-environment support is added.
*/
const API_BASE_URL = '/api';
/**
* Service for CRUD operations on filament spools.
* Communicates with the Extrudex backend SpoolsController.
*/
@Injectable({ providedIn: 'root' })
export class FilamentService {
private readonly http = inject(HttpClient);
/**
* Fetch all filament spools from the backend.
* GET /api/spools
*/
getFilaments(): Observable<Filament[]> {
return this.http.get<Filament[]>(`${API_BASE_URL}/spools`);
}
/**
* Soft-delete a filament spool by ID.
* DELETE /api/spools/{id}
* Returns 204 No Content on success.
*/
deleteFilament(id: string): Observable<void> {
return this.http.delete<void>(`${API_BASE_URL}/spools/${id}`);
}
}