Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: filters that crashed or were typed wider than they are
Damian Legawiecf44a81c6fad9
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex fc594831bf..e64e53f5a4 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -97,8 +97,8 @@ import type {PriceListFilters,PriceListSort,PriceSort,- ProductFilters,- ProductSort,+ ProductSearchFilters,+ ProductSearchSort,ProductTypeFilters,ProductTypeSort,PromotionActionFilters,@@ -1199,7 +1199,7 @@ export class AdminClient {readonly products = {list: (- params?: ListParams<ProductFilters, ProductSort>,+ params?: ListParams<ProductSearchFilters, ProductSearchSort>,options?: RequestOptions,): Promise<PaginatedResponse<Product>> =>this.request<PaginatedResponse<Product>>('GET', '/products', {diff --git a/packages/admin-sdk/src/types/filters.generated.ts b/packages/admin-sdk/src/types/filters.generated.tsindex 674e0bc219..e0cba40f4e 100644--- a/packages/admin-sdk/src/types/filters.generated.ts+++ b/packages/admin-sdk/src/types/filters.generated.ts@@ -859,6 +859,41 @@ export type PriceListSort = Filter.SortKey<'catalog_id' | 'created_at' | 'ends_aexport interface ProductFilterExtensions {}export type ProductFilters = ProductFields+ & Filter.Prefixed<'categories_', CategoryFields & Filter.Prefixed<'parent_', CategoryFields>>+ & Filter.Prefixed<'channels_', ChannelFields>+ & Filter.Prefixed<'collections_', CollectionFields>+ & Filter.Prefixed<'default_variant_', VariantFields & Filter.Prefixed<'option_values_', OptionValueFields> & Filter.Prefixed<'prices_', PriceFields> & Filter.Prefixed<'product_', ProductFields> & Filter.Prefixed<'seller_', SellerFields> & Filter.Prefixed<'tax_category_', TaxCategoryFields>>+ & Filter.Prefixed<'labels_', TagFields>+ & Filter.Prefixed<'option_types_', OptionTypeFields>+ & Filter.Prefixed<'product_categories_', ProductCategoryFields>+ & Filter.Prefixed<'product_type_', ProductTypeFields & Filter.Prefixed<'option_types_', OptionTypeFields>>+ & Filter.Prefixed<'seller_', SellerFields>+ & Filter.Prefixed<'store_', StoreFields>+ & Filter.Prefixed<'tags_', TagFields>+ & Filter.Prefixed<'variants_', VariantFields & Filter.Prefixed<'option_values_', OptionValueFields> & Filter.Prefixed<'prices_', PriceFields> & Filter.Prefixed<'product_', ProductFields> & Filter.Prefixed<'seller_', SellerFields> & Filter.Prefixed<'tax_category_', TaxCategoryFields>>+ & Filter.OrFilters+ & {+ ascend_by_price?: boolean+ descend_by_price?: boolean+ in_categories?: string | string[]+ in_category?: string+ in_collection?: string+ in_stock?: boolean+ in_taxon?: string+ not_discontinued?: boolean+ out_of_stock?: boolean+ price_between?: [string | number, string | number]+ price_gte?: string | number+ price_lte?: string | number+ search?: string+ search_by_name?: string+ with_option_value_ids?: string | string[]+ }+ & ProductFilterExtensions++export type ProductSort = Filter.SortKey<'available_on' | 'created_at' | 'description' | 'discontinue_on' | 'id' | 'name' | 'seller_id' | 'slug' | 'status' | 'updated_at'>++export type ProductSearchFilters = ProductFields& Filter.Prefixed<'categories_', CategoryFields & Filter.Prefixed<'parent_', CategoryFields>>& Filter.Prefixed<'channels_', ChannelFields>& Filter.Prefixed<'collections_', CollectionFields>@@ -892,7 +927,7 @@ export type ProductFilters = ProductFields& Filter.CustomFieldFilters& ProductFilterExtensions-export type ProductSort = Filter.SortKey<'available_on' | 'best_selling' | 'created_at' | 'description' | 'discontinue_on' | 'id' | 'manual' | 'name' | 'price' | 'seller_id' | 'slug' | 'status' | 'updated_at' | `cf_${string}`>+export type ProductSearchSort = Filter.SortKey<'available_on' | 'best_selling' | 'created_at' | 'description' | 'discontinue_on' | 'id' | 'manual' | 'name' | 'price' | 'seller_id' | 'slug' | 'status' | 'updated_at' | `cf_${string}`>export interface ProductTypeFilterExtensions {}diff --git a/packages/sdk-core/scripts/generate-filters.ts b/packages/sdk-core/scripts/generate-filters.tsindex 83736a0c2c..616d537b43 100644--- a/packages/sdk-core/scripts/generate-filters.ts+++ b/packages/sdk-core/scripts/generate-filters.ts@@ -146,19 +146,19 @@ function associationsType(function render(spec: Spec): string {checkPredicates(spec.components?.['x-spree-filter-predicates'])const tables = spec.components?.['x-spree-filter-tables'] ?? {}- const roots = new Map<string, Omit<EndpointFilters, 'table'>>()-- // Endpoints listing the same records share one type; their sort fields and- // custom-field support combine.+ // Endpoints listing the same records share one type, keyed by what they+ // accept: the search-backed lists (custom fields, provider sorts) get their+ // own `<Table>Search…` types when plain lists of the same records exist too.+ const groups = new Map<string, { table: string; search: boolean; sortable: Set<string> }>()for (const operations of Object.values(spec.paths)) {const filters = operations.get?.['x-spree-filters']if (!filters) continue- const known = roots.get(filters.table)- roots.set(filters.table, {- sortable: [...new Set([...(known?.sortable ?? []), ...filters.sortable])].sort(),- custom_fields: Boolean(known?.custom_fields || filters.custom_fields),- })+ const search = Boolean(filters.custom_fields)+ const key = `${filters.table}:${search}`+ const group = groups.get(key) ?? { table: filters.table, search, sortable: new Set<string>() }+ for (const field of filters.sortable) group.sortable.add(field)+ groups.set(key, group)}const out: string[] = []@@ -167,24 +167,28 @@ function render(spec: Spec): string {out.push(`export type ${name}Fields = ${fieldsType(tables[name])}`, '')}- for (const [name, endpoint] of [...roots].sort(([a], [b]) => a.localeCompare(b))) {+ const sorted = [...groups.values()].sort(+ (a, b) => a.table.localeCompare(b.table) || Number(a.search) - Number(b.search),+ )+ for (const { table: name, search, sortable } of sorted) {const table = tables[name]+ const typeName = search && groups.has(`${name}:false`) ? `${name}Search` : nameconst parts = [`${name}Fields`, ...associationsType(tables, table, 0), 'Filter.OrFilters']const scopes = scopesType(table)if (scopes) parts.push(scopes)- if (endpoint.custom_fields) parts.push('Filter.CustomFieldFilters')+ if (search) parts.push('Filter.CustomFieldFilters')- const sortable = endpoint.sortable.length ? union(endpoint.sortable) : 'never'- const sort = endpoint.custom_fields- ? `Filter.SortKey<${sortable} | \`cf_\${string}\`>`- : `Filter.SortKey<${sortable}>`+ const fields = sortable.size ? union([...sortable].sort()) : 'never'+ const sort = search+ ? `Filter.SortKey<${fields} | \`cf_\${string}\`>`+ : `Filter.SortKey<${fields}>`// Filters an app adds through its own extensions, which the published// types cannot know about: `declare module` the SDK and add them here.- out.push(`export interface ${name}FilterExtensions {}`, '')+ if (typeName === name) out.push(`export interface ${name}FilterExtensions {}`, '')parts.push(`${name}FilterExtensions`)- out.push(`export type ${name}Filters = ${parts.join('\n & ')}`, '')- out.push(`export type ${name}Sort = ${sort}`, '')+ out.push(`export type ${typeName}Filters = ${parts.join('\n & ')}`, '')+ out.push(`export type ${typeName}Sort = ${sort}`, '')}// A namespace import, so no table name can collide with a building block.diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rbindex 4ed5265c38..a67bd38511 100644--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb@@ -398,12 +398,25 @@ module Spreeendend- # @param attribute [String, nil] a `*type` column of {#model_class}+ # A `*type` column of {#model_class}, or of a model it reaches through+ # its associations (`payment_method_type`), as the filter tables publish.+ #+ # @param attribute [String, nil]# @return [Proc, nil] shorthand → stored class name- def api_type_resolver(attribute)- return if attribute.nil? || !model_class.respond_to?(:api_type_resolver)+ def api_type_resolver(attribute, model = model_class, depth = 0)+ return if attribute.nil? || !model.respond_to?(:api_type_resolver)++ model.api_type_resolver(attribute) || begin+ return if depth >= Spree::Api::V3::FilterTable::MAX_DEPTH- model_class.api_type_resolver(attribute)+ model.reflect_on_all_associations.each do |reflection|+ next if reflection.polymorphic? || !attribute.start_with?("#{reflection.name}_")++ resolver = api_type_resolver(attribute.delete_prefix("#{reflection.name}_"), reflection.klass, depth + 1)+ return resolver if resolver+ end+ nil+ endend# Matches both prefixed-FK predicates (`product_id_in`, `tax_category_id_eq`)diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rbindex 79370184f2..3482e0a25c 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb@@ -18,6 +18,16 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :controlexpect(json_response['data']).to be_an(Array)expect(json_response['data'].length).to be >= 1end++ it "filters by the payment method's type short name" do+ api_type = payment.payment_method.class.api_type++ get :index, params: { order_id: order_with_payment.prefixed_id, q: { payment_method_type_eq: api_type } }, as: :json+ expect(json_response['data'].pluck('id')).to include(payment.prefixed_id)++ get :index, params: { order_id: order_with_payment.prefixed_id, q: { payment_method_type_eq: 'store_credit' } }, as: :json+ expect(json_response['data'].pluck('id')).not_to include(payment.prefixed_id)+ endenddescribe 'GET #show' dodiff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rbindex be734b2298..21c3859152 100644--- a/spree/core/app/models/concerns/spree/customer_methods.rb+++ b/spree/core/app/models/concerns/spree/customer_methods.rb@@ -223,10 +223,11 @@ module Spree}# Customers with standing for a company: members of the node or of any- # ancestor (see #standing_for?). Accepts a record, an id, or an array.- scope :with_standing_for_company, ->(companies) {+ # ancestor (see #standing_for?). Accepts records, ids, or an array; a+ # splat because Ransack passes each value of a list as its own argument.+ scope :with_standing_for_company, ->(*companies) {scoped = Spree::Current.store&.companies || Spree::Company.none- nodes = Array.wrap(companies).filter_map do |company|+ nodes = companies.flatten.filter_map do |company|company.is_a?(Spree::Company) ? company : scoped.find_by_param(company)endnext none if nodes.empty?diff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex 2239a36605..bfb5140aaf 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -110,6 +110,9 @@ module Spree## Spree::Product.in_taxon(taxon).count(distinct: true)scope :in_taxon, ->(taxon) {+ taxon = Spree::Category.find_by_prefix_id(taxon) if taxon.is_a?(String)+ next none if taxon.nil?+joins(:product_categories).where("#{Spree::ProductCategory.table_name}.category_id" => taxon.cached_self_and_descendants_ids).distinct}diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rbindex a69c782559..0476d59f2d 100644--- a/spree/core/app/models/spree/seller.rb+++ b/spree/core/app/models/spree/seller.rb@@ -44,7 +44,7 @@ module Spree# The storefront lists approved sellers only, and a seller's contact# address is back-office data.self.whitelisted_ransackable_attributes = %w[status contact_email]- self.private_ransackable_attributes = { store: %w[status contact_email] }+ self.private_ransackable_attributes = { store: %w[status contact_email], seller: %w[status contact_email] }# Who remits consumer tax on this seller's sales. `seller` means they are# merchant of record; `platform` is the marketplace-facilitator case, anddiff --git a/spree/core/spec/models/spree/customer_standing_scope_spec.rb b/spree/core/spec/models/spree/customer_standing_scope_spec.rbindex 4bb28e0a1c..74ce9d1342 100644--- a/spree/core/spec/models/spree/customer_standing_scope_spec.rb+++ b/spree/core/spec/models/spree/customer_standing_scope_spec.rb@@ -49,6 +49,8 @@ RSpec.describe 'Spree.customer_class.with_standing_for_company' doexpect(matches).to include(division_buyer, group_buyer, globex_buyer)expect(matches).not_to include(outsider)+ # Ransack passes each value of a list filter as its own argument.+ expect(Spree.customer_class.with_standing_for_company(child.prefixed_id, other_root.prefixed_id)).to match_array(matches)endit 'returns nothing for a blank or unknown company' dodiff --git a/spree/core/spec/models/spree/product/scopes_spec.rb b/spree/core/spec/models/spree/product/scopes_spec.rbindex f405df46e7..0321d94b00 100644--- a/spree/core/spec/models/spree/product/scopes_spec.rb+++ b/spree/core/spec/models/spree/product/scopes_spec.rb@@ -59,6 +59,11 @@ describe 'Product scopes', type: :model doexpect(Spree::Product.in_taxon(@parent_category).to_a.size).to eq(1)end+ it 'calling Product.in_taxon with a prefixed ID, as a filter does' do+ expect(Spree::Product.in_taxon(@parent_category.prefixed_id)).to include(product)+ expect(Spree::Product.in_taxon('ctg_unknown')).to be_empty+ end+context 'returns correct products for category' dolet(:other_category) { create(:category, products: [product]) }let!(:product_2) { create(:product, categories: [@child_category, other_category]) }