割引コードと自動割引:率・定額・送料無料、商品/カテゴリ指定、利用回数と初回限定の制限
インストール
genpm add @core/discounts含まれるもの
- src/lib/discounts/ にソースコード(6 ファイル)。 (21.5 KB)
- src/lib/discounts/AGENTS.md に AI ルール、加えて IDE 用のルールファイル。
- @core/cart, @core/catalog, @core/db, @core/money, @core/orders を自動で解決します。
README
このパッケージには README がありません。
これは AI が src/lib/discounts で作業するときに読む内容そのものです。それ以外はコンテキストに追加されません。
@core/discounts — rules for AI agents
Purpose
Discount codes and automatic discounts for @core/cart: percent, fixed amount or free shipping; optional scope by
product or category slugs, minimum order, start/end dates, total and per-customer usage limits, first-order-only and
combinability (non-combinable ones compete: the biggest wins). Registers the discounts (100) and free-shipping
(250) totals steps and records redemptions inside the transaction that creates/pays the order (onOrderPaidTx of
@core/orders), with the discount row locked. Limits count recorded redemptions plus open payments carrying the code
(pendingCodeUses of @core/cart, fed by @core/checkout). If a limit was exceeded anyway (the customer already paid),
the order is kept, the redemption recorded and a discount_over_limit event is added to the order timeline for review.
Tables: discounts, discount_redemptions.
Map
index.ts— public API:upsertDiscount,DiscountInput,discountsStep,freeShippingStep,recordRedemptions,discountsAdminResource.discounts.ts— validation, application and the redemption handler (registered on import).admin.ts— admin resource.
Integration
- Migrations as in
src/lib/db/AGENTS.md. Import this module at startup (it registers its steps and handler). - Cart page: a code field calling
PUT /api/cart/codes {codes: [code]}(@core/cart); showtotals.discountsand anyinvalid_codeissues. - Pass the customer email to
computeTotals(cart, { email })once known so per-customer and first-order limits apply. - Add
discountsAdminResourcetosrc/genpm/admin.ts(permissionsdiscounts:read|update). - Verify: create
TEN(10 %), apply it, the total drops and each line shows its share.
Conventions
- Codes are stored uppercase (
A–Z 0–9 _ -); values: percent 1–100, fixed in minor units. - Deleting a discount deactivates it (redemption history stays).
- Free-shipping adjustments carry their
code(amount 0), so they count towards usage limits. - Check the order timeline (
discount_over_limit) when a usage-limited campaign ends. - Prefer automatic discounts for store-wide sales; codes for campaigns.
Don't
- Don't show a "was" price or a percentage off that isn't real: in the EU a price reduction must refer to the lowest price of the previous 30 days (Omnibus Directive). Use @core/pricing's price history for compare-at prices.
- Don't apply discounts on the client or trust discount amounts sent by the browser.
- Don't create fake urgency (countdowns that reset, "only today" when it isn't).
# @core/discounts — rules for AI agents
## Purpose
Discount codes and automatic discounts for @core/cart: percent, fixed amount or free shipping; optional scope by
product or category slugs, minimum order, start/end dates, total and per-customer usage limits, first-order-only and
combinability (non-combinable ones compete: the biggest wins). Registers the `discounts` (100) and `free-shipping`
(250) totals steps and records redemptions inside the transaction that creates/pays the order (`onOrderPaidTx` of
@core/orders), with the discount row locked. Limits count recorded redemptions plus open payments carrying the code
(`pendingCodeUses` of @core/cart, fed by @core/checkout). If a limit was exceeded anyway (the customer already paid),
the order is kept, the redemption recorded and a `discount_over_limit` event is added to the order timeline for review.
Tables: `discounts`, `discount_redemptions`.
## Map
- `index.ts` — public API: `upsertDiscount`, `DiscountInput`, `discountsStep`, `freeShippingStep`, `recordRedemptions`, `discountsAdminResource`.
- `discounts.ts` — validation, application and the redemption handler (registered on import). `admin.ts` — admin resource.
## Integration
1. Migrations as in `src/lib/db/AGENTS.md`. Import this module at startup (it registers its steps and handler).
2. Cart page: a code field calling `PUT /api/cart/codes {codes: [code]}` (@core/cart); show `totals.discounts` and any `invalid_code` issues.
3. Pass the customer email to `computeTotals(cart, { email })` once known so per-customer and first-order limits apply.
4. Add `discountsAdminResource` to `src/genpm/admin.ts` (permissions `discounts:read|update`).
5. Verify: create `TEN` (10 %), apply it, the total drops and each line shows its share.
## Conventions
- Codes are stored uppercase (`A–Z 0–9 _ -`); values: percent 1–100, fixed in minor units.
- Deleting a discount deactivates it (redemption history stays).
- Free-shipping adjustments carry their `code` (amount 0), so they count towards usage limits.
- Check the order timeline (`discount_over_limit`) when a usage-limited campaign ends.
- Prefer automatic discounts for store-wide sales; codes for campaigns.
## Don't
- Don't show a "was" price or a percentage off that isn't real: in the EU a price reduction must refer to the lowest
price of the previous 30 days (Omnibus Directive). Use @core/pricing's price history for compare-at prices.
- Don't apply discounts on the client or trust discount amounts sent by the browser.
- Don't create fake urgency (countdowns that reset, "only today" when it isn't).
.genpmignore 適用後に組み込まれる正確なツリーです。固定先:
// Tablas de @core/discounts. 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 { primaryId, timestamps } from '../db/index.ts';
const ts = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });
export const discounts = pgTable('discounts', {
id: primaryId('dsc'),
/** Código en mayúsculas; null = descuento automático. */
code: text('code').unique(),
name: text('name').notNull(),
type: text('type', { enum: ['percent', 'fixed', 'free_shipping'] }).notNull(),
/** `percent`: 1–100. `fixed`: unidades menores. `free_shipping`: 0. */
value: integer('value').notNull().default(0),
minSubtotal: integer('min_subtotal'),
/** Solo estos productos/categorías (slugs); vacío = todo el carrito. */
productSlugs: jsonb('product_slugs').$type<string[]>().notNull().default([]),
categorySlugs: jsonb('category_slugs').$type<string[]>().notNull().default([]),
firstOrderOnly: boolean('first_order_only').notNull().default(false),
usageLimit: integer('usage_limit'),
perCustomerLimit: integer('per_customer_limit'),
/** Se puede sumar a otros descuentos combinables; si no, compite y gana el mayor. */
combinable: boolean('combinable').notNull().default(false),
startsAt: ts('starts_at'),
endsAt: ts('ends_at'),
active: boolean('active').notNull().default(true),
...timestamps,
});
export const discountRedemptions = pgTable(
'discount_redemptions',
{
id: primaryId('dre'),
discountId: text('discount_id')
.notNull()
.references(() => discounts.id, { onDelete: 'cascade' }),
orderId: text('order_id').notNull(),
email: text('email').notNull(),
userId: text('user_id'),
amount: integer('amount').notNull(),
...timestamps,
},
(t) => [uniqueIndex('discount_redemptions_order_idx').on(t.discountId, t.orderId), index('discount_redemptions_email_idx').on(t.discountId, t.email)],
);
export type Discount = typeof discounts.$inferSelect;
このパッケージは MCP サーバーを宣言していません。
| バージョン | コミット | 公開日 | スキャン |
|---|---|---|---|
| 1.0.1 | 6b23d34 | 3 時間前 | スキャン合格 |
- npm
- zod ^4.0.0
- 提案
- GenPM は npm コマンドを提案し、あなたが承認した場合にのみ実行します。
- 利用元(1)
- @core/kit-store ^1.0.0
- スキャン
- スキャン合格 · 指摘 0 件
- コミット
- v1.0.1 → 6b23d346ddd5be7a9154a7106859687008386baa · 取得後に検証済み
- スクリプト
- なし。GenPM はパッケージのコードを実行しません。
- ライセンス
- MIT
- 品質
- 100/100
- 認識されたライセンス達成
- AGENTS.md に目的の説明がある達成
- AGENTS.md に統合手順がある達成
- AGENTS.md に規約や禁止事項がある達成
- テストを含む達成
- セキュリティスキャンに合格達成
- 過去 6 か月以内に公開達成
- 認証済みの公開者達成
- 概要とキーワード達成
- 報告
- 問題を見つけましたか?