@stacksjs/orm 0.75.618 → 0.75.621
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/models/commerce/Cart.ts +14 -0
- package/dist/models/commerce/Discount.ts +255 -0
- package/dist/models/commerce/PostPurchaseOffer.ts +175 -0
- package/dist/models/commerce/PostPurchaseOfferResponse.ts +145 -0
- package/package.json +23 -23
package/dist/index.d.ts
CHANGED
|
@@ -117,6 +117,9 @@ export declare const Label: ReturnType<typeof lazyModel<typeof import('./models/
|
|
|
117
117
|
export declare const LicenseActivation: ReturnType<typeof lazyModel<typeof import('./models/commerce/LicenseActivation').default>>;
|
|
118
118
|
export declare const LicenseKey: ReturnType<typeof lazyModel<typeof import('./models/commerce/LicenseKey').default>>;
|
|
119
119
|
export declare const LicenseSeat: ReturnType<typeof lazyModel<typeof import('./models/commerce/LicenseSeat').default>>;
|
|
120
|
+
export declare const Discount: ReturnType<typeof lazyModel<typeof import('./models/commerce/Discount').default>>;
|
|
121
|
+
export declare const PostPurchaseOffer: ReturnType<typeof lazyModel<typeof import('./models/commerce/PostPurchaseOffer').default>>;
|
|
122
|
+
export declare const PostPurchaseOfferResponse: ReturnType<typeof lazyModel<typeof import('./models/commerce/PostPurchaseOfferResponse').default>>;
|
|
120
123
|
export declare const Log: ReturnType<typeof lazyModel<typeof import('./models/Log').default>>;
|
|
121
124
|
export declare const LoyaltyPoint: ReturnType<typeof lazyModel<typeof import('./models/commerce/LoyaltyPoint').default>>;
|
|
122
125
|
export declare const LoyaltyReward: ReturnType<typeof lazyModel<typeof import('./models/commerce/LoyaltyReward').default>>;
|
|
@@ -215,8 +218,6 @@ export declare interface UserModel {
|
|
|
215
218
|
updated_at: string | null
|
|
216
219
|
stripe_id?: string | null
|
|
217
220
|
two_factor_enabled?: boolean
|
|
218
|
-
hasRole: (role: string) => boolean | Promise<boolean>
|
|
219
|
-
assignRole: (role: string) => unknown | Promise<unknown>
|
|
220
221
|
update: (data: Record<string, unknown>) => Promise<UserModel>
|
|
221
222
|
[key: string]: unknown
|
|
222
223
|
}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@stacksjs/validation/runtime";import{isCompiledBinary}from"@stacksjs/path";export*from"./utils/prunable";export{collectEncryptedAttributes,decryptValue,decryptValueInPlace,encryptValue,isEncrypted}from"./utils/encrypted";export{setAuditUser,createAuditMethods}from"./traits/audit";export{createCommentableMethods}from"./traits/commentable";export{createTaggableMethods}from"./traits/taggable";export{createCategorizableMethods}from"./traits/categorizable";export{createLikeableMethods}from"./traits/likeable";export{BILLABLE_INSTANCE_METHODS,isBillable,SubscriptionNotOwnedError}from"./traits/billable";export{filterFillable,getWritableFields,isUniqueViolation,mapWriteError,toSnakeCaseKeys}from"./auto-crud";export{customerOwnership,parentOwnership,selfOwnership,siteOwnership,teamMembershipOwnership}from"./ownership";export*from"./batch-loader";export*from"./db";export*from"./subquery";export*from"./transaction";export*from"./locked-row";export*from"./row-token";export*from"./gdpr";export*from"./model-types";export*from"./types";export*from"@stacksjs/model-meta";export*from"./define-model";export*from"./extend-model";export{buildDatabaseSchema,renderDatabaseTypeFile}from"./generate-database-schema";export{isCursorPaginator,isPaginator,isSimplePaginator,toCursorPaginator,toPaginator,toSimplePaginator}from"@stacksjs/pagination";export{enrichPaginatorUrls,parseCursor,resolveCursorArgs,resolvePageArgs}from"./paginator-request";async function importDefault(modulePath){for(let attempt=0;;attempt++){const mod=await import(modulePath);try{return mod.default}catch(err){if(attempt<5&&err instanceof ReferenceError&&/before initialization/.test(err.message)){await new Promise((resolve)=>setTimeout(resolve,0));continue}throw err}}}let announcedCompiledSkip=false;async function loadUserlandModel(modelName,subdirs=[""]){if(isCompiledBinary()){if(!announcedCompiledSkip){announcedCompiledSkip=true;console.debug("[orm] running from a compiled binary, so framework default models are not probed on disk; models this app uses are bundled.")}return null}const{path}=await import("@stacksjs/path");const userPath=path.userModelsPath(`${modelName}.ts`);try{if(await Bun.file(userPath).exists()){return await importDefault(userPath)}}catch(err){console.error(`[orm] Failed to import userland model ${modelName} from ${userPath} - falling back to framework default. Reason:`,err)}for(const sub of subdirs){const prefix=sub?`${sub}/`:"";const defaultPath=path.frameworkPath(`defaults/app/Models/${prefix}${modelName}.ts`);try{if(await Bun.file(defaultPath).exists()){return await importDefault(defaultPath)}}catch(err){console.error(`[orm] Failed to import framework default model ${modelName} from ${defaultPath} - trying next subdir. Reason:`,err)}}return null}const _loaded={};let _modelsSettled=false;const QUERY_ENTRYPOINTS=new Set(["where","orWhere","whereIn","whereNotIn","whereNull","whereNotNull","whereLike","whereBetween","whereNotBetween","orderBy","orderByDesc","latest","oldest","limit","take","skip","select","find","findOrFail","findMany","first","firstOrFail","all","get","paginate","count","sum","avg","min","max","create","createMany","firstOrCreate","updateOrCreate","save","update","updateMany","delete","destroy","remove","truncate"]);function featureGateFor(name){return FRAMEWORK_MODEL_MANIFEST.find(([model])=>model===name)?.[2]}export function frameworkModelFeature(name){return FRAMEWORK_MODEL_MANIFEST.find(([model])=>model===name)?.[2]}export class ModelUnavailableError extends Error{model;feature;name="ModelUnavailableError";constructor(model,feature){super(`Model "${model}" is not available in this process. ${feature?`The '${feature}' feature is off, so this model was never loaded - set \`enabled: true\` in config/${feature}.ts to use it.`:`No model file for it was found under app/Models or the framework defaults.`}`);this.model=model;this.feature=feature}}function unavailableModel(name){return new ModelUnavailableError(name,featureGateFor(name))}let _readyResolve=()=>{};export const ormReady=new Promise((resolve)=>{_readyResolve=resolve});function lazyModel(name){return new Proxy(function _modelStub(){},{get(_target,prop){if(prop==="then")return;const m=_loaded[name];if(m==null){if(_modelsSettled&&typeof prop==="string"&&QUERY_ENTRYPOINTS.has(prop))throw unavailableModel(name);return}const value=m[prop];return typeof value==="function"?value.bind(m):value},set(_target,prop,value){const m=_loaded[name];if(m==null)return false;m[prop]=value;return true},has(_target,prop){const m=_loaded[name];return m==null?false:(prop in m)},apply(_target,thisArg,args){const m=_loaded[name];if(m==null||typeof m!=="function")return;return m.apply(thisArg,args)}})}export const User=lazyModel("User");export const Job=lazyModel("Job");export const QueueWorker=lazyModel("QueueWorker");export const FailedJob=lazyModel("FailedJob");const FRAMEWORK_MODEL_MANIFEST=[["QueueWorker",[""],"queue"],["Referral",[""],"auth"],["ReferralCode",[""],"auth"],["Team",[""],"auth"],["TeamInvitation",[""],"auth"],["TeamMember",[""],"auth"],["SocialAccount",[""],"auth"],["Subscriber",[""],"auth"],["SubscriberEmail",[""],"auth"],["Subscription",[""],"auth"],["Categorizable",["Content"],"cms"],["Post",["Content"],"cms"],["Page",["Content"],"cms"],["PageRevision",["Content"],"cms"],["Redirect",["Content"],"cms"],["Menu",["Content"],"cms"],["MenuItem",["Content"],"cms"],["Author",["Content"],"cms"],["Comment",[""],"cms"],["Tag",[""],"cms"],["Site",[""],"auth"],["SiteDomain",[""],"auth"],["MagicLinkToken",[""],"auth"],["SmsOptOut",[""],"auth"],["GdprRequest",[""],"auth"],["Form",["Forms"],"forms"],["FormField",["Forms"],"forms"],["FormSubmission",["Forms"],"forms"],["Activity",[""],"dashboard"],["Board",[""],"dashboard"],["BoardColumn",[""],"dashboard"],["Card",[""],"dashboard"],["CardAttachment",[""],"dashboard"],["CardComment",[""],"dashboard"],["Deployment",[""],"dashboard"],["FeedbackToken",[""],"dashboard"],["Label",[""],"dashboard"],["Release",[""],"dashboard"],["Notification",[""],"dashboard"],["NotificationDelivery",[""],"dashboard"],["PersonalAccessToken",[""],"dashboard"],["MailPreference",[""],"dashboard"],["Log",[""],"dashboard"],["Request",[""],"dashboard"],["AnalyticsEvent",[""],"dashboard"],["QueryLog",[""],"dashboard"],["StorageItem",[""],"dashboard"],["StorageItemTask",[""],"dashboard"],["Error",[""],"monitoring"],["Websocket",["realtime"],"realtime"],["Campaign",[""],"marketing"],["CampaignSend",[""],"marketing"],["EmailList",[""],"marketing"],["EmailListSubscriber",[""],"marketing"],["EmailIdempotency",[""],"marketing"],["EmailSuppression",[""],"marketing"],["EmailWebhookEvent",[""],"marketing"],["SocialPost",[""],"marketing"],["Automation",[""],"marketing"],["AutomationRun",[""],"marketing"],["CampaignVariant",[""],"marketing"],["CommunicationSuppression",[""],"marketing"],["ConsentEvent",[""],"marketing"],["SenderDomain",[""],"marketing"],["UsageEvent",[""],"marketing"],["PaymentMethod",[""],"commerce"],["PaymentProduct",[""],"commerce"],["PaymentTransaction",[""],"commerce"],["Order",["commerce"],"commerce"],["OrderIdempotency",["commerce"],"commerce"],["OrderItem",["commerce"],"commerce"],["Cart",["commerce"],"commerce"],["CartItem",["commerce"],"commerce"],["Customer",["commerce"],"commerce"],["Product",["commerce"],"commerce"],["ProductVariant",["commerce"],"commerce"],["ProductUnit",["commerce"],"commerce"],["Manufacturer",["commerce"],"commerce"],["Category",["commerce"],"commerce"],["Coupon",["commerce"],"commerce"],["GiftCard",["commerce"],"commerce"],["LicenseKey",["commerce"],"commerce"],["LicenseActivation",["commerce"],"commerce"],["LicenseSeat",["commerce"],"commerce"],["Review",["commerce"],"commerce"],["Receipt",["commerce"],"commerce"],["PrintDevice",["commerce"],"commerce"],["ShippingMethod",["commerce"],"commerce"],["ShippingRate",["commerce"],"commerce"],["ShippingZone",["commerce"],"commerce"],["DeliveryRoute",["commerce"],"commerce"],["DeliveryStop",["commerce"],"commerce"],["DigitalDelivery",["commerce"],"commerce"],["Courier",["commerce"],"commerce"],["CourierPing",["commerce"],"commerce"],["TaxRate",["commerce"],"commerce"],["WaitlistProduct",["commerce"],"commerce"],["WaitlistRestaurant",["commerce"],"commerce"],["Auction",["commerce"],"commerce"],["AuctionItem",["commerce"],"commerce"],["Bid",["commerce"],"commerce"],["Pledge",["commerce"],"commerce"],["LoyaltyPoint",["commerce"],"commerce"],["LoyaltyReward",["commerce"],"commerce"],["Payment",["commerce"],"commerce"],["PaymentWebhookEvent",["commerce"],"commerce"],["Transaction",["commerce"],"commerce"]];queueMicrotask(async()=>{try{const{feature}=await import("@stacksjs/config");const userModel=await loadUserlandModel("User");if(userModel)_loaded.User=userModel;if(feature("queue")){const job=await loadUserlandModel("Job");if(job)_loaded.Job=job;const failedJob=await loadUserlandModel("FailedJob");if(failedJob)_loaded.FailedJob=failedJob}for(const[name,subdirs,featureFlag]of FRAMEWORK_MODEL_MANIFEST){if(!feature(featureFlag))continue;const M=await loadUserlandModel(name,subdirs);if(M)_loaded[name]=M}}catch(err){console.error("[orm] deferred model load failed:",err)}finally{_modelsSettled=true;_readyResolve()}});export const Activity=lazyModel("Activity");export const AnalyticsEvent=lazyModel("AnalyticsEvent");export const Automation=lazyModel("Automation");export const AutomationRun=lazyModel("AutomationRun");export const Auction=lazyModel("Auction");export const CampaignVariant=lazyModel("CampaignVariant");export const CommunicationSuppression=lazyModel("CommunicationSuppression");export const ConsentEvent=lazyModel("ConsentEvent");export const SenderDomain=lazyModel("SenderDomain");export const UsageEvent=lazyModel("UsageEvent");export const AuctionItem=lazyModel("AuctionItem");export const Author=lazyModel("Author");export const Bid=lazyModel("Bid");export const Board=lazyModel("Board");export const BoardColumn=lazyModel("BoardColumn");export const Campaign=lazyModel("Campaign");export const Card=lazyModel("Card");export const CardAttachment=lazyModel("CardAttachment");export const CardComment=lazyModel("CardComment");export const Cart=lazyModel("Cart");export const CartItem=lazyModel("CartItem");export const Category=lazyModel("Category");export const Comment=lazyModel("Comment");export const Coupon=lazyModel("Coupon");export const Customer=lazyModel("Customer");export const DeliveryRoute=lazyModel("DeliveryRoute");export const DeliveryStop=lazyModel("DeliveryStop");export const Deployment=lazyModel("Deployment");export const FeedbackToken=lazyModel("FeedbackToken");export const DigitalDelivery=lazyModel("DigitalDelivery");export const Courier=lazyModel("Courier");export const CourierPing=lazyModel("CourierPing");export const CampaignSend=lazyModel("CampaignSend");export const EmailList=lazyModel("EmailList");export const EmailListSubscriber=lazyModel("EmailListSubscriber");export const Form=lazyModel("Form");export const FormField=lazyModel("FormField");export const FormSubmission=lazyModel("FormSubmission");export const MagicLinkToken=lazyModel("MagicLinkToken");export const Menu=lazyModel("Menu");export const MenuItem=lazyModel("MenuItem");export const PageRevision=lazyModel("PageRevision");export const Pledge=lazyModel("Pledge");export const Redirect=lazyModel("Redirect");export const Site=lazyModel("Site");export const SiteDomain=lazyModel("SiteDomain");export const SmsOptOut=lazyModel("SmsOptOut");export const GdprRequest=lazyModel("GdprRequest");export const StorageItem=lazyModel("StorageItem");export const StorageItemTask=lazyModel("StorageItemTask");export const EmailIdempotency=lazyModel("EmailIdempotency");export const EmailSuppression=lazyModel("EmailSuppression");export const EmailWebhookEvent=lazyModel("EmailWebhookEvent");export const ErrorModel=lazyModel("Error");export const GiftCard=lazyModel("GiftCard");export const Label=lazyModel("Label");export const LicenseActivation=lazyModel("LicenseActivation");export const LicenseKey=lazyModel("LicenseKey");export const LicenseSeat=lazyModel("LicenseSeat");export const Log=lazyModel("Log");export const LoyaltyPoint=lazyModel("LoyaltyPoint");export const LoyaltyReward=lazyModel("LoyaltyReward");export const MailPreference=lazyModel("MailPreference");export const Manufacturer=lazyModel("Manufacturer");export const Notification=lazyModel("Notification");export const NotificationDelivery=lazyModel("NotificationDelivery");export const Order=lazyModel("Order");export const OrderIdempotency=lazyModel("OrderIdempotency");export const PersonalAccessToken=lazyModel("PersonalAccessToken");export const OrderItem=lazyModel("OrderItem");export const Page=lazyModel("Page");export const Payment=lazyModel("Payment");export const PaymentWebhookEvent=lazyModel("PaymentWebhookEvent");export const PaymentMethod=lazyModel("PaymentMethod");export const PaymentProduct=lazyModel("PaymentProduct");export const PaymentTransaction=lazyModel("PaymentTransaction");export const Post=lazyModel("Post");export const Categorizable=lazyModel("Categorizable");export const PrintDevice=lazyModel("PrintDevice");export const Product=lazyModel("Product");export const ProductUnit=lazyModel("ProductUnit");export const ProductVariant=lazyModel("ProductVariant");export const QueryLog=lazyModel("QueryLog");export const Receipt=lazyModel("Receipt");export const Referral=lazyModel("Referral");export const ReferralCode=lazyModel("ReferralCode");export const Release=lazyModel("Release");export const Request=lazyModel("Request");export const Review=lazyModel("Review");export const ShippingMethod=lazyModel("ShippingMethod");export const ShippingRate=lazyModel("ShippingRate");export const ShippingZone=lazyModel("ShippingZone");export const SocialPost=lazyModel("SocialPost");export const SocialAccount=lazyModel("SocialAccount");export const Subscriber=lazyModel("Subscriber");export const SubscriberEmail=lazyModel("SubscriberEmail");export const Subscription=lazyModel("Subscription");export const Tag=lazyModel("Tag");export const TaxRate=lazyModel("TaxRate");export const Team=lazyModel("Team");export const TeamInvitation=lazyModel("TeamInvitation");export const TeamMember=lazyModel("TeamMember");export const Transaction=lazyModel("Transaction");export const WaitlistProduct=lazyModel("WaitlistProduct");export const WaitlistRestaurant=lazyModel("WaitlistRestaurant");export const Websocket=lazyModel("Websocket");const _allExports={User,Job,FailedJob,QueueWorker,Activity,AnalyticsEvent,Automation,AutomationRun,Auction,AuctionItem,Author,Bid,Board,BoardColumn,Campaign,CampaignSend,CampaignVariant,Card,CardComment,Cart,CartItem,Categorizable,Category,Comment,Coupon,Customer,CommunicationSuppression,ConsentEvent,DeliveryRoute,DeliveryStop,Deployment,DigitalDelivery,Courier,CourierPing,EmailList,EmailListSubscriber,EmailIdempotency,EmailSuppression,EmailWebhookEvent,ErrorModel,Form,FormField,FormSubmission,GdprRequest,GiftCard,Label,LicenseActivation,LicenseKey,LicenseSeat,Log,LoyaltyPoint,LoyaltyReward,MailPreference,Manufacturer,Notification,MagicLinkToken,Menu,MenuItem,NotificationDelivery,Order,OrderIdempotency,OrderItem,Page,PageRevision,Payment,PaymentMethod,PaymentProduct,PaymentTransaction,PaymentWebhookEvent,Pledge,Post,PrintDevice,Product,ProductUnit,ProductVariant,QueryLog,Receipt,Release,Request,Review,ShippingMethod,Redirect,SenderDomain,ShippingRate,ShippingZone,Site,SiteDomain,SmsOptOut,SocialAccount,SocialPost,Subscriber,SubscriberEmail,Subscription,Tag,TaxRate,Team,TeamInvitation,TeamMember,Transaction,UsageEvent,WaitlistProduct,WaitlistRestaurant,Websocket};const g=globalThis;for(const[name,M]of Object.entries(_allExports)){if(M&&g[name]===undefined)g[name]=M}export const modelGlobalNames=Object.keys(_allExports);async function _safeAll(M){if(!M)return[];try{if(typeof M.all==="function"){const rows=await M.all();return Array.isArray(rows)?rows:[]}if(typeof M.get==="function"){const rows=await M.get();return Array.isArray(rows)?rows:[]}}catch{}return[]}function _safeGet(row,key,fallback=""){if(!row)return fallback;try{if(typeof row.get==="function"){const v=row.get(key);if(v!==undefined&&v!==null)return v}}catch{}const direct=row?.[key];return direct!==undefined&&direct!==null?direct:fallback}if(g.safeAll===undefined)g.safeAll=_safeAll;if(g.safeGet===undefined)g.safeGet=_safeGet;export*from"./messaging";
|
|
1
|
+
import"@stacksjs/validation/runtime";import{isCompiledBinary}from"@stacksjs/path";export*from"./utils/prunable";export{collectEncryptedAttributes,decryptValue,decryptValueInPlace,encryptValue,isEncrypted}from"./utils/encrypted";export{setAuditUser,createAuditMethods}from"./traits/audit";export{createCommentableMethods}from"./traits/commentable";export{createTaggableMethods}from"./traits/taggable";export{createCategorizableMethods}from"./traits/categorizable";export{createLikeableMethods}from"./traits/likeable";export{BILLABLE_INSTANCE_METHODS,isBillable,SubscriptionNotOwnedError}from"./traits/billable";export{filterFillable,getWritableFields,isUniqueViolation,mapWriteError,toSnakeCaseKeys}from"./auto-crud";export{customerOwnership,parentOwnership,selfOwnership,siteOwnership,teamMembershipOwnership}from"./ownership";export*from"./batch-loader";export*from"./db";export*from"./subquery";export*from"./transaction";export*from"./locked-row";export*from"./row-token";export*from"./gdpr";export*from"./model-types";export*from"./types";export*from"@stacksjs/model-meta";export*from"./define-model";export*from"./extend-model";export{buildDatabaseSchema,renderDatabaseTypeFile}from"./generate-database-schema";export{isCursorPaginator,isPaginator,isSimplePaginator,toCursorPaginator,toPaginator,toSimplePaginator}from"@stacksjs/pagination";export{enrichPaginatorUrls,parseCursor,resolveCursorArgs,resolvePageArgs}from"./paginator-request";async function importDefault(modulePath){for(let attempt=0;;attempt++){const mod=await import(modulePath);try{return mod.default}catch(err){if(attempt<5&&err instanceof ReferenceError&&/before initialization/.test(err.message)){await new Promise((resolve)=>setTimeout(resolve,0));continue}throw err}}}let announcedCompiledSkip=false;async function loadUserlandModel(modelName,subdirs=[""]){if(isCompiledBinary()){if(!announcedCompiledSkip){announcedCompiledSkip=true;console.debug("[orm] running from a compiled binary, so framework default models are not probed on disk; models this app uses are bundled.")}return null}const{path}=await import("@stacksjs/path");const userPath=path.userModelsPath(`${modelName}.ts`);try{if(await Bun.file(userPath).exists()){return await importDefault(userPath)}}catch(err){console.error(`[orm] Failed to import userland model ${modelName} from ${userPath} - falling back to framework default. Reason:`,err)}for(const sub of subdirs){const prefix=sub?`${sub}/`:"";const defaultPath=path.frameworkPath(`defaults/app/Models/${prefix}${modelName}.ts`);try{if(await Bun.file(defaultPath).exists()){return await importDefault(defaultPath)}}catch(err){console.error(`[orm] Failed to import framework default model ${modelName} from ${defaultPath} - trying next subdir. Reason:`,err)}}return null}const _loaded={};let _modelsSettled=false;const QUERY_ENTRYPOINTS=new Set(["where","orWhere","whereIn","whereNotIn","whereNull","whereNotNull","whereLike","whereBetween","whereNotBetween","orderBy","orderByDesc","latest","oldest","limit","take","skip","select","find","findOrFail","findMany","first","firstOrFail","all","get","paginate","count","sum","avg","min","max","create","createMany","firstOrCreate","updateOrCreate","save","update","updateMany","delete","destroy","remove","truncate"]);function featureGateFor(name){return FRAMEWORK_MODEL_MANIFEST.find(([model])=>model===name)?.[2]}export function frameworkModelFeature(name){return FRAMEWORK_MODEL_MANIFEST.find(([model])=>model===name)?.[2]}export class ModelUnavailableError extends Error{model;feature;name="ModelUnavailableError";constructor(model,feature){super(`Model "${model}" is not available in this process. ${feature?`The '${feature}' feature is off, so this model was never loaded - set \`enabled: true\` in config/${feature}.ts to use it.`:`No model file for it was found under app/Models or the framework defaults.`}`);this.model=model;this.feature=feature}}function unavailableModel(name){return new ModelUnavailableError(name,featureGateFor(name))}let _readyResolve=()=>{};export const ormReady=new Promise((resolve)=>{_readyResolve=resolve});function lazyModel(name){return new Proxy(function _modelStub(){},{get(_target,prop){if(prop==="then")return;const m=_loaded[name];if(m==null){if(_modelsSettled&&typeof prop==="string"&&QUERY_ENTRYPOINTS.has(prop))throw unavailableModel(name);return}const value=m[prop];return typeof value==="function"?value.bind(m):value},set(_target,prop,value){const m=_loaded[name];if(m==null)return false;m[prop]=value;return true},has(_target,prop){const m=_loaded[name];return m==null?false:(prop in m)},apply(_target,thisArg,args){const m=_loaded[name];if(m==null||typeof m!=="function")return;return m.apply(thisArg,args)}})}export const User=lazyModel("User");export const Job=lazyModel("Job");export const QueueWorker=lazyModel("QueueWorker");export const FailedJob=lazyModel("FailedJob");const FRAMEWORK_MODEL_MANIFEST=[["QueueWorker",[""],"queue"],["Referral",[""],"auth"],["ReferralCode",[""],"auth"],["Team",[""],"auth"],["TeamInvitation",[""],"auth"],["TeamMember",[""],"auth"],["SocialAccount",[""],"auth"],["Subscriber",[""],"auth"],["SubscriberEmail",[""],"auth"],["Subscription",[""],"auth"],["Categorizable",["Content"],"cms"],["Post",["Content"],"cms"],["Page",["Content"],"cms"],["PageRevision",["Content"],"cms"],["Redirect",["Content"],"cms"],["Menu",["Content"],"cms"],["MenuItem",["Content"],"cms"],["Author",["Content"],"cms"],["Comment",[""],"cms"],["Tag",[""],"cms"],["Site",[""],"auth"],["SiteDomain",[""],"auth"],["MagicLinkToken",[""],"auth"],["SmsOptOut",[""],"auth"],["GdprRequest",[""],"auth"],["Form",["Forms"],"forms"],["FormField",["Forms"],"forms"],["FormSubmission",["Forms"],"forms"],["Activity",[""],"dashboard"],["Board",[""],"dashboard"],["BoardColumn",[""],"dashboard"],["Card",[""],"dashboard"],["CardAttachment",[""],"dashboard"],["CardComment",[""],"dashboard"],["Deployment",[""],"dashboard"],["FeedbackToken",[""],"dashboard"],["Label",[""],"dashboard"],["Release",[""],"dashboard"],["Notification",[""],"dashboard"],["NotificationDelivery",[""],"dashboard"],["PersonalAccessToken",[""],"dashboard"],["MailPreference",[""],"dashboard"],["Log",[""],"dashboard"],["Request",[""],"dashboard"],["AnalyticsEvent",[""],"dashboard"],["QueryLog",[""],"dashboard"],["StorageItem",[""],"dashboard"],["StorageItemTask",[""],"dashboard"],["Error",[""],"monitoring"],["Websocket",["realtime"],"realtime"],["Campaign",[""],"marketing"],["CampaignSend",[""],"marketing"],["EmailList",[""],"marketing"],["EmailListSubscriber",[""],"marketing"],["EmailIdempotency",[""],"marketing"],["EmailSuppression",[""],"marketing"],["EmailWebhookEvent",[""],"marketing"],["SocialPost",[""],"marketing"],["Automation",[""],"marketing"],["AutomationRun",[""],"marketing"],["CampaignVariant",[""],"marketing"],["CommunicationSuppression",[""],"marketing"],["ConsentEvent",[""],"marketing"],["SenderDomain",[""],"marketing"],["UsageEvent",[""],"marketing"],["PaymentMethod",[""],"commerce"],["PaymentProduct",[""],"commerce"],["PaymentTransaction",[""],"commerce"],["Order",["commerce"],"commerce"],["OrderIdempotency",["commerce"],"commerce"],["OrderItem",["commerce"],"commerce"],["Cart",["commerce"],"commerce"],["CartItem",["commerce"],"commerce"],["Customer",["commerce"],"commerce"],["Product",["commerce"],"commerce"],["ProductVariant",["commerce"],"commerce"],["ProductUnit",["commerce"],"commerce"],["Manufacturer",["commerce"],"commerce"],["Category",["commerce"],"commerce"],["Coupon",["commerce"],"commerce"],["Discount",["commerce"],"commerce"],["PostPurchaseOffer",["commerce"],"commerce"],["PostPurchaseOfferResponse",["commerce"],"commerce"],["GiftCard",["commerce"],"commerce"],["LicenseKey",["commerce"],"commerce"],["LicenseActivation",["commerce"],"commerce"],["LicenseSeat",["commerce"],"commerce"],["Review",["commerce"],"commerce"],["Receipt",["commerce"],"commerce"],["PrintDevice",["commerce"],"commerce"],["ShippingMethod",["commerce"],"commerce"],["ShippingRate",["commerce"],"commerce"],["ShippingZone",["commerce"],"commerce"],["DeliveryRoute",["commerce"],"commerce"],["DeliveryStop",["commerce"],"commerce"],["DigitalDelivery",["commerce"],"commerce"],["Courier",["commerce"],"commerce"],["CourierPing",["commerce"],"commerce"],["TaxRate",["commerce"],"commerce"],["WaitlistProduct",["commerce"],"commerce"],["WaitlistRestaurant",["commerce"],"commerce"],["Auction",["commerce"],"commerce"],["AuctionItem",["commerce"],"commerce"],["Bid",["commerce"],"commerce"],["Pledge",["commerce"],"commerce"],["LoyaltyPoint",["commerce"],"commerce"],["LoyaltyReward",["commerce"],"commerce"],["Payment",["commerce"],"commerce"],["PaymentWebhookEvent",["commerce"],"commerce"],["Transaction",["commerce"],"commerce"]];queueMicrotask(async()=>{try{const{feature}=await import("@stacksjs/config");const userModel=await loadUserlandModel("User");if(userModel)_loaded.User=userModel;if(feature("queue")){const job=await loadUserlandModel("Job");if(job)_loaded.Job=job;const failedJob=await loadUserlandModel("FailedJob");if(failedJob)_loaded.FailedJob=failedJob}for(const[name,subdirs,featureFlag]of FRAMEWORK_MODEL_MANIFEST){if(!feature(featureFlag))continue;const M=await loadUserlandModel(name,subdirs);if(M)_loaded[name]=M}}catch(err){console.error("[orm] deferred model load failed:",err)}finally{_modelsSettled=true;_readyResolve()}});export const Activity=lazyModel("Activity");export const AnalyticsEvent=lazyModel("AnalyticsEvent");export const Automation=lazyModel("Automation");export const AutomationRun=lazyModel("AutomationRun");export const Auction=lazyModel("Auction");export const CampaignVariant=lazyModel("CampaignVariant");export const CommunicationSuppression=lazyModel("CommunicationSuppression");export const ConsentEvent=lazyModel("ConsentEvent");export const SenderDomain=lazyModel("SenderDomain");export const UsageEvent=lazyModel("UsageEvent");export const AuctionItem=lazyModel("AuctionItem");export const Author=lazyModel("Author");export const Bid=lazyModel("Bid");export const Board=lazyModel("Board");export const BoardColumn=lazyModel("BoardColumn");export const Campaign=lazyModel("Campaign");export const Card=lazyModel("Card");export const CardAttachment=lazyModel("CardAttachment");export const CardComment=lazyModel("CardComment");export const Cart=lazyModel("Cart");export const CartItem=lazyModel("CartItem");export const Category=lazyModel("Category");export const Comment=lazyModel("Comment");export const Coupon=lazyModel("Coupon");export const Customer=lazyModel("Customer");export const DeliveryRoute=lazyModel("DeliveryRoute");export const DeliveryStop=lazyModel("DeliveryStop");export const Deployment=lazyModel("Deployment");export const FeedbackToken=lazyModel("FeedbackToken");export const DigitalDelivery=lazyModel("DigitalDelivery");export const Courier=lazyModel("Courier");export const CourierPing=lazyModel("CourierPing");export const CampaignSend=lazyModel("CampaignSend");export const EmailList=lazyModel("EmailList");export const EmailListSubscriber=lazyModel("EmailListSubscriber");export const Form=lazyModel("Form");export const FormField=lazyModel("FormField");export const FormSubmission=lazyModel("FormSubmission");export const MagicLinkToken=lazyModel("MagicLinkToken");export const Menu=lazyModel("Menu");export const MenuItem=lazyModel("MenuItem");export const PageRevision=lazyModel("PageRevision");export const Pledge=lazyModel("Pledge");export const Redirect=lazyModel("Redirect");export const Site=lazyModel("Site");export const SiteDomain=lazyModel("SiteDomain");export const SmsOptOut=lazyModel("SmsOptOut");export const GdprRequest=lazyModel("GdprRequest");export const StorageItem=lazyModel("StorageItem");export const StorageItemTask=lazyModel("StorageItemTask");export const EmailIdempotency=lazyModel("EmailIdempotency");export const EmailSuppression=lazyModel("EmailSuppression");export const EmailWebhookEvent=lazyModel("EmailWebhookEvent");export const ErrorModel=lazyModel("Error");export const GiftCard=lazyModel("GiftCard");export const Label=lazyModel("Label");export const LicenseActivation=lazyModel("LicenseActivation");export const LicenseKey=lazyModel("LicenseKey");export const LicenseSeat=lazyModel("LicenseSeat");export const Discount=lazyModel("Discount");export const PostPurchaseOffer=lazyModel("PostPurchaseOffer");export const PostPurchaseOfferResponse=lazyModel("PostPurchaseOfferResponse");export const Log=lazyModel("Log");export const LoyaltyPoint=lazyModel("LoyaltyPoint");export const LoyaltyReward=lazyModel("LoyaltyReward");export const MailPreference=lazyModel("MailPreference");export const Manufacturer=lazyModel("Manufacturer");export const Notification=lazyModel("Notification");export const NotificationDelivery=lazyModel("NotificationDelivery");export const Order=lazyModel("Order");export const OrderIdempotency=lazyModel("OrderIdempotency");export const PersonalAccessToken=lazyModel("PersonalAccessToken");export const OrderItem=lazyModel("OrderItem");export const Page=lazyModel("Page");export const Payment=lazyModel("Payment");export const PaymentWebhookEvent=lazyModel("PaymentWebhookEvent");export const PaymentMethod=lazyModel("PaymentMethod");export const PaymentProduct=lazyModel("PaymentProduct");export const PaymentTransaction=lazyModel("PaymentTransaction");export const Post=lazyModel("Post");export const Categorizable=lazyModel("Categorizable");export const PrintDevice=lazyModel("PrintDevice");export const Product=lazyModel("Product");export const ProductUnit=lazyModel("ProductUnit");export const ProductVariant=lazyModel("ProductVariant");export const QueryLog=lazyModel("QueryLog");export const Receipt=lazyModel("Receipt");export const Referral=lazyModel("Referral");export const ReferralCode=lazyModel("ReferralCode");export const Release=lazyModel("Release");export const Request=lazyModel("Request");export const Review=lazyModel("Review");export const ShippingMethod=lazyModel("ShippingMethod");export const ShippingRate=lazyModel("ShippingRate");export const ShippingZone=lazyModel("ShippingZone");export const SocialPost=lazyModel("SocialPost");export const SocialAccount=lazyModel("SocialAccount");export const Subscriber=lazyModel("Subscriber");export const SubscriberEmail=lazyModel("SubscriberEmail");export const Subscription=lazyModel("Subscription");export const Tag=lazyModel("Tag");export const TaxRate=lazyModel("TaxRate");export const Team=lazyModel("Team");export const TeamInvitation=lazyModel("TeamInvitation");export const TeamMember=lazyModel("TeamMember");export const Transaction=lazyModel("Transaction");export const WaitlistProduct=lazyModel("WaitlistProduct");export const WaitlistRestaurant=lazyModel("WaitlistRestaurant");export const Websocket=lazyModel("Websocket");const _allExports={User,Job,FailedJob,QueueWorker,Activity,AnalyticsEvent,Automation,AutomationRun,Auction,AuctionItem,Author,Bid,Board,BoardColumn,Campaign,CampaignSend,CampaignVariant,Card,CardComment,Cart,CartItem,Categorizable,Category,Comment,Coupon,Customer,Discount,CommunicationSuppression,ConsentEvent,DeliveryRoute,DeliveryStop,Deployment,DigitalDelivery,Courier,CourierPing,EmailList,EmailListSubscriber,EmailIdempotency,EmailSuppression,EmailWebhookEvent,ErrorModel,Form,FormField,FormSubmission,GdprRequest,GiftCard,Label,LicenseActivation,LicenseKey,LicenseSeat,Log,LoyaltyPoint,LoyaltyReward,MailPreference,Manufacturer,Notification,MagicLinkToken,Menu,MenuItem,NotificationDelivery,Order,OrderIdempotency,OrderItem,Page,PageRevision,Payment,PaymentMethod,PaymentProduct,PaymentTransaction,PaymentWebhookEvent,Pledge,Post,PostPurchaseOffer,PostPurchaseOfferResponse,PrintDevice,Product,ProductUnit,ProductVariant,QueryLog,Receipt,Release,Request,Review,ShippingMethod,Redirect,SenderDomain,ShippingRate,ShippingZone,Site,SiteDomain,SmsOptOut,SocialAccount,SocialPost,Subscriber,SubscriberEmail,Subscription,Tag,TaxRate,Team,TeamInvitation,TeamMember,Transaction,UsageEvent,WaitlistProduct,WaitlistRestaurant,Websocket};const g=globalThis;for(const[name,M]of Object.entries(_allExports)){if(M&&g[name]===undefined)g[name]=M}export const modelGlobalNames=Object.keys(_allExports);async function _safeAll(M){if(!M)return[];try{if(typeof M.all==="function"){const rows=await M.all();return Array.isArray(rows)?rows:[]}if(typeof M.get==="function"){const rows=await M.get();return Array.isArray(rows)?rows:[]}}catch{}return[]}function _safeGet(row,key,fallback=""){if(!row)return fallback;try{if(typeof row.get==="function"){const v=row.get(key);if(v!==undefined&&v!==null)return v}}catch{}const direct=row?.[key];return direct!==undefined&&direct!==null?direct:fallback}if(g.safeAll===undefined)g.safeAll=_safeAll;if(g.safeGet===undefined)g.safeGet=_safeGet;export*from"./messaging";
|
|
@@ -221,6 +221,20 @@ export default defineModel({
|
|
|
221
221
|
rule: schema.string().max(20),
|
|
222
222
|
},
|
|
223
223
|
},
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* The discount code the shopper entered, as typed. Checked when it is
|
|
227
|
+
* applied and again when the order is placed, since a code can expire or
|
|
228
|
+
* run out in between. Matches a `Discount` code or a `Coupon` code.
|
|
229
|
+
*/
|
|
230
|
+
discountCode: {
|
|
231
|
+
order: 19,
|
|
232
|
+
fillable: true,
|
|
233
|
+
nullable: true,
|
|
234
|
+
validation: {
|
|
235
|
+
rule: schema.string().max(64),
|
|
236
|
+
},
|
|
237
|
+
},
|
|
224
238
|
},
|
|
225
239
|
|
|
226
240
|
dashboard: {
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { defineModel } from '@stacksjs/orm'
|
|
2
|
+
import { schema } from '@stacksjs/validation/runtime'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A discount the storefront applies by itself (automatic) or when a shopper
|
|
6
|
+
* enters its code.
|
|
7
|
+
*
|
|
8
|
+
* Coupons cover the simple case, a code worth a percentage or an amount.
|
|
9
|
+
* This covers the rest of what merchants run: buy X get Y ("buy 4, get 4
|
|
10
|
+
* free"), volume tiers ("5+ pairs 20% off"), free shipping, discounts limited
|
|
11
|
+
* to products, variants or categories, minimums, caps and the rules for which
|
|
12
|
+
* discounts combine. `commerce.discounts.price()` reads these rows and prices a
|
|
13
|
+
* basket with the pure engine in `@stacksjs/commerce/discounts/engine`.
|
|
14
|
+
*
|
|
15
|
+
* Amounts are integer minor units of the store's currency; percentages are
|
|
16
|
+
* plain numbers from 0 to 100.
|
|
17
|
+
*/
|
|
18
|
+
export default defineModel({
|
|
19
|
+
name: 'Discount',
|
|
20
|
+
table: 'discounts',
|
|
21
|
+
primaryKey: 'id',
|
|
22
|
+
autoIncrement: true,
|
|
23
|
+
|
|
24
|
+
// Store configuration: no row has a per-caller owner. Writes are an
|
|
25
|
+
// administrative concern gated by `middleware` (stacksjs/stacks#2375).
|
|
26
|
+
ownership: false,
|
|
27
|
+
|
|
28
|
+
traits: {
|
|
29
|
+
useUuid: true,
|
|
30
|
+
useTimestamps: true,
|
|
31
|
+
useSearch: {
|
|
32
|
+
displayable: ['id', 'title', 'code', 'type', 'value', 'isActive', 'usageCount', 'startsAt', 'endsAt'],
|
|
33
|
+
searchable: ['title', 'code'],
|
|
34
|
+
sortable: ['createdAt', 'updatedAt', 'title', 'usageCount', 'startsAt', 'endsAt'],
|
|
35
|
+
filterable: ['type', 'isActive'],
|
|
36
|
+
},
|
|
37
|
+
useSeeder: { count: 0 },
|
|
38
|
+
useApi: {
|
|
39
|
+
uri: 'discounts',
|
|
40
|
+
middleware: ['auth'],
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
|
|
44
|
+
attributes: {
|
|
45
|
+
/** What the shopper sees beside the saving: "BUY 4, GET 4 FREE | 50% OFF". */
|
|
46
|
+
title: {
|
|
47
|
+
order: 1,
|
|
48
|
+
fillable: true,
|
|
49
|
+
required: true,
|
|
50
|
+
validation: { rule: schema.string().required().max(255) },
|
|
51
|
+
factory: () => 'BUY 4, GET 4 FREE',
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
/** The code a shopper types. Empty makes the discount automatic. */
|
|
55
|
+
code: {
|
|
56
|
+
order: 2,
|
|
57
|
+
fillable: true,
|
|
58
|
+
unique: true,
|
|
59
|
+
nullable: true,
|
|
60
|
+
validation: { rule: schema.string().max(64) },
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
type: {
|
|
64
|
+
order: 3,
|
|
65
|
+
fillable: true,
|
|
66
|
+
required: true,
|
|
67
|
+
validation: {
|
|
68
|
+
rule: schema.enum(['percentage', 'fixed_amount', 'buy_x_get_y', 'volume', 'free_shipping']).required(),
|
|
69
|
+
},
|
|
70
|
+
factory: () => 'percentage',
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
/** Whole percent off for `percentage`, minor units for `fixed_amount`. */
|
|
74
|
+
value: {
|
|
75
|
+
order: 4,
|
|
76
|
+
fillable: true,
|
|
77
|
+
default: 0,
|
|
78
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
79
|
+
factory: () => 10,
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
/** `product` or `order`, for percentage and fixed amounts. Empty: decided by whether a target is set. */
|
|
83
|
+
scope: {
|
|
84
|
+
order: 5,
|
|
85
|
+
fillable: true,
|
|
86
|
+
nullable: true,
|
|
87
|
+
validation: { rule: schema.enum(['product', 'order']) },
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
/** A fixed amount off every targeted unit rather than once. */
|
|
91
|
+
perItem: {
|
|
92
|
+
order: 6,
|
|
93
|
+
fillable: true,
|
|
94
|
+
default: false,
|
|
95
|
+
validation: { rule: schema.boolean() },
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
/** JSON `{ productIds, variantIds, categoryIds }`: the lines it reaches. Empty reaches every line. */
|
|
99
|
+
target: {
|
|
100
|
+
order: 7,
|
|
101
|
+
fillable: true,
|
|
102
|
+
nullable: true,
|
|
103
|
+
type: 'text',
|
|
104
|
+
validation: { rule: schema.string() },
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
buyQuantity: {
|
|
108
|
+
order: 8,
|
|
109
|
+
fillable: true,
|
|
110
|
+
nullable: true,
|
|
111
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
/** JSON target for what must be bought. Empty: `target`. */
|
|
115
|
+
buyTarget: {
|
|
116
|
+
order: 9,
|
|
117
|
+
fillable: true,
|
|
118
|
+
nullable: true,
|
|
119
|
+
type: 'text',
|
|
120
|
+
validation: { rule: schema.string() },
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
getQuantity: {
|
|
124
|
+
order: 10,
|
|
125
|
+
fillable: true,
|
|
126
|
+
nullable: true,
|
|
127
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
/** JSON target for what comes discounted. Empty: the buy target. */
|
|
131
|
+
getTarget: {
|
|
132
|
+
order: 11,
|
|
133
|
+
fillable: true,
|
|
134
|
+
nullable: true,
|
|
135
|
+
type: 'text',
|
|
136
|
+
validation: { rule: schema.string() },
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
/** Whole percent off each "get" unit: 100 is free. */
|
|
140
|
+
getPercent: {
|
|
141
|
+
order: 12,
|
|
142
|
+
fillable: true,
|
|
143
|
+
nullable: true,
|
|
144
|
+
validation: { rule: schema.number().integer().min(0).max(100) },
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
/** Times one order may use a buy X get Y. Empty: unlimited. */
|
|
148
|
+
maxApplications: {
|
|
149
|
+
order: 13,
|
|
150
|
+
fillable: true,
|
|
151
|
+
nullable: true,
|
|
152
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
153
|
+
},
|
|
154
|
+
|
|
155
|
+
/** JSON `[{ minQuantity, percent }]` for volume tiers. */
|
|
156
|
+
tiers: {
|
|
157
|
+
order: 14,
|
|
158
|
+
fillable: true,
|
|
159
|
+
nullable: true,
|
|
160
|
+
type: 'text',
|
|
161
|
+
validation: { rule: schema.string() },
|
|
162
|
+
},
|
|
163
|
+
|
|
164
|
+
/** Free shipping only applies to a rate at or below this. */
|
|
165
|
+
maxShipping: {
|
|
166
|
+
order: 15,
|
|
167
|
+
fillable: true,
|
|
168
|
+
nullable: true,
|
|
169
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
minimumSubtotal: {
|
|
173
|
+
order: 16,
|
|
174
|
+
fillable: true,
|
|
175
|
+
nullable: true,
|
|
176
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
177
|
+
},
|
|
178
|
+
|
|
179
|
+
minimumQuantity: {
|
|
180
|
+
order: 17,
|
|
181
|
+
fillable: true,
|
|
182
|
+
nullable: true,
|
|
183
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
184
|
+
},
|
|
185
|
+
|
|
186
|
+
/** The most it takes off one order. */
|
|
187
|
+
maxAmount: {
|
|
188
|
+
order: 18,
|
|
189
|
+
fillable: true,
|
|
190
|
+
nullable: true,
|
|
191
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
combinesWithProduct: {
|
|
195
|
+
order: 19,
|
|
196
|
+
fillable: true,
|
|
197
|
+
default: false,
|
|
198
|
+
validation: { rule: schema.boolean() },
|
|
199
|
+
},
|
|
200
|
+
|
|
201
|
+
combinesWithOrder: {
|
|
202
|
+
order: 20,
|
|
203
|
+
fillable: true,
|
|
204
|
+
default: false,
|
|
205
|
+
validation: { rule: schema.boolean() },
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
combinesWithShipping: {
|
|
209
|
+
order: 21,
|
|
210
|
+
fillable: true,
|
|
211
|
+
default: false,
|
|
212
|
+
validation: { rule: schema.boolean() },
|
|
213
|
+
},
|
|
214
|
+
|
|
215
|
+
usageLimit: {
|
|
216
|
+
order: 22,
|
|
217
|
+
fillable: true,
|
|
218
|
+
nullable: true,
|
|
219
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
220
|
+
},
|
|
221
|
+
|
|
222
|
+
usageCount: {
|
|
223
|
+
order: 23,
|
|
224
|
+
fillable: true,
|
|
225
|
+
default: 0,
|
|
226
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
isActive: {
|
|
230
|
+
order: 24,
|
|
231
|
+
fillable: true,
|
|
232
|
+
default: true,
|
|
233
|
+
validation: { rule: schema.boolean() },
|
|
234
|
+
factory: () => true,
|
|
235
|
+
},
|
|
236
|
+
|
|
237
|
+
startsAt: {
|
|
238
|
+
order: 25,
|
|
239
|
+
fillable: true,
|
|
240
|
+
nullable: true,
|
|
241
|
+
validation: { rule: schema.string() },
|
|
242
|
+
},
|
|
243
|
+
|
|
244
|
+
endsAt: {
|
|
245
|
+
order: 26,
|
|
246
|
+
fillable: true,
|
|
247
|
+
nullable: true,
|
|
248
|
+
validation: { rule: schema.string() },
|
|
249
|
+
},
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
dashboard: {
|
|
253
|
+
highlight: false,
|
|
254
|
+
},
|
|
255
|
+
} as const)
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { defineModel } from '@stacksjs/orm'
|
|
2
|
+
import { schema } from '@stacksjs/validation/runtime'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A one-time offer shown after checkout, on the order confirmation page:
|
|
6
|
+
* "Thank you for your purchase! Grab 5+ pairs and get 60% off". The shopper
|
|
7
|
+
* picks a variant and a quantity and adds it to the order they just placed,
|
|
8
|
+
* charged to the payment method they already used, without checking out again.
|
|
9
|
+
*
|
|
10
|
+
* `commerce.upsells` decides which offers an order qualifies for, prices them,
|
|
11
|
+
* claims an acceptance once per order and product, takes the payment and adds
|
|
12
|
+
* the line to the order in one transaction. Responses (views, acceptances,
|
|
13
|
+
* declines) are `PostPurchaseOfferResponse` rows, which is where conversion
|
|
14
|
+
* and revenue come from.
|
|
15
|
+
*/
|
|
16
|
+
export default defineModel({
|
|
17
|
+
name: 'PostPurchaseOffer',
|
|
18
|
+
table: 'post_purchase_offers',
|
|
19
|
+
primaryKey: 'id',
|
|
20
|
+
autoIncrement: true,
|
|
21
|
+
|
|
22
|
+
// Store configuration, managed by staff through `middleware`.
|
|
23
|
+
ownership: false,
|
|
24
|
+
|
|
25
|
+
traits: {
|
|
26
|
+
useUuid: true,
|
|
27
|
+
useTimestamps: true,
|
|
28
|
+
useSearch: {
|
|
29
|
+
displayable: ['id', 'name', 'headline', 'discountPercent', 'minQuantity', 'isActive', 'priority'],
|
|
30
|
+
searchable: ['name', 'headline'],
|
|
31
|
+
sortable: ['createdAt', 'updatedAt', 'priority', 'name'],
|
|
32
|
+
filterable: ['isActive'],
|
|
33
|
+
},
|
|
34
|
+
useSeeder: { count: 0 },
|
|
35
|
+
useApi: {
|
|
36
|
+
uri: 'post-purchase-offers',
|
|
37
|
+
middleware: ['auth'],
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
hasMany: ['PostPurchaseOfferResponse'],
|
|
42
|
+
|
|
43
|
+
attributes: {
|
|
44
|
+
/** For staff: which offer this is in the dashboard. */
|
|
45
|
+
name: {
|
|
46
|
+
order: 1,
|
|
47
|
+
fillable: true,
|
|
48
|
+
required: true,
|
|
49
|
+
validation: { rule: schema.string().required().max(255) },
|
|
50
|
+
factory: () => 'Sock bundle upsell',
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
/** The heading over the offer on the confirmation page. */
|
|
54
|
+
headline: {
|
|
55
|
+
order: 2,
|
|
56
|
+
fillable: true,
|
|
57
|
+
nullable: true,
|
|
58
|
+
validation: { rule: schema.string().max(255) },
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
/** The offer in the shopper's words: "Grab 5+ pairs and get 60% off". */
|
|
62
|
+
message: {
|
|
63
|
+
order: 3,
|
|
64
|
+
fillable: true,
|
|
65
|
+
nullable: true,
|
|
66
|
+
type: 'text',
|
|
67
|
+
validation: { rule: schema.string().max(2000) },
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
/** JSON array of the product ids offered, in the order they are shown. */
|
|
71
|
+
productIds: {
|
|
72
|
+
order: 4,
|
|
73
|
+
fillable: true,
|
|
74
|
+
required: true,
|
|
75
|
+
type: 'text',
|
|
76
|
+
validation: { rule: schema.string().required() },
|
|
77
|
+
factory: () => '[]',
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
/** Whole percent off the offered products' prices, 0 to 100. */
|
|
81
|
+
discountPercent: {
|
|
82
|
+
order: 5,
|
|
83
|
+
fillable: true,
|
|
84
|
+
default: 0,
|
|
85
|
+
validation: { rule: schema.number().integer().min(0).max(100) },
|
|
86
|
+
factory: () => 60,
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
/** Units a shopper has to take for the offer price. */
|
|
90
|
+
minQuantity: {
|
|
91
|
+
order: 6,
|
|
92
|
+
fillable: true,
|
|
93
|
+
default: 1,
|
|
94
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
95
|
+
factory: () => 5,
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
/** What the quantity field starts at. */
|
|
99
|
+
defaultQuantity: {
|
|
100
|
+
order: 7,
|
|
101
|
+
fillable: true,
|
|
102
|
+
default: 1,
|
|
103
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
104
|
+
factory: () => 5,
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
/** The most units one acceptance may take. Empty: no ceiling but stock. */
|
|
108
|
+
maxQuantity: {
|
|
109
|
+
order: 8,
|
|
110
|
+
fillable: true,
|
|
111
|
+
nullable: true,
|
|
112
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
/** JSON array of product ids, one of which the order must contain. Empty: any order. */
|
|
116
|
+
triggerProductIds: {
|
|
117
|
+
order: 9,
|
|
118
|
+
fillable: true,
|
|
119
|
+
nullable: true,
|
|
120
|
+
type: 'text',
|
|
121
|
+
validation: { rule: schema.string() },
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
/** The order total, in minor units, an order needs to see the offer. */
|
|
125
|
+
minOrderTotal: {
|
|
126
|
+
order: 10,
|
|
127
|
+
fillable: true,
|
|
128
|
+
nullable: true,
|
|
129
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
130
|
+
},
|
|
131
|
+
|
|
132
|
+
/** Minutes after the order is placed that the offer stays open. */
|
|
133
|
+
windowMinutes: {
|
|
134
|
+
order: 11,
|
|
135
|
+
fillable: true,
|
|
136
|
+
default: 30,
|
|
137
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
138
|
+
factory: () => 30,
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
/** Higher shows first when an order qualifies for several. */
|
|
142
|
+
priority: {
|
|
143
|
+
order: 12,
|
|
144
|
+
fillable: true,
|
|
145
|
+
default: 0,
|
|
146
|
+
validation: { rule: schema.number().integer() },
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
isActive: {
|
|
150
|
+
order: 13,
|
|
151
|
+
fillable: true,
|
|
152
|
+
default: true,
|
|
153
|
+
validation: { rule: schema.boolean() },
|
|
154
|
+
factory: () => true,
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
startsAt: {
|
|
158
|
+
order: 14,
|
|
159
|
+
fillable: true,
|
|
160
|
+
nullable: true,
|
|
161
|
+
validation: { rule: schema.string() },
|
|
162
|
+
},
|
|
163
|
+
|
|
164
|
+
endsAt: {
|
|
165
|
+
order: 15,
|
|
166
|
+
fillable: true,
|
|
167
|
+
nullable: true,
|
|
168
|
+
validation: { rule: schema.string() },
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
dashboard: {
|
|
173
|
+
highlight: false,
|
|
174
|
+
},
|
|
175
|
+
} as const)
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { defineModel } from '@stacksjs/orm'
|
|
2
|
+
import { schema } from '@stacksjs/validation/runtime'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What one order did with one product of a post-purchase offer.
|
|
6
|
+
*
|
|
7
|
+
* Written when the offer is shown (`viewed`) and moved on from there:
|
|
8
|
+
* `pending` while its payment is being taken, then `accepted` (the line is on
|
|
9
|
+
* the order), `failed` (the payment did not go through; the shopper may try
|
|
10
|
+
* again while the offer is open) or `declined`. The unique index makes the
|
|
11
|
+
* offer one-time: an order can take each product of an offer once, however
|
|
12
|
+
* many tabs or double clicks race for it.
|
|
13
|
+
*
|
|
14
|
+
* The line is snapshotted here before the payment is taken, so a payment that
|
|
15
|
+
* needs the shopper to authenticate (3-D Secure) can be finished later by the
|
|
16
|
+
* payment webhook with exactly the price that was shown.
|
|
17
|
+
*/
|
|
18
|
+
export default defineModel({
|
|
19
|
+
name: 'PostPurchaseOfferResponse',
|
|
20
|
+
table: 'post_purchase_offer_responses',
|
|
21
|
+
primaryKey: 'id',
|
|
22
|
+
autoIncrement: true,
|
|
23
|
+
|
|
24
|
+
indexes: [
|
|
25
|
+
{
|
|
26
|
+
name: 'post_purchase_offer_responses_order_offer_product_unique',
|
|
27
|
+
columns: ['order_id', 'post_purchase_offer_id', 'product_id'],
|
|
28
|
+
unique: true,
|
|
29
|
+
},
|
|
30
|
+
],
|
|
31
|
+
|
|
32
|
+
// Written by `commerce.upsells` on the order's behalf, read by staff.
|
|
33
|
+
ownership: false,
|
|
34
|
+
|
|
35
|
+
belongsTo: ['PostPurchaseOffer', 'Order'],
|
|
36
|
+
|
|
37
|
+
traits: {
|
|
38
|
+
// No personal attributes of its own: the person is on the order it points at.
|
|
39
|
+
gdpr: { subject: { via: 'Order' }, erasure: 'keep', basis: 'legal_obligation', purpose: 'Order additions, kept for tax and accounting' },
|
|
40
|
+
useTimestamps: true,
|
|
41
|
+
useSeeder: { count: 0 },
|
|
42
|
+
},
|
|
43
|
+
|
|
44
|
+
attributes: {
|
|
45
|
+
status: {
|
|
46
|
+
order: 1,
|
|
47
|
+
fillable: true,
|
|
48
|
+
required: true,
|
|
49
|
+
validation: { rule: schema.enum(['viewed', 'pending', 'accepted', 'declined', 'failed']).required() },
|
|
50
|
+
factory: () => 'viewed',
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
productId: {
|
|
54
|
+
order: 2,
|
|
55
|
+
fillable: true,
|
|
56
|
+
required: true,
|
|
57
|
+
validation: { rule: schema.number().integer().required() },
|
|
58
|
+
factory: () => 1,
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
variantId: {
|
|
62
|
+
order: 3,
|
|
63
|
+
fillable: true,
|
|
64
|
+
nullable: true,
|
|
65
|
+
validation: { rule: schema.number().integer() },
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
quantity: {
|
|
69
|
+
order: 4,
|
|
70
|
+
fillable: true,
|
|
71
|
+
nullable: true,
|
|
72
|
+
validation: { rule: schema.number().integer().min(1) },
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
/** The offer price of one unit, in minor units. */
|
|
76
|
+
unitPrice: {
|
|
77
|
+
order: 5,
|
|
78
|
+
fillable: true,
|
|
79
|
+
nullable: true,
|
|
80
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
81
|
+
},
|
|
82
|
+
|
|
83
|
+
/** The regular price of one unit the offer was taken off, in minor units. */
|
|
84
|
+
compareAtPrice: {
|
|
85
|
+
order: 6,
|
|
86
|
+
fillable: true,
|
|
87
|
+
nullable: true,
|
|
88
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
/** `unitPrice * quantity`: what was added to the order. */
|
|
92
|
+
amount: {
|
|
93
|
+
order: 7,
|
|
94
|
+
fillable: true,
|
|
95
|
+
nullable: true,
|
|
96
|
+
validation: { rule: schema.number().integer().min(0) },
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
currency: {
|
|
100
|
+
order: 8,
|
|
101
|
+
fillable: true,
|
|
102
|
+
nullable: true,
|
|
103
|
+
validation: { rule: schema.string().max(3) },
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
/** The provider's id for the payment (a PaymentIntent), when one was taken. */
|
|
107
|
+
paymentReference: {
|
|
108
|
+
order: 9,
|
|
109
|
+
fillable: true,
|
|
110
|
+
nullable: true,
|
|
111
|
+
validation: { rule: schema.string().max(255) },
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
paymentProvider: {
|
|
115
|
+
order: 10,
|
|
116
|
+
fillable: true,
|
|
117
|
+
nullable: true,
|
|
118
|
+
validation: { rule: schema.string().max(64) },
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
failureReason: {
|
|
122
|
+
order: 11,
|
|
123
|
+
fillable: true,
|
|
124
|
+
nullable: true,
|
|
125
|
+
validation: { rule: schema.string().max(1000) },
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
/** The `order_items` row the acceptance created. */
|
|
129
|
+
orderItemId: {
|
|
130
|
+
order: 12,
|
|
131
|
+
fillable: true,
|
|
132
|
+
nullable: true,
|
|
133
|
+
validation: { rule: schema.number().integer() },
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
respondedAt: {
|
|
137
|
+
order: 13,
|
|
138
|
+
fillable: true,
|
|
139
|
+
nullable: true,
|
|
140
|
+
validation: { rule: schema.string() },
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
|
|
144
|
+
dashboard: { enabled: false },
|
|
145
|
+
} as const)
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/orm",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.621",
|
|
6
6
|
"description": "The Stacks ORM integration",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -63,32 +63,32 @@
|
|
|
63
63
|
"prepublishOnly": "bun run build"
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
|
-
"@stacksjs/cache": "0.75.
|
|
67
|
-
"@stacksjs/cli": "0.75.
|
|
68
|
-
"@stacksjs/config": "0.75.
|
|
69
|
-
"@stacksjs/database": "0.75.
|
|
70
|
-
"@stacksjs/env": "0.75.
|
|
71
|
-
"@stacksjs/error-handling": "0.75.
|
|
72
|
-
"@stacksjs/events": "0.75.
|
|
73
|
-
"@stacksjs/logging": "0.75.
|
|
74
|
-
"@stacksjs/model-meta": "0.75.
|
|
75
|
-
"@stacksjs/pagination": "0.75.
|
|
76
|
-
"@stacksjs/path": "0.75.
|
|
77
|
-
"@stacksjs/query-builder": "0.75.
|
|
78
|
-
"@stacksjs/realtime": "0.75.
|
|
79
|
-
"@stacksjs/router": "0.75.
|
|
80
|
-
"@stacksjs/storage": "0.75.
|
|
81
|
-
"@stacksjs/strings": "0.75.
|
|
66
|
+
"@stacksjs/cache": "0.75.621",
|
|
67
|
+
"@stacksjs/cli": "0.75.621",
|
|
68
|
+
"@stacksjs/config": "0.75.621",
|
|
69
|
+
"@stacksjs/database": "0.75.621",
|
|
70
|
+
"@stacksjs/env": "0.75.621",
|
|
71
|
+
"@stacksjs/error-handling": "0.75.621",
|
|
72
|
+
"@stacksjs/events": "0.75.621",
|
|
73
|
+
"@stacksjs/logging": "0.75.621",
|
|
74
|
+
"@stacksjs/model-meta": "0.75.621",
|
|
75
|
+
"@stacksjs/pagination": "0.75.621",
|
|
76
|
+
"@stacksjs/path": "0.75.621",
|
|
77
|
+
"@stacksjs/query-builder": "0.75.621",
|
|
78
|
+
"@stacksjs/realtime": "0.75.621",
|
|
79
|
+
"@stacksjs/router": "0.75.621",
|
|
80
|
+
"@stacksjs/storage": "0.75.621",
|
|
81
|
+
"@stacksjs/strings": "0.75.621",
|
|
82
82
|
"@stacksjs/ts-validation": "^0.5.7",
|
|
83
|
-
"@stacksjs/validation": "0.75.
|
|
83
|
+
"@stacksjs/validation": "0.75.621",
|
|
84
84
|
"bun-query-builder": "^0.6.2",
|
|
85
85
|
"stripe": "23.0.0"
|
|
86
86
|
},
|
|
87
87
|
"peerDependencies": {
|
|
88
|
-
"@stacksjs/auth": "0.75.
|
|
89
|
-
"@stacksjs/payments": "0.75.
|
|
90
|
-
"@stacksjs/queue": "0.75.
|
|
91
|
-
"@stacksjs/search-engine": "0.75.
|
|
88
|
+
"@stacksjs/auth": "0.75.621",
|
|
89
|
+
"@stacksjs/payments": "0.75.621",
|
|
90
|
+
"@stacksjs/queue": "0.75.621",
|
|
91
|
+
"@stacksjs/search-engine": "0.75.621"
|
|
92
92
|
},
|
|
93
93
|
"peerDependenciesMeta": {
|
|
94
94
|
"@stacksjs/auth": {
|
|
@@ -102,7 +102,7 @@
|
|
|
102
102
|
}
|
|
103
103
|
},
|
|
104
104
|
"devDependencies": {
|
|
105
|
-
"@stacksjs/types": "0.75.
|
|
105
|
+
"@stacksjs/types": "0.75.621",
|
|
106
106
|
"better-dx": "^0.2.39"
|
|
107
107
|
}
|
|
108
108
|
}
|