Add HL3D branding, Etsy Live/Draft paging and Projects lifecycle
Deploy HickLab3D Dashboard / Deploy to production (push) Failing after 23s

Replace the old touchmark/PNG identity with the supplied lockup and
monogram, segmented role-aware navigation, Live/Draft listing filters
with generation-based cache invalidation, and admin Projects covering
immutable file revisions, listing live pointers, and exact-decimal
filament/packaging/shipping costing. Additive schema only; no Etsy
publication. Isolated clone tests: 301 tests, 1162 assertions.
This commit is contained in:
2026-11-08 12:50:56 +00:00
parent c8c5822166
commit d4928789c4
83 changed files with 5808 additions and 84 deletions
+36 -11
View File
@@ -5,6 +5,7 @@ namespace App\Services;
use App\Models\EtsyAppCredential;
use App\Models\EtsyConnection;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
@@ -188,24 +189,34 @@ class Etsy
/**
* @return array{count: int, limit: int, offset: int, state: string, results: list<array<string, mixed>>}
*/
public function listListings(EtsyConnection $connection, string $state = 'active', int $limit = 25, int $offset = 0): array
public function listListings(EtsyConnection $connection, string $state = 'active', int $limit = 25, int $offset = 0, bool $fresh = false): array
{
$state = strtolower($state);
if (! in_array($state, self::LISTING_STATES, true)) {
throw new RuntimeException('Listing state must be one of: '.implode(', ', self::LISTING_STATES).'.');
}
[$limit, $offset] = $this->page($limit, $offset);
$response = $this->request('GET', 'application/shops/'.$connection->shop_id.'/listings', $this->accessToken($connection), [
'state' => $state, 'limit' => $limit, 'offset' => $offset,
]);
$generation = Cache::get('etsy.listing-generation.'.$connection->shop_id, '0');
$cacheKey = 'etsy.listListings.'.$connection->shop_id.'.'.$generation.'.'.$state.'.'.$limit.'.'.$offset;
return [
'count' => (int) ($response['count'] ?? count($response['results'] ?? [])),
'limit' => $limit,
'offset' => $offset,
'state' => $state,
'results' => array_map(fn (array $listing): array => $this->summarizeListing($listing), $this->results($response)),
];
$result = $this->cache->remember($cacheKey, 600, function () use ($connection, $state, $limit, $offset): array {
$response = $this->request('GET', 'application/shops/'.$connection->shop_id.'/listings', $this->accessToken($connection), [
'state' => $state, 'limit' => $limit, 'offset' => $offset,
]);
return [
'count' => (int) ($response['count'] ?? count($response['results'] ?? [])),
'limit' => $limit,
'offset' => $offset,
'state' => $state,
'results' => array_map(fn (array $listing): array => $this->summarizeListing($listing), $this->results($response)),
];
}, $fresh);
$entry = Cache::get('integration:'.$cacheKey);
$result['fetched_at'] = is_array($entry) ? $entry['fetched_at'] : null;
$result['stale'] = $result['fetched_at'] === null || time() >= $result['fetched_at'] + 600;
return $result;
}
/**
@@ -270,6 +281,7 @@ class Etsy
$payload = $this->validatedListingPayload($payload, true);
$listing = $this->request('POST', 'application/shops/'.$connection->shop_id.'/listings', $this->accessToken($connection), body: $payload);
$this->cache->forget('etsy.listings.'.$connection->shop_id);
$this->forgetListingStateCaches($connection);
return $this->summarizeListing($listing, detailed: true);
}
@@ -289,6 +301,7 @@ class Etsy
$listing = $this->request('PATCH', 'application/shops/'.$connection->shop_id.'/listings/'.$listingId, $this->accessToken($connection), body: $payload);
$this->assertListingBelongsToShop($connection, $listing);
$this->cache->forget('etsy.listings.'.$connection->shop_id);
$this->forgetListingStateCaches($connection);
return $this->summarizeListing($listing, detailed: true);
}
@@ -306,10 +319,21 @@ class Etsy
$listing = $this->request('PATCH', 'application/shops/'.$connection->shop_id.'/listings/'.$listingId, $this->accessToken($connection), body: ['state' => 'active']);
$this->assertListingBelongsToShop($connection, $listing);
$this->cache->forget('etsy.listings.'.$connection->shop_id);
$this->forgetListingStateCaches($connection);
return $this->summarizeListing($listing, detailed: true);
}
/**
* Invalidate the first page of both Live and Draft state caches so a
* write immediately shown to the operator doesn't keep serving a stale
* cached page. Older pages expire on their own TTL.
*/
private function forgetListingStateCaches(EtsyConnection $connection): void
{
Cache::put('etsy.listing-generation.'.$connection->shop_id, bin2hex(random_bytes(16)), 172800);
}
/**
* @return array<string, mixed>
*/
@@ -359,6 +383,7 @@ class Etsy
}
$inventory = $this->request('PUT', 'application/listings/'.$listingId.'/inventory', $this->accessToken($connection), body: $body, jsonBody: true);
$this->cache->forget('etsy.listings.'.$connection->shop_id);
$this->forgetListingStateCaches($connection);
return $inventory;
}
+610
View File
@@ -0,0 +1,610 @@
<?php
namespace App\Services;
use App\Models\ProjectFile;
use Illuminate\Http\UploadedFile;
use RuntimeException;
use XMLReader;
use ZipArchive;
/**
* Structural validation for private manufacturing file uploads (STL, 3MF, G-code).
*
* MIME sniffing alone is not trustworthy for these formats, so each extension is
* combined with bounded, format-specific structural checks:
*
* - STL: a real facet/vertex grammar for ASCII (not just "starts with solid,
* contains endsolid somewhere"), a triangle-count vs file-size cross-check for
* binary with a positive triangle requirement, and a finite-float check on
* every normal/vertex component so a NaN/Infinity payload is rejected.
* - 3MF: a bounded zip reader (entry count, per-entry and total uncompressed
* size, compression ratio, encrypted entries, duplicate entry names, unsafe
* paths, symlink entries) feeding a real, safe XML parse (XMLReader, no DTD
* loading, no network, rejecting any DOCTYPE outright) of every XML/.model/
* .rels part — not the root relationships file alone — checking the 3MF
* model namespace/resources/build structure and rejecting any relationship
* with an external TargetMode or a Target outside the package, regardless of
* quoting style. Every XML part is read through a bounded stream (per-entry
* and whole-archive byte budgets) rather than trusting the zip's own declared
* sizes, so a size lie can't blow past the caps.
* - G-code: a plain-text check; it is never parsed or executed.
*
* No slicer, shell command or print job is ever invoked here, and nothing is
* ever extracted to disk.
*/
class ManufacturingFileValidator
{
public const MAX_FILE_SIZE = 100 * 1024 * 1024;
public const MAX_TOTAL_BATCH_SIZE = 250 * 1024 * 1024;
private const MAX_STL_TRIANGLES = 5_000_000;
private const MAX_3MF_ENTRIES = 2000;
private const MAX_3MF_TOTAL_UNCOMPRESSED = 128 * 1024 * 1024;
private const MAX_3MF_RATIO = 100;
private const MAX_3MF_MODEL_PART_BYTES = 64 * 1024 * 1024;
private const MAX_3MF_XML_ENTRY_BYTES = 16 * 1024 * 1024;
private const MAX_3MF_TOTAL_PARSED_BYTES = 128 * 1024 * 1024;
private const MODEL_NAMESPACE_PREFIX = 'http://schemas.microsoft.com/3dmanufacturing/core/';
private const FLOAT_PATTERN = '[-+]?(?:\d+\.\d+|\.\d+|\d+)(?:[eE][-+]?\d+)?';
/** @var array<string, string> */
private const MEDIA_TYPES = [
'stl' => 'model/stl',
'3mf' => 'model/3mf',
'gcode' => 'text/x-gcode',
];
/**
* @return array{extension: string, media_type: string}
*/
public function validate(UploadedFile $file): array
{
$size = $file->getSize();
if ($size === false || $size <= 0) {
throw new RuntimeException('File is empty or unreadable.');
}
if ($size > self::MAX_FILE_SIZE) {
throw new RuntimeException('File exceeds the maximum allowed size of 100 MiB.');
}
$extension = strtolower((string) $file->getClientOriginalExtension());
if (! in_array($extension, ProjectFile::EXTENSIONS, true)) {
throw new RuntimeException("Unsupported file type: .{$extension}");
}
$path = $file->getRealPath() ?: $file->getPathname();
match ($extension) {
'stl' => $this->validateStl($path, $size),
'3mf' => $this->validate3mf($path),
'gcode' => $this->validateGcode($path, $size),
default => throw new RuntimeException("Unsupported file type: .{$extension}"),
};
return ['extension' => $extension, 'media_type' => self::MEDIA_TYPES[$extension]];
}
private function validateStl(string $path, int $size): void
{
if ($size >= 84) {
$header = $this->readPrefix($path, 84);
if (strlen($header) === 84) {
$count = unpack('V', substr($header, 80, 4))[1] ?? 0;
if ($count > 0 && $count <= self::MAX_STL_TRIANGLES && $size === 84 + $count * 50) {
$this->assertBinaryStlTrianglesFinite($path, $count);
return;
}
}
}
$prefix = strtolower(ltrim($this->readPrefix($path, 16)));
if (! str_starts_with($prefix, 'solid')) {
throw new RuntimeException('File does not match the declared STL format.');
}
if (! $this->isPlainText($path)) {
throw new RuntimeException('ASCII STL contains unexpected binary content.');
}
$this->validateAsciiStlGrammar($path);
}
/**
* A real facet/vertex grammar: "solid garbage endsolid" with zero facets,
* or any facet missing its outer loop/vertices, is rejected — not just
* files that merely start with "solid" and contain "endsolid" somewhere.
* Streamed line-by-line so an up-to-100-MiB file never needs to be loaded
* into memory at once.
*/
private function validateAsciiStlGrammar(string $path): void
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('Unable to read uploaded file.');
}
try {
$first = fgets($handle);
if ($first === false || preg_match('/^\s*solid\b/i', $first) !== 1) {
throw new RuntimeException('ASCII STL must begin with a "solid" declaration.');
}
$facetCount = 0;
$state = 'facet_or_end';
$done = false;
while (($line = fgets($handle)) !== false) {
$trimmed = trim($line);
if ($trimmed === '') {
continue;
}
switch ($state) {
case 'facet_or_end':
if (preg_match('/^endsolid\b/i', $trimmed) === 1) {
$done = true;
break 2;
}
if (preg_match('/^facet\s+normal\s+('.self::FLOAT_PATTERN.')\s+('.self::FLOAT_PATTERN.')\s+('.self::FLOAT_PATTERN.')\s*$/i', $trimmed, $m) !== 1) {
throw new RuntimeException('ASCII STL contains an unexpected line outside a facet block.');
}
$this->assertFiniteTokens([$m[1], $m[2], $m[3]], 'facet normal');
$state = 'outer_loop';
break;
case 'outer_loop':
if (preg_match('/^outer\s+loop$/i', $trimmed) !== 1) {
throw new RuntimeException('Expected "outer loop" after a facet normal.');
}
$state = 'vertex1';
break;
case 'vertex1':
case 'vertex2':
case 'vertex3':
if (preg_match('/^vertex\s+('.self::FLOAT_PATTERN.')\s+('.self::FLOAT_PATTERN.')\s+('.self::FLOAT_PATTERN.')\s*$/i', $trimmed, $m) !== 1) {
throw new RuntimeException('Expected a "vertex x y z" line inside a facet loop.');
}
$this->assertFiniteTokens([$m[1], $m[2], $m[3]], 'vertex');
$state = match ($state) {
'vertex1' => 'vertex2',
'vertex2' => 'vertex3',
'vertex3' => 'endloop',
};
break;
case 'endloop':
if (preg_match('/^endloop$/i', $trimmed) !== 1) {
throw new RuntimeException('Expected "endloop" after three vertices.');
}
$state = 'endfacet';
break;
case 'endfacet':
if (preg_match('/^endfacet$/i', $trimmed) !== 1) {
throw new RuntimeException('Expected "endfacet" to close a facet.');
}
$facetCount++;
if ($facetCount > self::MAX_STL_TRIANGLES) {
throw new RuntimeException('ASCII STL exceeds the maximum supported facet count.');
}
$state = 'facet_or_end';
break;
}
}
if (! $done || $state !== 'facet_or_end') {
throw new RuntimeException('ASCII STL is missing an endsolid terminator or has an incomplete facet.');
}
if ($facetCount < 1) {
throw new RuntimeException('ASCII STL must contain at least one facet.');
}
} finally {
fclose($handle);
}
}
/**
* @param list<string> $tokens
*/
private function assertFiniteTokens(array $tokens, string $context): void
{
foreach ($tokens as $token) {
$value = (float) $token;
if (! is_finite($value)) {
throw new RuntimeException("ASCII STL {$context} contains a non-finite value.");
}
}
}
private function assertBinaryStlTrianglesFinite(string $path, int $count): void
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('Unable to read uploaded file.');
}
try {
fseek($handle, 84);
$remaining = $count;
while ($remaining > 0) {
$batch = min($remaining, 2000);
$bytes = $batch * 50;
$chunk = fread($handle, $bytes);
if ($chunk === false || strlen($chunk) !== $bytes) {
throw new RuntimeException('Binary STL triangle data is truncated.');
}
for ($i = 0; $i < $batch; $i++) {
$floats = unpack('f12', substr($chunk, $i * 50, 48));
if ($floats === false) {
throw new RuntimeException('Binary STL triangle data is malformed.');
}
foreach ($floats as $value) {
if (! is_finite($value)) {
throw new RuntimeException('Binary STL contains a non-finite (NaN/Infinity) normal or vertex value.');
}
}
}
$remaining -= $batch;
}
} finally {
fclose($handle);
}
}
private function validateGcode(string $path, int $size): void
{
if (! $this->isPlainText($path)) {
throw new RuntimeException('G-code file contains unexpected binary content.');
}
}
private function validate3mf(string $path): void
{
$zip = new ZipArchive;
if ($zip->open($path) !== true) {
throw new RuntimeException('Unable to read 3MF archive.');
}
try {
$count = $zip->count();
if ($count > self::MAX_3MF_ENTRIES) {
throw new RuntimeException('3MF archive has too many entries.');
}
$totalUncompressed = 0;
/** @var array<string, true> $seenNames */
$seenNames = [];
/** @var list<string> $modelParts */
$modelParts = [];
/** @var list<string> $relsEntries */
$relsEntries = [];
/** @var list<string> $xmlEntries */
$xmlEntries = [];
for ($i = 0; $i < $count; $i++) {
$stat = $zip->statIndex($i);
if ($stat === false) {
throw new RuntimeException('Unable to read 3MF archive entry.');
}
$name = (string) $stat['name'];
if (isset($seenNames[$name])) {
throw new RuntimeException("3MF archive contains a duplicate entry path: {$name}.");
}
$seenNames[$name] = true;
$this->assertSafeZipEntryName($name);
$this->assertNotSymlinkEntry($zip, $i, $name);
if (($stat['encryption_method'] ?? ZipArchive::EM_NONE) !== ZipArchive::EM_NONE) {
throw new RuntimeException("3MF archive contains an encrypted entry: {$name}.");
}
$uncompressed = (int) $stat['size'];
$compressed = (int) $stat['comp_size'];
$totalUncompressed += $uncompressed;
if ($compressed > 0 && ($uncompressed / $compressed) > self::MAX_3MF_RATIO) {
throw new RuntimeException('3MF entry has a suspicious compression ratio.');
}
if ($compressed === 0 && $uncompressed > 10 * 1024 * 1024) {
throw new RuntimeException('3MF entry has a suspicious compression ratio.');
}
if (str_ends_with($name, '.model')) {
$modelParts[] = $name;
} elseif (str_ends_with($name, '.rels')) {
$relsEntries[] = $name;
} elseif (str_ends_with($name, '.xml')) {
$xmlEntries[] = $name;
}
}
if ($totalUncompressed > self::MAX_3MF_TOTAL_UNCOMPRESSED) {
throw new RuntimeException('3MF archive exceeds the maximum uncompressed size.');
}
if (! in_array('3D/3dmodel.model', $modelParts, true)) {
throw new RuntimeException('3MF archive is missing the required 3D model part.');
}
if (! in_array('_rels/.rels', $relsEntries, true)) {
throw new RuntimeException('3MF archive is missing the required root relationships part.');
}
$budget = self::MAX_3MF_TOTAL_PARSED_BYTES;
$rootTargets = [];
foreach ($relsEntries as $relsName) {
$xml = $this->readBoundedZipEntry($zip, $relsName, self::MAX_3MF_XML_ENTRY_BYTES, $budget);
$targets = $this->parseRelationships($xml, $relsName);
if ($relsName === '_rels/.rels') {
$rootTargets = $targets;
}
}
$hasModelRelationship = false;
foreach ($rootTargets as $target) {
$resolved = ltrim($target, '/');
if (isset($seenNames[$resolved]) && str_ends_with($resolved, '.model')) {
$hasModelRelationship = true;
}
}
if (! $hasModelRelationship) {
throw new RuntimeException('3MF root relationships do not point to an internal model part.');
}
foreach ($xmlEntries as $xmlName) {
$xml = $this->readBoundedZipEntry($zip, $xmlName, self::MAX_3MF_XML_ENTRY_BYTES, $budget);
$this->assertGenericWellFormedXml($xml, $xmlName);
}
foreach ($modelParts as $modelName) {
$cap = $modelName === '3D/3dmodel.model' ? self::MAX_3MF_MODEL_PART_BYTES : self::MAX_3MF_XML_ENTRY_BYTES;
$xml = $this->readBoundedZipEntry($zip, $modelName, $cap, $budget);
$this->assertWellFormedModelXml($xml, $modelName);
}
} finally {
$zip->close();
}
}
/**
* Reads a zip entry through a bounded stream rather than trusting the
* archive's own declared size, so a size lie in the central directory
* can't blow past the per-entry or whole-archive parse budgets.
*/
private function readBoundedZipEntry(ZipArchive $zip, string $name, int $perEntryCap, int &$remainingBudget): string
{
$stream = $zip->getStream($name);
if ($stream === false) {
throw new RuntimeException("Unable to read 3MF archive entry: {$name}.");
}
$buffer = '';
$total = 0;
try {
while (! feof($stream)) {
$chunk = fread($stream, 65536);
if ($chunk === false) {
throw new RuntimeException("Unable to read 3MF archive entry: {$name}.");
}
$total += strlen($chunk);
if ($total > $perEntryCap) {
throw new RuntimeException("3MF archive entry exceeds its size cap: {$name}.");
}
$remainingBudget -= strlen($chunk);
if ($remainingBudget < 0) {
throw new RuntimeException('3MF archive exceeds the total parse budget.');
}
$buffer .= $chunk;
}
} finally {
fclose($stream);
}
return $buffer;
}
/**
* @return list<string> the raw Target attribute values of every Relationship
*/
private function parseRelationships(string $xml, string $context): array
{
$reader = $this->openSafeXmlReader($xml, $context);
$targets = [];
try {
while (@$reader->read()) {
if ($reader->nodeType === XMLReader::DOC_TYPE) {
throw new RuntimeException("3MF relationships part contains a disallowed DOCTYPE declaration: {$context}.");
}
if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'Relationship') {
continue;
}
$targetMode = $reader->getAttribute('TargetMode');
if ($targetMode !== null && strcasecmp($targetMode, 'External') === 0) {
throw new RuntimeException("3MF relationship declares an external TargetMode: {$context}.");
}
$target = $reader->getAttribute('Target');
if ($target === null || $target === '') {
throw new RuntimeException("3MF relationship is missing a Target attribute: {$context}.");
}
if (preg_match('#^[a-zA-Z][a-zA-Z0-9+.-]*:#', $target) === 1 || str_contains($target, '..')) {
throw new RuntimeException("3MF relationship target is not a safe internal package reference: {$context}.");
}
$targets[] = $target;
}
} finally {
$this->closeSafeXmlReader($reader, $context);
}
return $targets;
}
private function assertGenericWellFormedXml(string $xml, string $context): void
{
$reader = $this->openSafeXmlReader($xml, $context);
try {
while (@$reader->read()) {
if ($reader->nodeType === XMLReader::DOC_TYPE) {
throw new RuntimeException("3MF XML part contains a disallowed DOCTYPE declaration: {$context}.");
}
}
} finally {
$this->closeSafeXmlReader($reader, $context);
}
}
private function assertWellFormedModelXml(string $xml, string $context): void
{
$reader = $this->openSafeXmlReader($xml, $context);
$sawRoot = false;
$sawResources = false;
$sawBuild = false;
$rootDepth = null;
try {
while (@$reader->read()) {
if ($reader->nodeType === XMLReader::DOC_TYPE) {
throw new RuntimeException("3MF model part contains a disallowed DOCTYPE declaration: {$context}.");
}
if ($reader->nodeType !== XMLReader::ELEMENT) {
continue;
}
if (! $sawRoot) {
if ($reader->localName !== 'model' || ! str_starts_with((string) $reader->namespaceURI, self::MODEL_NAMESPACE_PREFIX)) {
throw new RuntimeException("3MF model part does not have a valid <model> root element in the 3MF core namespace: {$context}.");
}
$sawRoot = true;
$rootDepth = $reader->depth;
continue;
}
if ($reader->depth === $rootDepth + 1) {
if ($reader->localName === 'resources') {
$sawResources = true;
}
if ($reader->localName === 'build') {
$sawBuild = true;
}
}
}
} finally {
$this->closeSafeXmlReader($reader, $context);
}
if (! $sawRoot || ! $sawResources || ! $sawBuild) {
throw new RuntimeException("3MF model part is missing a valid model root with resources/build elements: {$context}.");
}
}
/**
* No DTD loading, no network access, no entity substitution — any DOCTYPE
* encountered while reading is explicitly rejected by the callers above
* rather than relied upon to be harmless.
*/
private function openSafeXmlReader(string $xml, string $context): XMLReader
{
libxml_use_internal_errors(true);
libxml_clear_errors();
$reader = XMLReader::XML($xml, null, LIBXML_NONET);
if ($reader === false) {
throw new RuntimeException("3MF part is not well-formed XML: {$context}.");
}
return $reader;
}
private function closeSafeXmlReader(XMLReader $reader, string $context): void
{
$errors = libxml_get_errors();
libxml_clear_errors();
$reader->close();
foreach ($errors as $error) {
if ($error->level >= LIBXML_ERR_ERROR) {
throw new RuntimeException("3MF part is not well-formed XML: {$context}.");
}
}
}
private function assertSafeZipEntryName(string $name): void
{
if ($name === ''
|| str_contains($name, '..')
|| str_starts_with($name, '/')
|| str_contains($name, '\\')
|| preg_match('/^[A-Za-z]:/', $name) === 1) {
throw new RuntimeException('3MF archive contains an unsafe entry path.');
}
}
/**
* Unix "external file attributes" pack the st_mode bits into the top 16 bits.
* A symlink entry (S_IFLNK octal 0120000) must never be trusted, even though
* nothing in this codebase currently extracts 3MF content to disk — a future
* caller doing so should not inherit a symlink-following vulnerability.
*/
private function assertNotSymlinkEntry(ZipArchive $zip, int $index, string $name): void
{
$external = $zip->getExternalAttributesIndex($index, $opsys, $attr) ? $attr : null;
if ($external === null) {
return;
}
$unixMode = ($external >> 16) & 0xFFFF;
if (($unixMode & 0xF000) === 0xA000) {
throw new RuntimeException("3MF archive contains a symlink entry: {$name}.");
}
}
private function readPrefix(string $path, int $length): string
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('Unable to read uploaded file.');
}
$data = fread($handle, $length);
fclose($handle);
return $data === false ? '' : $data;
}
private function isPlainText(string $path): bool
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('Unable to read uploaded file.');
}
while (! feof($handle)) {
$chunk = fread($handle, 1024 * 1024);
if ($chunk === false) {
break;
}
if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $chunk) === 1) {
fclose($handle);
return false;
}
}
fclose($handle);
return true;
}
}
+185
View File
@@ -0,0 +1,185 @@
<?php
namespace App\Services;
use App\Models\ProjectCostLine;
use App\Support\FixedPoint;
use InvalidArgumentException;
/**
* Exact decimal costing math for project cost snapshots, using bounded integer
* fixed-point arithmetic (see FixedPoint) instead of floats. Filament, packaging
* and shipping are kept as distinct totals; a missing category stays null
* ("not costed") rather than being coerced to zero.
*/
class ProjectCosting
{
private const QUANTITY_SCALE = 3;
private const RATE_SCALE = 6;
private const AMOUNT_SCALE = 4;
private const MAX_QUANTITY = 1_000_000;
private const MAX_RATE = 1_000_000;
/**
* Matches the project_cost_lines/project_cost_snapshots decimal(14,4) columns:
* at most 10 integer digits, so amounts must be checked before insert rather
* than left for the database to reject (or silently truncate) at write time.
*/
private const MAX_AMOUNT_SCALED = 99_999_999_999_999;
/** @var array<string, string> */
private const UNIT_BY_CATEGORY = [
ProjectCostLine::CATEGORY_FILAMENT => 'g',
ProjectCostLine::CATEGORY_PACKAGING => 'unit',
ProjectCostLine::CATEGORY_SHIPPING => 'parcel',
];
/** @var list<string> */
public const ALLOWED_CURRENCIES = [
'GBP', 'USD', 'EUR', 'CAD', 'AUD', 'NZD', 'JPY', 'CHF', 'SEK', 'NOK',
'DKK', 'PLN', 'CZK', 'SGD', 'HKD', 'MXN', 'ZAR', 'ILS',
];
public static function isValidCurrency(string $currency): bool
{
return in_array(strtoupper($currency), self::ALLOWED_CURRENCIES, true);
}
/**
* Each category has exactly one accepted unit so a mistyped or mislabelled
* unit (e.g. "G", "grams", "kg") is rejected at validation time instead of
* silently skipping or mis-applying the gram-to-kilogram conversion.
*/
public static function isValidUnitForCategory(string $category, string $unit): bool
{
return isset(self::UNIT_BY_CATEGORY[$category]) && self::UNIT_BY_CATEGORY[$category] === $unit;
}
/**
* @param list<string> $currencies
*/
public static function assertSameCurrency(array $currencies): void
{
$unique = array_unique(array_map('strtoupper', $currencies));
if (count($unique) > 1) {
throw new InvalidArgumentException('Cannot combine cost figures in different currencies without an explicit conversion: '.implode(', ', $unique));
}
}
public static function lineTotal(string $category, string $quantity, string $quantityUnit, string $unitRate, string $waste = '0'): string
{
if (! in_array($category, ProjectCostLine::CATEGORIES, true)) {
throw new InvalidArgumentException("Unknown cost category: {$category}");
}
if (! self::isValidUnitForCategory($category, $quantityUnit)) {
throw new InvalidArgumentException("Invalid quantity unit '{$quantityUnit}' for category '{$category}'; expected '".self::UNIT_BY_CATEGORY[$category]."'.");
}
$quantityScaled = FixedPoint::toScaled($quantity, self::QUANTITY_SCALE, self::MAX_QUANTITY, allowNegative: false);
$wasteScaled = FixedPoint::toScaled($waste, self::QUANTITY_SCALE, self::MAX_QUANTITY, allowNegative: false);
$rateScaled = FixedPoint::toScaled($unitRate, self::RATE_SCALE, self::MAX_RATE, allowNegative: false);
$effectiveQuantity = FixedPoint::add($quantityScaled, $wasteScaled);
$product = FixedPoint::multiply($effectiveQuantity, $rateScaled);
$productScale = self::QUANTITY_SCALE + self::RATE_SCALE;
if ($category === ProjectCostLine::CATEGORY_FILAMENT && $quantityUnit === 'g') {
// Rate is per kilogram, so the result needs an extra /1000. Treating the
// product as if it carried 3 more scale places folds that division into
// the normal rescale-down-to-amount-scale step.
$amount = FixedPoint::rescale($product, $productScale + 3, self::AMOUNT_SCALE);
self::assertWithinStorableAmount($amount);
return FixedPoint::format($amount, self::AMOUNT_SCALE);
}
$amount = FixedPoint::rescale($product, $productScale, self::AMOUNT_SCALE);
self::assertWithinStorableAmount($amount);
return FixedPoint::format($amount, self::AMOUNT_SCALE);
}
/**
* Shipping's units-per-parcel allocation is a distinct concept from the
* batch's manufacturing yield (see perUnit()): it divides a parcel's cost by
* how many saleable units that one parcel carries, never by how many units
* the print batch itself produced. The two divisions must never be chained.
*/
public static function shippingUnitContribution(string $unitRate, int $unitsPerParcel): string
{
if ($unitsPerParcel < 1) {
throw new InvalidArgumentException('Units per parcel must be a positive number of saleable units.');
}
$rateScaled = FixedPoint::toScaled($unitRate, self::RATE_SCALE, self::MAX_RATE, allowNegative: false);
$amount = FixedPoint::rescale($rateScaled, self::RATE_SCALE, self::AMOUNT_SCALE);
self::assertWithinStorableAmount($amount);
return FixedPoint::format(FixedPoint::divideByInt($amount, $unitsPerParcel), self::AMOUNT_SCALE);
}
private static function assertWithinStorableAmount(int $amountScaled): void
{
if (abs($amountScaled) > self::MAX_AMOUNT_SCALED) {
throw new InvalidArgumentException('Cost amount exceeds the storable precision bound.');
}
}
/**
* @param list<array{category: string, line_total: string}> $lines
* @return array{filament_total: ?string, packaging_total: ?string, shipping_total: ?string, grand_total: ?string}
*/
public static function aggregate(array $lines): array
{
$totals = [];
foreach (ProjectCostLine::CATEGORIES as $category) {
$categoryLines = array_values(array_filter($lines, fn (array $line): bool => $line['category'] === $category));
if ($categoryLines === []) {
$totals[$category] = null;
continue;
}
$sum = 0;
foreach ($categoryLines as $line) {
$sum = FixedPoint::add($sum, FixedPoint::toScaled((string) $line['line_total'], self::AMOUNT_SCALE));
}
self::assertWithinStorableAmount($sum);
$totals[$category] = FixedPoint::format($sum, self::AMOUNT_SCALE);
}
$grand = null;
foreach ($totals as $value) {
if ($value === null) {
continue;
}
$scaled = FixedPoint::toScaled($value, self::AMOUNT_SCALE);
$grand = $grand === null ? $scaled : FixedPoint::add($grand, $scaled);
}
if ($grand !== null) {
self::assertWithinStorableAmount($grand);
}
return [
'filament_total' => $totals[ProjectCostLine::CATEGORY_FILAMENT],
'packaging_total' => $totals[ProjectCostLine::CATEGORY_PACKAGING],
'shipping_total' => $totals[ProjectCostLine::CATEGORY_SHIPPING],
'grand_total' => $grand === null ? null : FixedPoint::format($grand, self::AMOUNT_SCALE),
];
}
public static function perUnit(string $grandTotal, int $batchUnits): string
{
if ($batchUnits < 1) {
throw new InvalidArgumentException('Batch yield must be a positive number of saleable units.');
}
$scaled = FixedPoint::toScaled($grandTotal, self::AMOUNT_SCALE);
return FixedPoint::format(FixedPoint::divideByInt($scaled, $batchUnits), self::AMOUNT_SCALE);
}
}