# @happyvertical/smrt-inventory 中文文档

规范地址：https://npmcn.com/package/%40happyvertical/smrt-inventory/

版本：0\.62\.1
npm 元数据更新时间：2026-11-17T07:53:43.480Z
中文译文更新时间：2026-11-17T10:09:01.600Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40happyvertical/smrt-inventory
原文对照：https://npmcn.com/package/%40happyvertical/smrt-inventory/?lang=original
项目主页：https://github.com/happyvertical/smrt#readme
源码仓库：https://github.com/happyvertical/smrt

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：815 kB，86 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：6 个
- peer 依赖：svelte ^5\.57\.0
- 首次发布：2026-06-23T01:18:36.102Z
- 最新版本发布：2026-11-17T07:53:43.280Z
- 近 30 天下载量：14753（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：365（近 12 个月 365 个）

## 中文简介

SMRT框架的多地储存跟踪——Sku、库存存放、库存级、库存移动、批量和序列跟踪以及库存模拟和批量服务

## 安装

```sh
npm install @happyvertical/smrt-inventory
```

也可以使用：`pnpm add @happyvertical/smrt-inventory`、`yarn add @happyvertical/smrt-inventory`、`bun add @happyvertical/smrt-inventory`

## README

# @happyvertical/ smrt-inforum (原始内容存档于2018-09-29) (英语)

S-m-r-t框架的多地盘跟踪。 严格意义上的工业中立性——同样的原始人服务于服装,家具,汽车,CPG,电子产品,以及其它任何能够统计出不同地点的离散单位的垂直.

## 安装

```bash
pnpm add @happyvertical/smrt-inventory
```

## 使用量

### 设立SKU、地点和股票服务

```typescript
import {
  createStockService,
  InventoryLocationCollection,
} from '@happyvertical/smrt-inventory';
// The `@happyvertical/smrt-products` root entry pulls in Vite virtual
// modules (`@smrt/client` etc.) and won't resolve under plain Node /
// tsx. Import from the `/collections` subpath for server-side scripts,
// tests, and SSR runtimes that don't run the Vite plugin.
import { SkuCollection } from '@happyvertical/smrt-products/collections';

const db = { type: 'sqlite', url: 'app.db' };
const skus = await SkuCollection.create({ db });
const locations = await InventoryLocationCollection.create({ db });
const stock = await createStockService({ db });

const widget = await skus.create({
  productId: 'prod-1',
  code: 'WIDGET-001',
  barcode: '0123456789012',
  attributes: { finish: 'matte' },
});
await widget.save();

const warehouse = await locations.create({
  code: 'WH-EAST',
  name: 'Warehouse East',
  kind: 'warehouse',
});
await warehouse.save();
```

### 将股票在整个生命周期移动

每个方法写一个(或两个,用于转账) `StockMovement` 审计行,所以分类账 保持锁定与实际水平.

```typescript
// Inbound receipt — +qty available.
await stock.receive(widget.id!, warehouse.id!, 100, {
  sourceType: 'PurchaseOrder',
  sourceId: po.id,
});

// Reserve against an order — available → allocated.
// Throws InsufficientStockError if there isn't enough available.
await stock.reserve(widget.id!, warehouse.id!, 10, {
  sourceType: 'Contract',
  sourceId: order.id,
});

// Ship — removes from allocated, leaves the building.
await stock.fulfill(widget.id!, warehouse.id!, 10, {
  sourceType: 'Fulfillment',
  sourceId: shipment.id,
});

// Cycle count caught five extra units — non-zero signed delta.
await stock.adjust(widget.id!, warehouse.id!, 5, {
  sourceType: 'CycleCount',
  sourceId: count.id,
});

// Move stock between locations — writes transfer_out + transfer_in legs.
await stock.transfer(widget.id!, warehouse.id!, store.id!, 12, {
  sourceType: 'TransferOrder',
  sourceId: xfer.id,
});
```

### 查询余额和审计日志

```typescript
import {
  StockLevelCollection,
  StockMovementCollection,
} from '@happyvertical/smrt-inventory';

const levels = await StockLevelCollection.create({ db });
const movements = await StockMovementCollection.create({ db });

// What's on hand at this location across every state?
const here = await levels.findByLocation(warehouse.id!);

// What's the available total for a SKU across all locations?
const availableTotal = await levels.totalForSku(widget.id!, 'available');

// What movements were caused by a particular contract?
const audit = await movements.findBySource('Contract', order.id);
```

### 抓取库存不足错误

```typescript
import { InsufficientStockError } from '@happyvertical/smrt-inventory';

try {
  await stock.reserve(widget.id!, warehouse.id!, 9999);
} catch (err) {
  if (err instanceof InsufficientStockError) {
    console.log(
      `Only ${err.available} available for ${err.skuId} at ${err.locationId}, requested ${err.requested}`,
    );
  } else {
    throw err;
  }
}
```

### 多重租赁

清单模型`InventoryLocation`, (中文(简体) ), `StockLevel`, (中文(简体) ), `StockMovement`,以及批量模型 `Lot`, (中文(简体) ), `LotUsage`, (中文(简体) ), `LotCorrection`, (中文(简体) ), `LotDocument`, (中文(简体) ), `LotStockLevel`(a) 使用情况 `@TenantScoped({ mode: 'optional' })` 与无效 `tenantId`。目录形状(`Sku`, (中文(简体) ), `Product`, (中文(简体) ), `ProductVariant`, (中文(简体) ), `Material`住在这里 `@happyvertical/smrt-products` 并携带他们自己的租户装饰; 交叉包装的id refs流出未变. 环绕突变 `withTenant()` 从 `@happyvertical/smrt-tenancy` 自动到范围查询.

```typescript
import { withTenant } from '@happyvertical/smrt-tenancy';

await withTenant({ tenantId: 'tenant-a' }, async () => {
  // Every read/write through skus, locations, levels, movements, and the
  // StockService is filtered by tenant_id = 'tenant-a'.
  await stock.receive(widget.id!, warehouse.id!, 100);
});
```

### 自动插播布线

搭桥的货船搬运工 `contract:created` → `reserve()` 财务报告和审定财务报表 `fulfillment:shipped` → `fulfill()`。默认关闭;在您的 `smrt.ts` 用于自动存量运动:

```typescript
import { createDispatchBus } from '@happyvertical/smrt-core';
import { installInventoryDispatchHandlers } from '@happyvertical/smrt-inventory';

const bus = await createDispatchBus({ db });
const handlers = await installInventoryDispatchHandlers({
  dispatchBus: bus,
  db,
});

// In smrt-commerce (or your own code):
await bus.emit('contract:created', {
  contractId: order.id,
  lines: [{ skuId, locationId, qty }],
});

// Later, on shipment:
await bus.emit('fulfillment:shipped', {
  fulfillmentId: shipment.id,
  lines: [{ skuId, locationId, qty }],
});
```

手动切换( P)`installContractReserved`, (中文(简体) ), `installFulfillmentShipped`让消费者准确选择他们所关心的信号。 这个 `production_order:posted` 处理者是故意的 _没有_ 这座桥就住在这 `@happyvertical/smrt-manufacturing`。 。 。 .

## API 密码

### 模型

| 导出 | 说明 |
| --- | --- |
| `InventoryLocation` | 实物或虚拟储存网站,开放 `kind`。 。 。 . |
| `StockLevel` | 已实现 `(skuId, locationId, state) → qty` 排队. **绝不直接变异——使用 `StockService`。 。 。 .** |
| `StockMovement` | 仅附加审计行. 每变出一出;转出二出. 携带无效 `lotId`。 。 。 . |
| `Lot` | 一批(`kind: 'lot'`)或单单位(`'serial'`),具有数字,属性和地位. **通过 `LotService`。 。 。 .** |
| `LotStockLevel` | 已实现 `(lotId, locationId, state) → qty` 排队. **仅由 `StockService`。 。 。 .** |
| `LotUsage` | 消费者使用的很多`consumerType` + 键 `consumerId`· ; `'Lot'` (为集会)。 从未删除; `unlinked` 换句话说. |
| `LotCorrection` | 每一次更正只附加记录,并附有理由,新旧等值. |
| `LotDocument` | 大量附着的已存储文件( 资产 id) 。 已删除,从未删除. |

### 收款

| 导出 | 说明 |
| --- | --- |
| `InventoryLocationCollection` | `findByCode`, (中文(简体) ), `findByKind`, (中文(简体) ), `findByPlace`, (中文(简体) ), `findActive` |
| `StockLevelCollection` | `getLevel`, (中文(简体) ), `findBySku`, (中文(简体) ), `findByLocation`, (中文(简体) ), `totalForSku`, (中文(简体) ), `totalForLocation` |
| `StockMovementCollection` | `findBySku`, (中文(简体) ), `findByLocation`, (中文(简体) ), `findBySource`, (中文(简体) ), `findByReason` |
| `LotCollection` | `findByLotNumber(number, { skuId? })` (对大小写不敏感) |
| `LotStockLevelCollection` | `getLevel(lotId, locationId, state?)`, (中文(简体) ), `onHand(lotId, state?)` |
| `LotUsageCollection` | `findActiveForLot`, (中文(简体) ), `findForConsumer` |
| `LotCorrectionCollection`, (中文(简体) ), `LotDocumentCollection` | 阅读权限 |

所有目录形状( E)`Product`, (中文(简体) ), `Material`, (中文(简体) ), `ProductVariant`, (中文(简体) ), `Sku`住在这里 [`@happyvertical/smrt-products`](https://npmcn.com/package/%40happyvertical/products)。本套件添加了存量运动层(`InventoryLocation`, (中文(简体) ), `StockLevel`, (中文(简体) ), `StockMovement`, (中文(简体) ), `StockService`在顶上.

### 服务

| 导出 | 说明 |
| --- | --- |
| `StockService` | 唯一允许的突变表面。 六种方法: `receive`, (中文(简体) ), `reserve`, (中文(简体) ), `release`, (中文(简体) ), `fulfill`, (中文(简体) ), `transfer`, (中文(简体) ), `adjust`。 。 。 . |
| `createStockService({ db })` | 便利工厂. |
| `InsufficientStockError` | 被丢弃 `reserve` 编号 : `fulfill` 编号 : `transfer` 负数 `adjust` 当股票出现负值时 卡莉丝 `skuId`, (中文(简体) ), `locationId`, (中文(简体) ), `state`, (中文(简体) ), `requested`, (中文(简体) ), `available`。 。 。 . |
| `LotService` 编号 : `createLotService({ db })` | 很多和连载: `receiveLot`, (中文(简体) ), `correctLotNumber`, (中文(简体) ), `correctAttributes`, (中文(简体) ), `setStatus`, (中文(简体) ), `recordUsage`, (中文(简体) ), `unlinkUsage`, (中文(简体) ), `attachDocument`, (中文(简体) ), `detachDocument`, (中文(简体) ), `history`, (中文(简体) ), `traceForward`, (中文(简体) ), `traceBack`, (中文(简体) ), `withTransaction`。 。 。 . |
| `DuplicateLotError`, (中文(简体) ), `LotInUseError`, (中文(简体) ), `LotMismatchError`, (中文(简体) ), `LotNotFoundError`, (中文(简体) ), `LotCorrectionError` | 大量的失败. |
| `installInventoryDispatchHandlers({ dispatchBus, db })` | 自动插播布线 `contract:created` 财务报告和审定财务报表 `fulfillment:shipped`。 。 。 . |

### 许多和系列

过 `lotId` 对任意 `StockService` 变异和同为三角形的分数按批量使用(具有同为非负数规则),分数被印在每次运动上;SKU级的平衡表现如前. `LotService` 创造众生。 接收的很多没有移动股票,所以两者都组成一个交易:

```typescript
await stock.withTransaction(async (tx) => {
  const lots = await createLotService({ db: tx.db });
  const lot = await lots.receiveLot({ lotNumber: 'B-1042', skuId, receivedQty: 40 });
  await tx.receive(skuId, locationId, 40, { lotId: lot.id });
});
await lots.recordUsage(lot.id, { consumerType: 'ProductionOrder', consumerId });
const trace = await lots.traceForward(lot.id);        // where it went
const sources = await lots.traceBack('ProductionOrder', consumerId); // where it came from
```

默认情况下,很多数字并非独一无二(一个供应商批次可在两个收据上到达);通过 `unique: true`,或 `kind: 'serial'`,使它这样,或 `idempotencyKey` 以重置收据 安全。 重复 `idempotencyKey` 返回即使其他字段不同的第一个批次,并重复 `recordUsage` 对于一个消费者来说,现有用法不变. `StockService` 忽略 `lot.status`;呼叫者决定隔离区可以做什么. 惩罚总是需要一个理由。 包中不检查授权;呼叫者授权和通过 `actorProfileId`。 。 。 .

现有部署必须在使用批量之前生成并应用其正常的 s-m-r-t 计划迁移:五个新的表格(`inventory_lots`, (中文(简体) ), `inventory_lot_stock_levels`, (中文(简体) ), `inventory_lot_usages`, (中文(简体) ), `inventory_lot_corrections`, (中文(简体) ), `inventory_lot_documents`和无效 `lot_id` 打开 `inventory_stock_movements` (UUID on PostgreSQL/DuckDB,文本取自SQLite). 现有行和 `StockLevel`'独有的密钥不变; 运行时间读取不创建表格 .

### 类型

| 导出 | 说明 |
| --- | --- |
| `StockState` | `'available' | 'allocated' | 'wip' | 'qc_hold' | 'damaged'` |
| `InventoryLocationKind` | 开放式分类器字符串 |
| `StockMovementReason` | 分类理由词汇表(`'receipt'`, (中文(简体) ), `'reservation'`, (中文(简体) ), `'release'`, (中文(简体) ), `'fulfillment'`, (中文(简体) ), `'transfer_out'`, (中文(简体) ), `'transfer_in'`, (中文(简体) ), `'adjustment'`, (中文(简体) ), `'production_consume'`, (中文(简体) ), `'production_produce'`)加自由形式字符串 |

## 依赖关系

| 软件包 | 目的 |
| --- | --- |
| `@happyvertical/smrt-core` | Smrt 对象 / Smrt Collection / 调度局 |
| `@happyvertical/smrt-tenancy` | 备选租户范围界定 |
| `@happyvertical/sql` | 数据库适配器 |

## 许可证

麻省理工学院

### 数据库初始化

`StockService.create()` 和交易范围服务建设初始化 他们的三部曲依次收录 每个初始化检查框架 共享连接上的系统表格;并行探测器可干扰 DuckDB (英语). 此订单不会改变单交易库存/审计合同 或运行时的应用程序计划.

包件测试套件覆盖了冷 SQLite/DuckDB 初始化并重复 交易回滚。 设定 `SMRT_TEST_POSTGRES_URL` 到一个孤立的 PostgreSQL 数据库,用于在 PostgreSQL 上进行相同的固定.

### 调整政策和行动行动者的秩序

`stock.setReorderPolicy(skuId, locationId, reorderPoint, reorderQuantity?)` 在 **可用** 库存行。 它创造了一个 必要时不发明审计动作的零余额行。 值必须 (一) 有限且不负; `null` 禁用监视并省略重排 数量澄清了它的建议。 股票变异保留了这些设置. `stock.levels.findBelowReorderPoint(locationId?)` 返回可见的现有行 数量为 **绝对少** 而不是他们所配置的点。 平等,未设定 阈值,而其他国家则不计. 两种方法都保留正常的租户 范围界定和设定人员参与 `stock.withTransaction()`。 。 。 .

每个突变都接受 `actorProfileId` 与源的归属。 这是一个 无效 `@happyvertical/smrt-profiles:Profile`复制到 包括两条转移腿 漏出记录 `null` 页:1 遗留的呼叫器和无人看管的自动化。 提供信任的配置文件 ID 服务器上下文; 此属性字段不授权调用者 .

现有部署必须产生和应用其正常的 s-m-r-t 计划迁移 在使用这些字段之前:添加可取消的小数 `reorder_point` 财务报告和审定财务报表 `reorder_quantity` 改为 `inventory_stock_levels`,和无效的配置参考 `actor_profile_id` 改为 `inventory_stock_movements` (UUID on PostgreSQL/DuckDB, sQLite上的案文。 已存在的行仍未被设定; 运行时间读取不移取表格 .

### Svelte 组件

可选 `@happyvertical/smrt-inventory/svelte` 条目导出 :

| 构成部分 | 数据/回调合同 |
| --- | --- |
| `StockLevels` | `levels`选项 `locationId`; 显示平衡、 重排序设置和低存量状态 |
| `MovementHistory` | `movements`; 仅读历史与演员, 源和注释 |
| `AdjustStockForm` | `skuId`, (中文(简体) ), `locationId`, (中文(简体) ), `onsubmit({ skuId, locationId, delta, reasonCode, note })` |
| `LocationList` | `locations`选项 `onedit(location)`; 包括非活动地点 |
| `LocationForm` | 选项 `location`, (中文(简体) ), `onsubmit({ id?, code, name, kind, placeId, active })` |

该条目还输出结构浏览器安全数据类型. 核准的主机装载量 记录并执行召回; 组件不导入数据库模型, 获取 结束点,或管理认证。 提交路线调整 `StockService.adjust`在服务器上附加信任的演员。 保存位置 通过窗体 `InventoryLocationCollection`; 停止使用 `active: false` 而不是删除历史。 两种表格都接受 `disabled`,防止重复 在等待召回时提交,并显示召回失败。 重排 政策编辑采用上述服务方法;库存数量和变动情况 在调整工作流程之外保留只读.

## 常见问题

### @happyvertical/smrt-inventory 是什么？

SMRT框架的多地储存跟踪——Sku、库存存放、库存级、库存移动、批量和序列跟踪以及库存模拟和批量服务

### 如何安装 @happyvertical/smrt-inventory？

在项目目录运行 npm install @happyvertical/smrt-inventory，或使用 pnpm add / yarn add / bun add。

### @happyvertical/smrt-inventory 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @happyvertical/smrt-inventory 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @happyvertical/smrt-inventory 可以商用吗？

@happyvertical/smrt-inventory 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @happyvertical/smrt-inventory 的下载量有多少？

根据 npm 官方下载统计，@happyvertical/smrt-inventory 在 2026/10/17 – 2026/11/15 这 30 天内被下载 14,753 次，日均约 492 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @happyvertical/smrt-inventory 还在维护吗？

最新版本 0\.62\.1 发布于 2026/11/17（今天）；至今共发布 365 个版本，其中过去 12 个月发布了 365 个；首次发布于 2026/06/23。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

