Skip to content

k.commerce.product ​

Product management.

Execution ContextPrerequisitesTypical Use
KScript API (k.api.get / k.api.post), server-side <script env="server">E-commerce module enabled; file digital items read files via k.file site storage pathsList/search catalog products, manage SKU variants, update multilingual fields, compute customer/currency pricing, attach digital assets, and handle reviews

k.commerce.product manages catalog products, variants, category memberships, currency/customer price resolution, variant-level digital items, and customer reviews.

Quick Start ​

js
k.api.get(() => {
    const products = k.commerce.product.list({ includeOffline: false })
    if (products.length === 0) {
        return { count: 0, first: null }
    }
    const detail = k.commerce.product.get(products[0].id)
    return {
        count: products.length,
        title: detail.title,
        variantCount: detail.variants.length
    }
})

Quick Reference ​

Method / PropertyDescriptionReturns
list(query?)List products filtered by categories, currency, offline flag, or whereProductSimple[]
get(seoNameOrId, options?)Get product details and variants by SEO name or ID (throws if missing)ProductDetail
search(keyword, options?)Search products by keyword and facet filters with facet aggregationSearchResult
create(value)Create a new productProduct
createVariant(productId, value)Create a new variant under an existing productProduct
updateField(id, property, value, lang?)Update a single product field (optionally localized)void
updateFields(id, updateFields)Batch update multiple product fieldsvoid
updateVariantField(id, property, value, lang?)Update a single variant field (9 supported fields; lang is ignored)void
updateVariantFields(id, updateFields)Batch update multiple variant fieldsvoid
getPriceDetail(variantId, options?)Calculate discounted variant price for a customer/currencyProductPrice | null
addCategory(id, categoryId)Assign the product to a categoryvoid
removeCategory(id, categoryId)Remove the product from a categoryvoid
addTextDigitalItem(variantId, name, text)Attach a plain-text digital delivery item to a variantvoid
addLinkDigitalItem(variantId, name, link)Attach a URL link digital delivery item to a variantvoid
addFileDigitalItem(variantId, name, filePath)Attach a site file digital delivery item to a variantvoid
removeDigitalItem(variantId, digitalItemId)Remove a digital delivery item from a variantvoid
addReview(model)Submit a customer review for a product variantvoid
reviewList(variantId)List customer reviews for a product variantProductReviewModel[]
deleteVariant(id)Delete a variant by IDvoid
delete(id)Delete a product by IDvoid

list() ​

Get a list of products.

ParameterTypeRequiredDescription
queryProductQueryParamsNoProduct list filters
query.categoriesstring[]NoFilter by category IDs
query.includeOfflinebooleanNoWhether to include offline products (default false)
query.includeSubCategorybooleanNoWhether to include products from child categories (default false)
query.currencystringNoTarget display currency code
query.whereanyNoCustom filter expression/object

Returns: ProductSimple[]. Product list matching the filters.

js
k.api.get(() => {
    const products = k.commerce.product.list()
    return { count: products.length, products }
})

get() ​

Get product details including variants, categories, and currency conversion.

Exception Handling

Throws "Product not found" when no matching product exists; wrap calls with try / catch when looking up arbitrary IDs or slugs.

ParameterTypeRequiredDescription
seoNameOrIdstringYesProduct SEO name or product ID
optionsGetProductOptionsNoOptional query options
options.currencystringNoTarget currency code for converted prices

Returns: ProductDetail. Product detail including variants, categories, and currency.

js
k.api.get(() => {
    try {
        const product = k.commerce.product.get('product-seo-name')
        return { title: product.title, variants: product.variants }
    } catch (e) {
        return { error: e.message }
    }
})

Search products by keyword and facet filters.

ParameterTypeRequiredDescription
keywordstringYesSearch keyword
optionsSearchOptionsNoSearch filters
options.categoriesstring[]NoFilter by category IDs
options.includeOfflinebooleanNoWhether to include offline products (default false)
options.includeSubCategorybooleanNoWhether to include products from child categories (default false)
options.currencystringNoTarget display currency code
options.facetParamsFacetParam[]NoFacet filter items ({ name, label })

Returns: SearchResult. Contains matching list and aggregated facets.

js
k.api.get(() => {
    const result = k.commerce.product.search('wireless earbuds', {
        includeOffline: true,
        includeSubCategory: false
    })
    return { count: result.list.length, facets: result.facets }
})

create() ​

Create a new product (and automatically create its initial default variant using price, inventory, variantImage, autoDelivery, and active).

ParameterTypeRequiredDescription
valueNewProductYesNew product data

Returns: Product (Entities.Product). Does not include price, inventory, autoDelivery, variantImage, variants, or categories; call get(product.id) for ProductDetail when you need variants or prices.

js
k.api.post(() => {
    const product = k.commerce.product.create({
        title: 'New Product',
        description: 'Product description',
        price: 99.9,
        active: true
    })
    return { id: product.id, title: product.title }
})

createVariant() ​

Create a new variant for an existing product.

ParameterTypeRequiredDescription
productIdstringYesProduct ID
valueNewProductVariantYesNew variant data

Returns: Product (Entities.Product). Does not include price, inventory, variants, or categories; call get(product.id) to inspect ProductDetail.

js
k.api.post(() => {
    const productId = k.commerce.product.list()[0].id
    const product = k.commerce.product.createVariant(productId, {
        sku: 'SKU-' + Date.now(),
        price: 88,
        inventory: 100
    })
    const detail = k.commerce.product.get(product.id)
    return { id: product.id, variantCount: detail.variants.length }
})

updateField() ​

Update a single product field.

ParameterTypeRequiredDescription
idstringYesProduct ID
propertystringYesField name
valueanyYesField value
langstringNoLanguage code for multilingual fields

Returns: void.

js
k.api.post(() => {
    const productId = k.commerce.product.list()[0].id
    k.commerce.product.updateField(productId, 'title', 'Updated Title')
    k.commerce.product.updateField(productId, 'title', 'New Title', 'en')
    return { success: true }
})

updateFields() ​

Batch update multiple product fields.

ParameterTypeRequiredDescription
idstringYesProduct ID
updateFieldsUpdateFieldParams[]YesList of fields to update
updateFields[].propertystringYesField name
updateFields[].valueanyYesField value
updateFields[].langstringNoLanguage code for multilingual fields

Returns: void.

js
k.api.post(() => {
    const productId = k.commerce.product.list()[0].id
    k.commerce.product.updateFields(productId, [
        { property: 'title', value: 'Updated Title', lang: 'en' },
        { property: 'tags', value: ['tag1', 'tag2'] }
    ])
    return { success: true }
})

updateVariantField() ​

Update a single variant field. Only the following 9 fixed property names (case-insensitive) are supported: active, barcode, sku, image, tags, price, weight, inventory, and selectedOptions.

ParameterTypeRequiredDescription
idstringYesVariant ID
propertystringYesField name (one of the 9 supported fields above)
valueanyYesField value
langstringNoLanguage code (accepted by signature for consistency with updateField, but ignored at runtime because variants have no multilingual fields)

Returns: void.

js
k.api.post(() => {
    const product = k.commerce.product.get(k.commerce.product.list()[0].id)
    const variantId = product.variants[0].id
    k.commerce.product.updateVariantField(variantId, 'sku', 'NEW-SKU')
    return { updated: true }
})

updateVariantFields() ​

Batch update multiple variant fields. Only the 9 fixed fields (active, barcode, sku, image, tags, price, weight, inventory, selectedOptions) are supported.

ParameterTypeRequiredDescription
idstringYesVariant ID
updateFieldsUpdateFieldParams[]YesList of fields to update
updateFields[].propertystringYesField name (one of the 9 supported fields above)
updateFields[].valueanyYesField value
updateFields[].langstringNoLanguage code (accepted by signature, but ignored at runtime because variants have no multilingual fields)

Returns: void.

js
k.api.post(() => {
    const product = k.commerce.product.get(k.commerce.product.list()[0].id)
    const variantId = product.variants[0].id
    k.commerce.product.updateVariantFields(variantId, [
        { property: 'sku', value: 'NEW-SKU' }
    ])
    return { updated: true }
})

getPriceDetail() ​

Calculate discounted price details for a variant including original amount, discounted amount, and currency metadata.

Note: Returned amount and originalAmount values are always calculated in the store's base currency (not multiplied by currency.rate). options.currency only resolves the returned currency metadata object ({ code, symbol, rate }); multiply by detail.currency.rate on the caller side when displaying converted currency amounts.

ParameterTypeRequiredDescription
variantIdstringYesVariant ID
optionsProductPriceOptionsNoPrice calculation options (customerId for membership/discount matching, currency to populate currency metadata)

Returns: ProductPrice | null. Returns base-currency amount, originalAmount, and resolved currency ({ code, symbol, rate }), or null if the variant does not exist.

js
k.api.get(() => {
    const product = k.commerce.product.get(k.commerce.product.list()[0].id)
    const variantId = product.variants[0].id
    const detail = k.commerce.product.getPriceDetail(variantId, {
        customerId: k.commerce.customer.currentId || '',
        currency: 'USD'
    })
    return detail
})

addCategory() ​

Assign the product to a category (by productId).

ParameterTypeRequiredDescription
idstringYesProduct ID
categoryIdstringYesCategory ID

Returns: void.

js
k.api.post(() => {
    const productId = k.commerce.product.list()[0].id
    const categoryId = k.commerce.category.list()[0].id
    k.commerce.product.addCategory(productId, categoryId)
    return { categories: k.commerce.product.get(productId).categories }
})

removeCategory() ​

Remove the product from a category.

ParameterTypeRequiredDescription
idstringYesProduct ID
categoryIdstringYesCategory ID

Returns: void.

js
k.api.post(() => {
    const productId = k.commerce.product.list()[0].id
    const categoryId = k.commerce.category.list()[0].id
    k.commerce.product.removeCategory(productId, categoryId)
    return { categories: k.commerce.product.get(productId).categories }
})

addTextDigitalItem() ​

Attach a plain-text digital delivery item (such as a license key) to a variant (variantId).

ParameterTypeRequiredDescription
variantIdstringYesVariant ID
namestringYesDigital item name shown to the customer
textstringYesText content

Returns: void.

js
k.api.post(() => {
    const product = k.commerce.product.get(k.commerce.product.list()[0].id)
    const variantId = product.variants[0].id
    k.commerce.product.addTextDigitalItem(variantId, 'License key', 'XXXX-XXXX')
    return { updated: true }
})

addLinkDigitalItem() ​

Attach a URL link digital delivery item to a variant.

ParameterTypeRequiredDescription
variantIdstringYesVariant ID
namestringYesDigital item name shown to the customer
linkstringYesDownload or resource URL

Returns: void.

js
k.api.post(() => {
    const product = k.commerce.product.get(k.commerce.product.list()[0].id)
    const variantId = product.variants[0].id
    k.commerce.product.addLinkDigitalItem(variantId, 'Download', 'https://example.com/file.zip')
    return { updated: true }
})

addFileDigitalItem() ​

Attach a site file digital delivery item (for example an e-book) to a variant. The file path is a site directory path readable by k.file.

ParameterTypeRequiredDescription
variantIdstringYesVariant ID
namestringYesDigital item filename (used as the display name, stored filename on disk, and for MIME type detection; must include the file extension such as 'book.pdf' and must not contain path separators)
filePathstringYesRelative path to the site file

Returns: void.

js
k.api.post(() => {
    const product = k.commerce.product.get(k.commerce.product.list()[0].id)
    const variantId = product.variants[0].id
    k.commerce.product.addFileDigitalItem(variantId, 'book.pdf', 'exports/book.pdf')
    return { updated: true }
})

removeDigitalItem() ​

Remove a digital delivery item from a variant by its ID.

ParameterTypeRequiredDescription
variantIdstringYesVariant ID
digitalItemIdstringYesDigital item ID

Returns: void.

js
k.api.post(() => {
    k.commerce.product.removeDigitalItem('variant-id', 'digital-item-id')
    return { removed: true }
})

addReview() ​

Submit a customer review for a product variant.

ParameterTypeRequiredDescription
modelNewProductReviewYesReview payload
model.customerIdstringYesCustomer ID
model.variantIdstringYesVariant ID
model.ratingnumberYesRating score
model.commentstringYesReview text
model.imagesstring[]NoImage URL list (note: currently ignored and not persisted by addReview(), nor returned by reviewList())

Note: Although images is declared on NewProductReview, the current KProduct.AddReview implementation does not persist images, and ProductReviewModel returned by reviewList() does not store or include them.

Returns: void.

js
k.api.post(() => {
    const customerId = k.commerce.customer.currentId || 'customer-id'
    const product = k.commerce.product.get(k.commerce.product.list()[0].id)
    const variantId = product.variants[0].id
    k.commerce.product.addReview({
        customerId,
        variantId,
        rating: 5,
        comment: 'Great quality',
        images: []
    })
    return k.commerce.product.reviewList(variantId)
})

reviewList() ​

List customer reviews for a product variant.

ParameterTypeRequiredDescription
variantIdstringYesVariant ID

Returns: ProductReviewModel[] (customerId, productId, variantId, rating, comment, createdAt).

js
k.api.get(() => {
    const product = k.commerce.product.get(k.commerce.product.list()[0].id)
    const reviews = k.commerce.product.reviewList(product.variants[0].id)
    return { count: reviews.length, items: reviews }
})

deleteVariant() ​

Delete a product variant.

ParameterTypeRequiredDescription
idstringYesVariant ID

Returns: void.

js
k.api.post(() => {
    k.commerce.product.deleteVariant('variant-id')
    return { deleted: true }
})

delete() ​

Delete a product.

ParameterTypeRequiredDescription
idstringYesProduct ID to delete

Returns: void.

js
k.api.post(() => {
    k.commerce.product.delete('product-id')
    return { deleted: true }
})

Structures ​

Product attributes ​

create() and createVariant() return the Kooboo.Sites.Commerce.Entities.Product entity directly (it does not include price, inventory, autoDelivery, variantImage, variants, or categories; call get(product.id) to retrieve ProductDetail):

PropertyDescriptionType
idProduct IDstring
titleProduct titlestring
descriptionProduct descriptionstring
attributesAttribute key-value pairs{ key: string, value: string }[]
activeWhether activeboolean
seoNameSEO namestring
featuredImageFeatured imagestring
imagesImage liststring[]
imageMetasImage metadata JSONstring
tagsTagsstring[]
isDigitalWhether digital productboolean
maxDownloadCountMaximum number of downloads (digital products)number | null
maxDownloadDayMaximum download days (digital products)number | null
variantOptionsVariant option definitionsVariantOption[]
customDataMultilingual and custom data mapRecord<string, Record<string, any>>
createdAtCreation timeDate
updatedAtUpdate timeDate

NewProduct properties ​

Input payload for create(value) (price, inventory, variantImage, autoDelivery, and active populate the automatically created first variant):

PropertyDescriptionType
titleProduct titlestring
descriptionProduct descriptionstring
attributesAttribute key-value pairs{ key: string, value: string }[]
activeWhether active (also applied to the default variant)boolean
seoNameSEO namestring
featuredImageFeatured imagestring
imagesImage liststring[]
tagsTagsstring[]
variantImageDefault variant imagestring
pricePrice (applied to the default variant)number
inventoryInventory count (applied to the default variant)number
isDigitalWhether digital productboolean
autoDeliveryWhether delivered automatically (applied to the default variant)boolean
maxDownloadCountMaximum number of downloads (digital products)number | null
maxDownloadDayMaximum download days (digital products)number | null

ProductDetail properties ​

Detailed view returned by get(seoNameOrId, options?) (also includes dynamic custom fields configured in backend settings):

PropertyDescriptionType
idProduct IDstring
titleProduct titlestring
descriptionProduct descriptionstring
featuredImageFeatured imagestring
activeWhether activeboolean
isDigitalWhether digital productboolean
priceLowest converted variant pricenumber
imagesImage liststring[]
imageMetasImage metadata JSONstring
seoNameSEO namestring
tagsTagsstring[]
attributesAttribute key-value pairs{ key: string, value: string }[]
variantsVariant listVariant[]
categoriesCategory listCategorySimple[]
variantOptionsLocalized variant option definitionsVariantOption[]
currencyResolved display currency info{ code: string, symbol: string, rate: number }

Variant properties ​

PropertyDescriptionType
idVariant IDstring
productIdProduct IDstring
createdAtCreation time (serialized date string at runtime via ToKscriptModel)string
updatedAtUpdate time (serialized date string at runtime via ToKscriptModel)string
skuSKU codestring
barcodeBarcodestring
pricePricenumber
inventoryInventory countnumber
weightWeightnumber
orderSort ordernumber
salesSales volumenumber
activeWhether enabledboolean
imageVariant imagestring
imageMetaVariant image metadata JSONstring
selectedOptionsOptions (e.g. color/size){ name: string, value: string }[]
digitalsDigital items listDigitalItem[]

DigitalItem property ​

PropertyDescriptionType
typeItem type'file' | 'text' | 'link'
nameDisplay namestring
valueContent (text / link / variant archive ID)string

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface KProduct {
  list(query?: KScript.Commerce.Models.ProductQueryParams): KScript.Commerce.Models.ProductSimple[];
  get(seoNameOrId: string, options?: KScript.Commerce.Models.GetProductOptions): KScript.Commerce.Models.ProductDetail;
  search(keyword: string, options?: KScript.Commerce.Models.SearchOptions): KScript.Commerce.Models.SearchResult;
  create(value: KScript.Commerce.Models.NewProduct): Kooboo.Sites.Commerce.Entities.Product;
  createVariant(productId: string, value: KScript.Commerce.Models.NewProductVariant): Kooboo.Sites.Commerce.Entities.Product;
  deleteVariant(id: string): void;
  delete(id: string): void;
  updateField(id: string, property: string, value: any, lang?: string): void;
  updateFields(id: string, updateFields: KScript.Commerce.Models.UpdateFieldParams[]): void;
  addCategory(id: string, categoryId: string): void;
  removeCategory(id: string, categoryId: string): void;
  updateVariantField(id: string, property: string, value: any, lang?: string): void;
  updateVariantFields(id: string, updateFields: KScript.Commerce.Models.UpdateFieldParams[]): void;
  getPriceDetail(variantId: string, options?: KScript.Commerce.Models.ProductPriceOptions): KScript.Commerce.Models.ProductPrice;
  addTextDigitalItem(variantId: string, name: string, text: string): void;
  addLinkDigitalItem(variantId: string, name: string, link: string): void;
  addFileDigitalItem(variantId: string, name: string, filePath: string): void;
  removeDigitalItem(variantId: string, digitalItemId: string): void;
  addReview(model: KScript.Commerce.Models.NewProductReview): void;
  reviewList(variantId: string): Kooboo.Sites.Commerce.DataStorage.ProductReviewModel[];
}

interface ProductQueryParams {
  categories: string[];
  includeSubCategory: boolean;
  includeOffline: boolean;
  currency: string;
  where: any;
}

interface Product {
  id: string;
  title: string;
  description: string;
  attributes: { key: string; value: string }[];
  active: boolean;
  seoName: string;
  featuredImage: string;
  images: string[];
  imageMetas: string;
  tags: string[];
  isDigital: boolean;
  maxDownloadCount?: number;
  maxDownloadDay?: number;
  variantOptions: Kooboo.Sites.Commerce.Entities.VariantOption[];
  customData: Record<string, Record<string, any>>;
  createdAt: Date;
  updatedAt: Date;
}

interface ProductSimple {
  id: string;
  title: string;
  featuredImage: string;
  images: string[];
  imageMetas: string;
  active: boolean;
  isDigital: boolean;
  price: number;
  seoName: string;
  tags: string[];
  attributes: any[];
  variants: Variant[];
  variantOptions: VariantOption[];
  currency: Kooboo.Sites.Commerce.Entities.Currency;
}

interface GetProductOptions {
  currency: string;
}

interface ProductDetail {
  id: string;
  title: string;
  description: string;
  featuredImage: string;
  active: boolean;
  isDigital: boolean;
  price: number;
  images: string[];
  imageMetas: string;
  seoName: string;
  tags: string[];
  attributes: KScript.KeyValue[];
  variants: Variant[];
  categories: CategorySimple[];
  variantOptions: VariantOption[];
  currency: Kooboo.Sites.Commerce.Entities.Currency;
}

interface SearchOptions {
  facetParams: FacetParam[];
  categories: string[];
  includeSubCategory: boolean;
  includeOffline: boolean;
  currency: string;
}

interface SearchResult {
  list: ProductSimple[];
  facets: FacetResult[];
}

interface NewProduct {
  title: string;
  description: string;
  attributes: KScript.KeyValue[];
  active: boolean;
  seoName: string;
  featuredImage: string;
  images: string[];
  tags: string[];
  variantImage: string;
  price: number;
  inventory: number;
  isDigital: boolean;
  autoDelivery: boolean;
  maxDownloadCount?: number;
  maxDownloadDay?: number;
}

interface NewProductVariant {
  barcode: string;
  sku: string;
  image: string;
  price: number;
  active: boolean;
  selectedOptions: Kooboo.Sites.Commerce.Entities.ProductVariantOption[];
  weight: number;
  inventory: number;
  tags: string[];
  autoDelivery: boolean;
}

interface ProductPriceOptions {
  customerId: string;
  currency: string;
}

interface ProductPrice {
  currency: Kooboo.Sites.Commerce.Entities.Currency;
  originalAmount: number;
  amount: number;
}

interface NewProductReview {
  customerId: string;
  variantId: string;
  rating: number;
  comment: string;
  images: string[];
}

interface ProductReviewModel {
  customerId: string;
  productId: string;
  variantId: string;
  rating: number;
  comment: string;
  createdAt: Date;
}

interface DigitalItem {
  /** 'file' 'text' 'link' */
  type: string;
  name: string;
  value: string;
}