Precios desde el coste: reglas de margen por categoría/proveedor/producto, redondeo .99, alertas de margen e historial de 30 días UE
Instalar
genpm add @core/pricingQué obtienes
- Código en src/lib/pricing/, 6 archivos. (16,4 kB)
- Reglas de IA en src/lib/pricing/AGENTS.md, más archivos de reglas para tu IDE.
- Resuelve @core/catalog, @core/contracts, @core/db, @core/money por ti.
README
Este paquete no tiene README.
Esto es exactamente lo que lee tu IA cuando trabaja en src/lib/pricing. No se añade nada más a su contexto.
@core/pricing — rules for AI agents
Purpose
Turns costs into selling prices and keeps price changes honest. Rules (scope all / category / supplier / product,
cost range, markup in basis points, fixed add-on, charm rounding, minimum margin, priority) pick the most specific
match; repriceProduct applies them to variants with a cost. Every price change goes to price_history, which gives
the EU "prior price" (lowest of the 30 days before the current price) for any sale badge. Tables: price_rules, price_history.
Map
index.ts— public API:upsertPriceRule,priceFromCost,applyRule,repriceProduct,setVariantPrice,priorPrice,honestCompareAt,lowMarginVariants,priceRulesAdminResource.pricing.ts— logic.admin.ts— admin resource.schema.ts— tables.
Integration
- Migrations as in
src/lib/db/AGENTS.md. - Create rules in the admin (
priceRulesAdminResourceinsrc/genpm/admin.ts, permissionspricing:read|update), e.g.markupBps: 15000(+150 %), rounding.99. - Change prices only with
setVariantPrice(variantId, amount)(also from the admin and supplier syncs) so history is kept. - Product pages: show a crossed-out price only with
honestCompareAt(variantId); never with a typed "compare at". - Simulate before applying:
repriceProduct(productId, { apply: false })returns old/new price and margin per variant. - Verify: lower a price,
honestCompareAtreturns the lowest price of the previous 30 days.
Conventions
- Amounts in minor units; markup and margins in basis points (10000 = 100 %).
- Review
lowMarginVariants()after cost changes; items below their rule's minimum must not be sold silently.
Don't
- Don't update
priceAmountdirectly or invent "was" prices; that breaks the 30-day rule (Omnibus Directive). - Don't raise a price shortly before a sale to inflate the discount.
- Don't expose costs or margins in public pages or APIs.
# @core/pricing — rules for AI agents
## Purpose
Turns costs into selling prices and keeps price changes honest. Rules (scope all / category / supplier / product,
cost range, markup in basis points, fixed add-on, charm rounding, minimum margin, priority) pick the most specific
match; `repriceProduct` applies them to variants with a cost. Every price change goes to `price_history`, which gives
the EU "prior price" (lowest of the 30 days before the current price) for any sale badge. Tables: `price_rules`, `price_history`.
## Map
- `index.ts` — public API: `upsertPriceRule`, `priceFromCost`, `applyRule`, `repriceProduct`, `setVariantPrice`, `priorPrice`, `honestCompareAt`, `lowMarginVariants`, `priceRulesAdminResource`.
- `pricing.ts` — logic. `admin.ts` — admin resource. `schema.ts` — tables.
## Integration
1. Migrations as in `src/lib/db/AGENTS.md`.
2. Create rules in the admin (`priceRulesAdminResource` in `src/genpm/admin.ts`, permissions `pricing:read|update`), e.g. `markupBps: 15000` (+150 %), rounding `.99`.
3. Change prices only with `setVariantPrice(variantId, amount)` (also from the admin and supplier syncs) so history is kept.
4. Product pages: show a crossed-out price only with `honestCompareAt(variantId)`; never with a typed "compare at".
5. Simulate before applying: `repriceProduct(productId, { apply: false })` returns old/new price and margin per variant.
6. Verify: lower a price, `honestCompareAt` returns the lowest price of the previous 30 days.
## Conventions
- Amounts in minor units; markup and margins in basis points (10000 = 100 %).
- Review `lowMarginVariants()` after cost changes; items below their rule's minimum must not be sold silently.
## Don't
- Don't update `priceAmount` directly or invent "was" prices; that breaks the 30-day rule (Omnibus Directive).
- Don't raise a price shortly before a sale to inflate the discount.
- Don't expose costs or margins in public pages or APIs.
El árbol exacto que se inyectará, tras aplicar .genpmignore. Anclado a
// Tablas de @core/pricing. Las recoge drizzle-kit vía src/lib/db/drizzle.config.ts.
import { boolean, index, integer, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
import { productVariants } from '../catalog/index.ts';
import { primaryId, timestamps } from '../db/index.ts';
export const priceRules = pgTable('price_rules', {
id: primaryId('prr'),
name: text('name').notNull(),
/** A qué aplica: todo, una categoría, un proveedor o un producto (slug/id en `scopeValue`). */
scope: text('scope', { enum: ['all', 'category', 'supplier', 'product'] }).notNull().default('all'),
scopeValue: text('scope_value'),
/** Tramo de coste (unidades menores) en el que aplica. */
minCost: integer('min_cost'),
maxCost: integer('max_cost'),
/** Margen sobre el coste en puntos básicos: 15000 = +150 % (precio = coste × 2,5). */
markupBps: integer('markup_bps').notNull().default(0),
/** Importe fijo añadido tras el margen (p. ej. para cubrir comisiones). */
fixedAdd: integer('fixed_add').notNull().default(0),
rounding: text('rounding', { enum: ['none', '.99', '.95', '.90', '.00'] }).notNull().default('.99'),
/** Margen mínimo aceptable (bps sobre el precio): por debajo, alerta. */
minMarginBps: integer('min_margin_bps').notNull().default(1000),
priority: integer('priority').notNull().default(0),
active: boolean('active').notNull().default(true),
...timestamps,
});
/** Historial de precios por variante (necesario para anunciar rebajas en la UE: precio más bajo de 30 días). */
export const priceHistory = pgTable(
'price_history',
{
id: primaryId('prh'),
variantId: text('variant_id')
.notNull()
.references(() => productVariants.id, { onDelete: 'cascade' }),
amount: integer('amount').notNull(),
currency: text('currency').notNull(),
validFrom: timestamp('valid_from', { withTimezone: true, mode: 'date' }).notNull(),
validTo: timestamp('valid_to', { withTimezone: true, mode: 'date' }),
},
(t) => [index('price_history_variant_idx').on(t.variantId, t.validFrom)],
);
export type PriceRule = typeof priceRules.$inferSelect;
Este paquete no declara servidores MCP.
| Versión | Commit | Publicado | Escaneo |
|---|---|---|---|
| 1.0.0 | 6aa4077 | hace 3 horas | escaneo superado |
- npm
- zod ^4.0.0
- propuesta
- GenPM propone el comando npm y solo lo ejecuta si dices que sí.
- Usado por (2)
- @core/kit-dropshipping ^1.0.0@core/suppliers ^1.0.0
- escaneo
- escaneo superado · 0 hallazgos
- commit
- v1.0.0 → 6aa40774c5407480451f9b9f74d4e4e0577c06df · verificado tras la descarga
- scripts
- Ninguno. GenPM nunca ejecuta código del paquete.
- licencia
- MIT
- Calidad
- 100/100
- Licencia reconocidacumplido
- AGENTS.md explica su propósitocumplido
- AGENTS.md tiene pasos de integracióncumplido
- AGENTS.md lista convenciones o prohibicionescumplido
- Incluye testscumplido
- Escaneo de seguridad superadocumplido
- Publicado en los últimos 6 mesescumplido
- Publicador verificadocumplido
- Resumen y palabras clavecumplido
- reporte
- ¿Ves algo raro?