@happyvertical/ smrt- 制造
S-m-r-t框架的材料单、成本滚动和生产订单操作。 严格的工业中立性——同种原始人服务于服装,家具,汽车,CPG,电子,食品生产,定制硬件,以及从食谱中构建成品的任何其他垂直.
安装
pnpm add @happyvertical/smrt-manufacturing
此软件包取决于 @happyvertical/smrt-inventory 库存业务和 @happyvertical/smrt-products 用于目录 : Assembly 是一个 Product 子类型,和帐单行指向 Sku 编号.
使用量
界定议会及其法案
一个 Assembly 是一种产品,与 Material它生活在共享的 products 表格 (单位:千美元)productType: 'assembly')并增加了三个自己的领域: estimatedLabourMinutes, (中文(简体) ), defaultOperationId 财务报告和审定财务报表 partReference其部分编号和库存来自 Sku因为它的法案。 子组装只是一条法案线,其SKU属于另一个会.
import { SkuCollection } from '@happyvertical/smrt-products/collections';
import {
AssemblyCollection,
BillOfMaterialsCollection,
BomLineCollection,
} from '@happyvertical/smrt-manufacturing';
const assemblies = await AssemblyCollection.create({ db });
const skus = await SkuCollection.create({ db });
const boms = await BillOfMaterialsCollection.create({ db });
const lines = await BomLineCollection.create({ db });
const panel = await assemblies.create({ name: 'Side panel', partReference: 'DWG-200' });
const panelSku = await skus.create({ productId: panel.id!, code: 'SP-100' });
const frame = await assemblies.create({
name: 'Frame',
partReference: 'DWG-100',
estimatedLabourMinutes: 95,
});
const frameBom = await boms.create({ productId: frame.id!, version: 1, status: 'active' });
// Two side panels per frame: a sub-assembly line.
await lines.create({ bomId: frameBom.id!, componentSkuId: panelSku.id!, qtyPerUnit: 2 });
解决一个组件并拒绝循环
import { AssemblyService, BomCycleError } from '@happyvertical/smrt-manufacturing';
const assemblyService = await AssemblyService.create({ db });
const component = await assemblyService.resolveComponent(panelSku.id!);
// component.kind: 'assembly' | 'material' | 'bought' | 'missing'
// component.activeBom: the sub-assembly's active bill, or null when it has none
// component.buildable: true only for an assembly with an active bill
const frameSku = await skus.create({ productId: frame.id!, code: 'FR-100' });
const panelBom = await boms.create({ productId: panel.id!, version: 1, status: 'active' });
try {
// The frame contains the panel, so the panel may not contain the frame.
await lines.create({ bomId: panelBom.id!, componentSkuId: frameSku.id!, qtyPerUnit: 1 });
} catch (error) {
if (error instanceof BomCycleError) {
console.log(error.message);
// Refused: "Side panel" would contain itself: Side panel → Frame → Side panel
}
}
每个 BomLine 惟有一部分人 active 帐单, 运行此检查, 因此生成的 REST 路径也拒绝循环 。 只有正在使用的次级组装计数法案;草案或被取代的法案不是结构的一部分.
定义包含组件的管理局
import {
BillOfMaterialsCollection,
BomLineCollection,
} from '@happyvertical/smrt-manufacturing';
const db = { type: 'sqlite', url: 'app.db' };
const boms = await BillOfMaterialsCollection.create({ db });
const lines = await BomLineCollection.create({ db });
const bom = await boms.create({
productId: shirt.id, // upstream Product or any STI subtype
version: 1,
status: 'active',
currency: 'USD',
notes: 'Initial revision',
});
await bom.save();
const fabric = await lines.create({
bomId: bom.id!,
componentSkuId: fabricSku.id!,
qtyPerUnit: 2.0,
uom: 'yards',
wastePercent: 10, // 10% cutting waste
});
await fabric.save();
const buttons = await lines.create({
bomId: bom.id!,
componentSkuId: buttonSku.id!,
qtyPerUnit: 4,
uom: 'each',
});
await buttons.save();
与废物一起滚出材料成本
import { BomService } from '@happyvertical/smrt-manufacturing';
const service = await BomService.create({
db,
// Plug in any cost source: smrt-products Material.costPerUnit,
// a purchase-order rolling average, a vendor price book, anything.
costResolver: async (componentSkuId) => {
const sku = await skus.get(componentSkuId);
return sku?.attributes ? Number(JSON.parse(sku.attributes).cost ?? 0) : null;
},
});
const rollup = await service.computeMaterialCost(bom.id!);
console.log(rollup.totalCost, rollup.currency);
// Walks lines, applies waste, surfaces a per-line breakdown.
业务、路线和估计劳动力
一个 Operation 一种工作(剪接、焊接、检查)作为管理清单保存,每件
租户. 一份材料单可携带一条路线:一份订购的业务清单,
每个单元估计持续时间为分钟。 没有路由的账单
和以前一样.
import {
BomService,
OperationService,
RoutingService,
} from '@happyvertical/smrt-manufacturing';
const operations = await OperationService.create({ db });
const cut = await operations.define({ code: 'CUT', name: 'Cutting', category: 'fabrication' });
const weld = await operations.define({
code: 'WELD',
name: 'Welding',
// Plain id of a smrt-human-resources Qualification; an application reads it
// to decide who may start the operation. Not validated here.
requiredQualificationId: qualificationId,
});
await operations.rename(cut.id!, 'Plasma cutting');
await operations.retire(weld.id!); // leaves pickers, stays on history
await operations.reinstate(weld.id!);
const routing = await RoutingService.create({ db });
await routing.replaceRouting(bom.id!, [
{ operationId: cut.id!, estimatedMinutes: 30 },
{ operationId: weld.id!, estimatedMinutes: 90, notes: 'tack first' },
]);
const service = await BomService.create({
db,
// Optional, like costResolver: hourly rate for an operation, or null.
rateResolver: (operation) => (operation.code === 'WELD' ? 80 : 60),
});
const labour = await service.computeLabourEstimate(bom.id!);
console.log(labour.totalMinutes, labour.totalCost, labour.steps);
replaceRouting 在一次交易中互换整个路径( 步骤编号)
1.n 按给出的顺序;空列表将其删除). 退休手术可以留下来
在一条已有但不能新添加的路线上。 没有
rateResolver 估计仅报告分钟,并标出每个步骤
rateUnavailable。 。 。 .
操作清单和表格
@happyvertical/smrt-manufacturing/svelte 出口道具驱动 OperationList
(带有可选编辑、退出和恢复动作)和 OperationForm (添加,或
编辑名称、类别和所需资格;代码一旦确定就固定了).
他们登记在 ModuleUIRegistry 输入时。 主机装入行通过
OperationService 并亲自行动.
计划进行生产
const requirements = await service.explodeRequirements(bom.id!, 100);
// [{ componentSkuId: fabricSku.id, totalQty: 220, uom: 'yards' },
// { componentSkuId: buttonSku.id, totalQty: 400, uom: 'each' }]
const check = await service.canProduce(bom.id!, 100);
if (!check.ok) {
for (const shortage of check.shortages) {
console.log(
`Need ${shortage.requested} of ${shortage.componentSkuId}, have ${shortage.available}`,
);
}
}
行走子组装
每个 BomService 方法默认读取一个级别。 过 { levels } (若干级法案,或 'all')打开每个有活性账单的子组装. 废物化合物的含量会降低;单位会按每行申报的顺序保留.
const service = await BomService.create({ db });
// Gross: every line with its level and path, plus the rolled-up totals.
const explosion = await service.explode(frameBom.id!, 10, { levels: 'all' });
// explosion.lines: [{ level: 1, name: 'Side panel', totalQty: 20, expanded: true, ... },
// { level: 2, name: 'Steel tube', totalQty: 44, uom: 'm', ... }, ...]
// explosion.totals: [{ componentSkuId: tubeSku.id, totalQty: 44, uom: 'm' }]
// Net of stock: what is available, what is short, and what building the
// shortfall of each sub-assembly takes. Facts only; you decide build or buy.
const plan = await service.planRequirements(frameBom.id!, 10, { levels: 'all' });
// plan.lines: [{ name: 'Side panel', totalQty: 20, available: 5, short: 15, expanded: true }, ...]
// plan.shortages: [{ componentSkuId: tubeSku.id, requested: 33, available: 0, level: 2, path: [...] }]
await service.canProduce(frameBom.id!, 10, { levels: 'all' }); // shortages at their own level
await service.computeMaterialCost(frameBom.id!, { levels: 'all' }); // sub-assemblies costed from their bills
await service.computeLabourEstimate(frameBom.id!, { levels: 'all' }); // adds sub-assembly routings
步行停在材料,购买物品, 集会没有活跃的法案和 levels 限制。 它拒绝一个更深的结构 MAX_EXPLOSION_DEPTH (32) 水平或大于 MAX_EXPLOSION_LINES,且存储数据中已经存在的循环失败 BomStructureCycleError 点名.
记录生产运行
A 类 ProductionRun 以一个法案作为目标数量,一旦发生,就予以报告.
import { ProductionRunService } from '@happyvertical/smrt-manufacturing';
const runs = await ProductionRunService.create({ db });
const run = await runs.createRun({ productId: frame.id!, targetQty: 25 }); // pins the active bill
await runs.recordCompletion(run.id!, { qty: 12 }); // 25 to build, 12 done; no stock moves
// Optionally consume the bill and receive the finished units in the same transaction.
await runs.recordCompletion(run.id!, {
qty: 13,
consume: { locationId: factory.id! },
produce: { locationId: factory.id!, finishedSkuId: frameSku.id! },
}); // the run is now done
start, (中文(简体) ), finish (低于目标), cancel 财务报告和审定财务报表 setTarget 移动运行通过 planned, (中文(简体) ), in_progress, (中文(简体) ), done 财务报告和审定财务报表 cancelled。并行报告全部计数,永远不通过目标。 数量是十进制, 一直到六位, 并准确总结,所以 0.1 + 0.2 完成目标为 0.3; 运行接受数量最多 MAX_QUANTITY (999,999,999) (中文(简体) ).
根据生产订单执行消费/生产
这个 ProductionOrder 排队本身就住在 @happyvertical/smrt-commerce 作为 Contract STI子类型. 这个包代表它修改了存货分类账.
import { ProductionService } from '@happyvertical/smrt-manufacturing';
const production = await ProductionService.create({ db });
// Pull materials from the factory.
const consumed = await production.consumeMaterials(
{
id: order.id, // ProductionOrder.id
productId: order.productId,
},
{
locationId: factory.id, // explicit — not stored on the order
qty: 100,
},
);
// Receive finished goods.
const produced = await production.produceFinishedGoods(
{ id: order.id, productId: order.productId },
{
locationId: factory.id,
qty: 100,
finishedSkuId: finishedVariant.id, // explicit — one productId can have many SKUs
},
);
每一次发射 StockMovement 标记为 sourceType: 'ProductionOrder' 加号 sourceId: order.id 这样审计查询就可以重建后来发生的事情 StockMovementCollection.findBySource('ProductionOrder', order.id)。 。 。 .
多重租赁
Assembly, (中文(简体) ), BillOfMaterials 财务报告和审定财务报表 BomLine 使用情况 @TenantScoped({ mode: 'optional' }) 与无效 tenantId。环绕突变 withTenant() 从 @happyvertical/smrt-tenancy 自动到范围查询.
import { withTenant } from '@happyvertical/smrt-tenancy';
await withTenant({ tenantId: 'tenant-a' }, async () => {
const requirements = await service.explodeRequirements(bom.id!, 50);
// Reads are auto-filtered by tenant_id = 'tenant-a'.
});
自动插播布线
将生产-订单生命周期事件与消耗/生产流量挂钩的货包船舶装卸商。 默认关闭; 在您明确安装 smrt.ts数字 :
import { createDispatchBus } from '@happyvertical/smrt-core';
import { installInventoryDispatchHandlers } from '@happyvertical/smrt-inventory';
import { installManufacturingDispatchHandlers } from '@happyvertical/smrt-manufacturing';
const bus = await createDispatchBus({ db });
// Inventory handlers bridge contract:created and fulfillment:shipped.
await installInventoryDispatchHandlers({ dispatchBus: bus, db });
// Manufacturing handlers bridge production_order:posted (and optionally
// production_order:completed) to consume / produce.
await installManufacturingDispatchHandlers({
dispatchBus: bus,
db,
// Consume and produce in one shot when posted (make-to-stock).
producedOnPosted: true,
});
// Later, when a production order is posted:
await bus.emit('production_order:posted', {
productionOrderId: order.id,
productId: order.productId,
locationId: factory.id,
qty: 100,
finishedSkuId: finishedVariant.id, // only needed when producedOnPosted: true
});
手动切换( P)installProductionPosted, (中文(简体) ), installProductionCompleted让消费者选择他们想要的腿 伴侣 contract:created 财务报告和审定财务报表 fulfillment:shipped 管理者居住 @happyvertical/smrt-inventory。 。 。 .
Svelte 组件
@happyvertical/smrt-manufacturing/svelte 船道具驱动组件;主机加载数据并保存.
<script lang="ts">
import {
AssemblyForm,
AssemblyList,
BomEditor,
ProductionRunList,
RequirementsTree,
toRequirementTotals,
toRequirementTree,
} from '@happyvertical/smrt-manufacturing/svelte';
let { assemblies, policy, assembly, operations, lines, components, runs, plan } = $props();
</script>
<AssemblyList {assemblies} {policy} onselect={(id) => goto(`/assemblies/${id}`)} />
<AssemblyForm {assembly} {operations} hiddenFields={['price']} onsubmit={save} />
<BomEditor {lines} {components} onadd={addLine} loadBill={loadLines} error={saveError} />
<ProductionRunList
{runs}
oncomplete={(runId, qty) => report(runId, qty)}
onsettarget={(run, target) => runService.setTarget(run.id, target)}
onfinish={(run) => runService.finish(run.id)}
oncancel={(run) => runService.cancel(run.id)}
/>
<RequirementsTree lines={toRequirementTree(plan)} totals={toRequirementTotals(plan)} />
AssemblyList 选中已解析的字段 policy 用于装配并放下所隐藏的柱子(未显示隐藏价格). AssemblyForm 名称、说明、类别、部分参考、价格(按主要单位类型,对照 currency prop的次要单位 , 作为整数小单位移交; 读取器留下的字段保持其存储值的准确性 , 估计劳动力( 整分, 0分或多分), 默认操作拾取器 operations 您通过(通过活动操作;已退休或未上市的当前操作保留选中、标记和可以清除)和标记。 通过 assembly 并绘制读者的实地政策地图 hiddenFields (未提供)和 readonlyFields (shown, 不可编辑); 两者的初始值都通过 onsubmit 没有改变,所以只保留读者可以写的东西. onsubmit(values, formData) 接收选中值和窗体 FormData形式从未存在. showSkuCode 添加一个必需的分号字段(组装代码: Sku; 修剪为 values.skuCode,缺席 values 未显示时; 给出存储代码为 assembly.skuCode; 从保存中报告重复代码 errors={{ fields: { skuCode: 'FR-100 is already in use.' } }} (单位:千美元)errors.form 显示整个格式的信息. extraFields 是一个在它行动之前在表单内 显示的片段,所以一个主机自己命名的控件会随它一起提交并到达 formData。用 toAssemblyView 编辑行 toBomEditorLines(await assemblyService.getBillStructure(bomId))中的子组合行 BomEditor 说它是否有自己的账单 并扩展只读通过 loadBill。 。 。 . ProductionRunList 显示每个运行的进展和状态,并 oncomplete,用于报告已完成单位的字段(从 toProductionRunView) (中文(简体) ). onsettarget(run, target), (中文(简体) ), onfinish(run) 财务报告和审定财务报表 oncancel(run) 每一个都为打开运行添加自己的控制,并且只有在给定时才会添加:目标字段(检查高于零,而不是低于已完成的工作),通过一个 ConfirmDialog 先说 返回的处理器 false 或丢出保留输入并显示失败消息; 主机呼叫 ProductionRunService.setTarget, (中文(简体) ), finish 或者说 cancel 刷新时 runs。 。 。 . RequirementsTree 显示 explode 或者说 planRequirements 按级别、计划可用和每行短数得出结果.
无组件视图适配器
@happyvertical/smrt-manufacturing/views 出口 toBomEditorLine, (中文(简体) ), toBomEditorLines, (中文(简体) ), toRequirementTree 财务报告和审定财务报表 toRequirementTotals (及其资源) BomEditorLine, (中文(简体) ), RequirementLineView 财务报告和审定财务报表 RequirementTotalView 类型)从一个没有组件的模块中导入,所以服务器负载可以在不编译任何内容的情况下调整服务结果 .svelte 文档. ./svelte 再出口的功能不变.
API 密码
模型
| 导出 | 说明 |
|---|---|
Assembly | 制作的产品: Product STI 子类型 estimatedLabourMinutes, (中文(简体) ), defaultOperationId, (中文(简体) ), partReference。 。 。 . |
BillOfMaterials | 一个成品的食谱. 版本为 a draft 编号 : active 编号 : superseded 生命周期. |
BomLine | 一个组件在BOM. effectiveQtyPerUnit() 返回包括废物在内的qty. |
Operation | 一种工作: code (每个房客的独特性), name, (中文(简体) ), category, (中文(简体) ), isActive (退休业务保持历史,从未被删除),可选 requiredQualificationId (平面字符串 id of a) smrt-human-resources 资格). |
RoutingStep | 在BOM的可选路线中有一个操作: bomId, (中文(简体) ), operationId, (中文(简体) ), sequence (一.n),(c), estimatedMinutes, (中文(简体) ), notes。 。 。 . |
ProductionRun | 一项法案: bomId, (中文(简体) ), targetQty, (中文(简体) ), completedQty, (中文(简体) ), status (单位:千美元)planned 编号 : in_progress 编号 : done 编号 : cancelled) (中文(简体) ). 写入 ProductionRunService。 。 。 . |
ProductionRunCompletion | 一份已完成的单位运行报告: runId, (中文(简体) ), qty, (中文(简体) ), completedAt。 。 。 . |
收款
| 导出 | 说明 |
|---|---|
AssemblyCollection | 共享的组合行 products 页:1. |
BillOfMaterialsCollection | findByProduct, (中文(简体) ), findActiveForProduct, (中文(简体) ), findByStatus |
BomLineCollection | findByBom, (中文(简体) ), findByComponent |
OperationCollection | findByCode, (中文(简体) ), listOperations({ includeRetired? }) |
RoutingStepCollection | findByBom (按步骤顺序排列), findByOperation |
ProductionRunCollection | findByBom, (中文(简体) ), findByStatus |
ProductionRunCompletionCollection | findByRun (按完成顺序) |
服务
| 导出 | 说明 |
|---|---|
AssemblyService | resolveComponent, (中文(简体) ), findActiveBom, (中文(简体) ), isAssembly, (中文(简体) ), getBillStructure, (中文(简体) ), findCycle, (中文(简体) ), assertLineAcyclic, (中文(简体) ), assertBillAcyclic。通过 { tenantId } 读取一个租户的结构. |
createAssemblyService({ db }) | 便利工厂. |
BomCycleError | A 类 ValidationError 名称 path 这样节省可以让一个产品 包含自己. |
BomService | 费用上涨、需求爆炸、罐头检查; { levels } 走路的子组装. explode (项目毛额和共计)和 planRequirements (净入股. |
BomStructureCycleError, (中文(简体) ), BomExplosionLimitError | 一个行走遇到存储数据的循环,或超过 MAX_EXPLOSION_DEPTH 编号 : MAX_EXPLOSION_LINES。 。 。 . |
ProductionRunService 编号 : createProductionRunService({ db }) | createRun, (中文(简体) ), get, (中文(简体) ), listCompletions, (中文(简体) ), start, (中文(简体) ), recordCompletion, (中文(简体) ), finish, (中文(简体) ), cancel, (中文(简体) ), setTarget。 。 。 . |
ProductionRunNotFoundError, (中文(简体) ), ProductionRunStateError, (中文(简体) ), ProductionRunOverCompletionError, (中文(简体) ), InvalidProductionRunInputError | 生产运行失误. |
createBomService({ db, costResolver?, rateResolver? }) | 便利工厂. computeLabourEstimate(bomId) 上行路由分钟,还有 rateResolver,成本。 费用. |
OperationService 编号 : createOperationService({ db }) | define, (中文(简体) ), get, (中文(简体) ), list, (中文(简体) ), rename, (中文(简体) ), update, (中文(简体) ), retire, (中文(简体) ), reinstate。 。 。 . |
RoutingService 编号 : createRoutingService({ db }) | list(bomId), (中文(简体) ), replaceRouting(bomId, steps)。 。 。 . |
OperationNotFoundError, (中文(简体) ), DuplicateOperationCodeError, (中文(简体) ), OperationRetiredError, (中文(简体) ), InvalidOperationInputError | 操作和路由错误. |
ProductionService | 根据生产订单进行业务消费/生产. |
createProductionService({ db }) | 便利工厂. |
installManufacturingDispatchHandlers({ dispatchBus, db }) | 客运专线. |
BomNotFoundError | 当BOM ID无法解决时丢弃. |
NoActiveBomForProductError | 被丢弃 ProductionService 既未明确 bomId 生产订单中也不可用活性BOM. |
类型
| 导出 | 说明 |
|---|---|
BomStatus | 'draft' | 'active' | 'superseded' |
ComponentKind | 'assembly' | 'material' | 'bought' | 'missing' |
ResolvedComponent | 返回形状 resolveComponent。 。 。 . |
BillStructure | 返回形状 getBillStructure。 。 。 . |
BomCostRollup | 返回形状 computeMaterialCost。 。 。 . |
BomLineCost | A 内的每行条目 BomCostRollup。 。 。 . |
MaterialRequirement | 返回条目 explodeRequirements。 。 。 . |
MaterialShortage | 返回条目 canProduce 当库存不足时. |
CanProduceResult | { ok: true; shortages: [] } | { ok: false; shortages: [...] } |
ExplosionLevels, (中文(简体) ), ExplosionOptions | levels:若干法案级别或 'all'。 。 。 . |
Explosion, (中文(简体) ), ExplodedLine, (中文(简体) ), ExplosionPathEntry | 返回形状 explode。 。 。 . |
RequirementsPlan, (中文(简体) ), PlannedLine | 返回形状 planRequirements。 。 。 . |
SubAssemblyLabour | 在一个多层次的子组装 LabourEstimate。 。 。 . |
CreateProductionRunInput, (中文(简体) ), RecordCompletionInput, (中文(简体) ), RecordCompletionResult | 生产投入和成果. |
ComponentCostResolver | Async( 或同步) 回调单位成本或 null。 。 。 . |
OperationRateResolver | Async(或同步)回调返回一个操作的小时费率或 null。 。 。 . |
LabourEstimate, (中文(简体) ), RoutingStepEstimate | 返回形状 computeLabourEstimate。 。 。 . |
DefineOperationInput, (中文(简体) ), RoutingStepInput | 输入到 define 财务报告和审定财务报表 replaceRouting。 。 。 . |
依赖关系
| 软件包 | 目的 |
|---|---|
@happyvertical/smrt-core | Smrt 对象 / Smrt Collection / 调度局 |
@happyvertical/smrt-inventory | 库存服务(假设/生产目标) |
@happyvertical/smrt-products | Product (基数 Assembly, (中文(简体) ), Material, (中文(简体) ), Sku |
@happyvertical/smrt-ui | Svelte 控件和 i18n |
@happyvertical/smrt-tenancy | 备选租户范围界定 |
@happyvertical/smrt-ui 编号 : @happyvertical/smrt-types | 行动清单和表格(./svelte模块插槽(./ui(三); svelte 是可选对等点 |
@happyvertical/sql | 数据库适配器 |
许可证
麻省理工学院