ドロップシッピング仕入先:ルール価格での商品取込、原価・在庫同期、支払済み注文の転送、追跡、例外処理
インストール
genpm add @core/suppliers含まれるもの
- src/lib/suppliers/ にソースコード(8 ファイル)。 (48 KB)
- src/lib/suppliers/AGENTS.md に AI ルール、加えて IDE 用のルールファイル。
- .env.example に追加される環境変数: SUPPLIER_COST_ALERT_PCT。
- @core/catalog, @core/contracts, @core/db, @core/email, @core/jobs, @core/media, @core/money, @core/orders, @core/pricing, @core/rich-text を自動で解決します。
README
このパッケージには README がありません。
これは AI が src/lib/suppliers で作業するときに読む内容そのものです。それ以外はコンテキストに追加されません。
@core/suppliers — rules for AI agents
Purpose
Dropshipping operations behind a SupplierAdapter contract: import supplier products into @core/catalog as drafts
(price from @core/pricing rules, images copied to @core/media, plain-text description), map variants to supplier
SKUs with cost and delivery days, sync cost and stock (reprice; pause products that would sell at a loss), turn paid
orders into supplier orders (approval by default, or automatic), forward them with retries, record tracking on the
order and keep an exceptions queue. Ships the manual adapter (CSV import, orders emailed to the supplier).
Map
index.ts— public API:upsertSupplier,parseSupplierCsv,importProduct,syncSupplier,setFxRatesProvider,approveSupplierOrder,forwardSupplierOrder,recordSupplierShipment,deliveryEstimate,registerAdapter,suppliersAdminResources.suppliers.ts— flows and jobs (suppliers.forward,suppliers.sync,suppliers.tracking).adapter.ts— contract.adapters/manual.ts— manual adapter and CSV parser.admin.ts— suppliers, supplier orders, exceptions.
Integration
- Install @core/pricing and create at least one price rule. Migrations as in
src/lib/db/AGENTS.md; the @core/jobs cron must run. - Import this module at startup (registers the manual adapter and the
paidorder handler). - Create a supplier in the admin: adapter
manual,config.orderEmail, currency. API adapters read credentials from env, never fromconfig. - Import:
importProduct(supplierId, parseSupplierCsv(csv, currency)[0], { slug, categories })→ review the draft, then publish. - Schedule
syncAllJob(e.g. every 6 h) andpollTrackingJob(every 12 h) with @core/jobsschedule. Suppliers in another currency need exchange rates for the scheduled sync:setFxRatesProvider(async () => ({ base, rates }))at startup, or envSUPPLIER_FX_RATES='{"base":"EUR","rates":{"USD":1.08}}'. Without them, products whose cost changed are paused with anfx_rates_missingexception. A failing supplier gets async_failedexception; the rest still sync. - Product pages: show
deliveryEstimate(variantId)before purchase. - Add
...suppliersAdminResources()tosrc/genpm/admin.ts; check open exceptions daily.
Conventions
- New adapters implement
SupplierAdapterin their own file and callregisterAdapter; list their image hosts. - Supplier orders start in
pending_approvalunless the supplier hasautoForward; failures retry, then open an exception. - Forwarding is at most once: the row is claimed (
queued → sending) beforeplaceOrder. A timeout or a row found insendingmeans the outcome is unknown: it goes tofailedwith aforward_failedexception and is never re-sent automatically — check with the supplier before approving it again. Only non-refunded units are forwarded. - Adapters:
placeOrderthrows only when the order was NOT created, usesorder.referenceas idempotency key when the API allows it, and passesopts.signaltofetch. - Costs may be in another currency: pass exchange
rates(and store them) when importing or syncing.
Don't
- Don't scrape supplier websites or bypass their terms; use official APIs or the manual adapter.
- Don't forward unpaid, cancelled or refunded orders, and don't sell below cost (sync pauses those products).
- Don't hotlink supplier images or copy descriptions claiming features/certifications you can't verify.
# @core/suppliers — rules for AI agents
## Purpose
Dropshipping operations behind a `SupplierAdapter` contract: import supplier products into @core/catalog as drafts
(price from @core/pricing rules, images copied to @core/media, plain-text description), map variants to supplier
SKUs with cost and delivery days, sync cost and stock (reprice; pause products that would sell at a loss), turn paid
orders into supplier orders (approval by default, or automatic), forward them with retries, record tracking on the
order and keep an exceptions queue. Ships the `manual` adapter (CSV import, orders emailed to the supplier).
## Map
- `index.ts` — public API: `upsertSupplier`, `parseSupplierCsv`, `importProduct`, `syncSupplier`, `setFxRatesProvider`, `approveSupplierOrder`, `forwardSupplierOrder`, `recordSupplierShipment`, `deliveryEstimate`, `registerAdapter`, `suppliersAdminResources`.
- `suppliers.ts` — flows and jobs (`suppliers.forward`, `suppliers.sync`, `suppliers.tracking`). `adapter.ts` — contract.
- `adapters/manual.ts` — manual adapter and CSV parser. `admin.ts` — suppliers, supplier orders, exceptions.
## Integration
1. Install @core/pricing and create at least one price rule. Migrations as in `src/lib/db/AGENTS.md`; the @core/jobs cron must run.
2. Import this module at startup (registers the manual adapter and the `paid` order handler).
3. Create a supplier in the admin: adapter `manual`, `config.orderEmail`, currency. API adapters read credentials from env, never from `config`.
4. Import: `importProduct(supplierId, parseSupplierCsv(csv, currency)[0], { slug, categories })` → review the draft, then publish.
5. Schedule `syncAllJob` (e.g. every 6 h) and `pollTrackingJob` (every 12 h) with @core/jobs `schedule`. Suppliers
in another currency need exchange rates for the scheduled sync: `setFxRatesProvider(async () => ({ base, rates }))`
at startup, or env `SUPPLIER_FX_RATES='{"base":"EUR","rates":{"USD":1.08}}'`. Without them, products whose cost
changed are paused with an `fx_rates_missing` exception. A failing supplier gets a `sync_failed` exception; the rest still sync.
6. Product pages: show `deliveryEstimate(variantId)` before purchase.
7. Add `...suppliersAdminResources()` to `src/genpm/admin.ts`; check open exceptions daily.
## Conventions
- New adapters implement `SupplierAdapter` in their own file and call `registerAdapter`; list their image hosts.
- Supplier orders start in `pending_approval` unless the supplier has `autoForward`; failures retry, then open an exception.
- Forwarding is at most once: the row is claimed (`queued → sending`) before `placeOrder`. A timeout or a row found
in `sending` means the outcome is unknown: it goes to `failed` with a `forward_failed` exception and is never
re-sent automatically — check with the supplier before approving it again. Only non-refunded units are forwarded.
- Adapters: `placeOrder` throws only when the order was NOT created, uses `order.reference` as idempotency key when
the API allows it, and passes `opts.signal` to `fetch`.
- Costs may be in another currency: pass exchange `rates` (and store them) when importing or syncing.
## Don't
- Don't scrape supplier websites or bypass their terms; use official APIs or the manual adapter.
- Don't forward unpaid, cancelled or refunded orders, and don't sell below cost (sync pauses those products).
- Don't hotlink supplier images or copy descriptions claiming features/certifications you can't verify.
.genpmignore 適用後に組み込まれる正確なツリーです。固定先:
// Tablas de @core/suppliers. Las recoge drizzle-kit vía src/lib/db/drizzle.config.ts.
import { boolean, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
import { productVariants } from '../catalog/index.ts';
import { primaryId, timestamps } from '../db/index.ts';
export const suppliers = pgTable('suppliers', {
id: primaryId('sup'),
name: text('name').notNull(),
/** Adaptador registrado: `manual`, `cj`, `aliexpress`… */
adapter: text('adapter').notNull(),
/** Configuración sin secretos (las credenciales van en variables de entorno). */
config: jsonb('config').$type<Record<string, string>>().notNull().default({}),
currency: text('currency').notNull(),
status: text('status', { enum: ['active', 'paused'] }).notNull().default('active'),
/** Reenviar pedidos pagados sin aprobación manual. */
autoForward: boolean('auto_forward').notNull().default(false),
lastSyncAt: timestamp('last_sync_at', { withTimezone: true, mode: 'date' }),
...timestamps,
});
/** Qué variante del catálogo corresponde a qué artículo del proveedor, con su coste y plazo. */
export const supplierProducts = pgTable(
'supplier_products',
{
variantId: text('variant_id')
.primaryKey()
.references(() => productVariants.id, { onDelete: 'cascade' }),
supplierId: text('supplier_id')
.notNull()
.references(() => suppliers.id, { onDelete: 'cascade' }),
externalProductId: text('external_product_id').notNull(),
externalVariantId: text('external_variant_id').notNull(),
cost: integer('cost').notNull(),
currency: text('currency').notNull(),
shippingDaysMin: integer('shipping_days_min'),
shippingDaysMax: integer('shipping_days_max'),
lastSyncAt: timestamp('last_sync_at', { withTimezone: true, mode: 'date' }),
...timestamps,
},
(t) => [index('supplier_products_supplier_idx').on(t.supplierId, t.externalVariantId)],
);
export const supplierOrders = pgTable(
'supplier_orders',
{
id: primaryId('spo'),
orderId: text('order_id').notNull(),
supplierId: text('supplier_id')
.notNull()
.references(() => suppliers.id),
status: text('status', { enum: ['pending_approval', 'queued', 'sending', 'sent', 'shipped', 'failed', 'cancelled'] }).notNull(),
lines: jsonb('lines').$type<Array<{ orderLineId: string; externalVariantId: string; quantity: number }>>().notNull(),
externalRef: text('external_ref'),
error: text('error'),
attempts: integer('attempts').notNull().default(0),
...timestamps,
},
(t) => [uniqueIndex('supplier_orders_order_idx').on(t.orderId, t.supplierId), index('supplier_orders_status_idx').on(t.status)],
);
export const supplierExceptions = pgTable(
'supplier_exceptions',
{
id: primaryId('sex'),
type: text('type', { enum: ['out_of_stock', 'cost_increase', 'negative_margin', 'forward_failed', 'tracking_stalled', 'sync_failed', 'fx_rates_missing'] }).notNull(),
supplierId: text('supplier_id'),
variantId: text('variant_id'),
orderId: text('order_id'),
message: text('message').notNull(),
data: jsonb('data').$type<Record<string, unknown>>().notNull().default({}),
status: text('status', { enum: ['open', 'resolved'] }).notNull().default('open'),
...timestamps,
},
(t) => [index('supplier_exceptions_status_idx').on(t.status, t.createdAt)],
);
export type Supplier = typeof suppliers.$inferSelect;
export type SupplierOrder = typeof supplierOrders.$inferSelect;
export type SupplierException = typeof supplierExceptions.$inferSelect;
このパッケージは MCP サーバーを宣言していません。
| バージョン | コミット | 公開日 | スキャン |
|---|---|---|---|
| 1.1.0 | 4e946f2 | 3 時間前 | スキャン合格 |
- genpm
- @core/catalog ^1.0.0@core/contracts ^1.0.0@core/db ^1.0.0@core/email ^1.0.1@core/jobs ^1.0.0@core/media ^1.0.0@core/money ^1.0.0@core/orders ^1.0.0@core/pricing ^1.0.0@core/rich-text ^1.0.0
- npm
- zod ^4.0.0
- 提案
- GenPM は npm コマンドを提案し、あなたが承認した場合にのみ実行します。
- スキャン
- スキャン合格 · 指摘 0 件
- コミット
- v1.1.0 → 4e946f226d5dd3af9dbeb2209701da45a13e8769 · 取得後に検証済み
- スクリプト
- なし。GenPM はパッケージのコードを実行しません。
- ライセンス
- MIT
- 品質
- 100/100
- 認識されたライセンス達成
- AGENTS.md に目的の説明がある達成
- AGENTS.md に統合手順がある達成
- AGENTS.md に規約や禁止事項がある達成
- テストを含む達成
- セキュリティスキャンに合格達成
- 過去 6 か月以内に公開達成
- 認証済みの公開者達成
- 概要とキーワード達成
- 報告
- 問題を見つけましたか?