import { ANY_FILTER_VALUE, APPROVED_VARIANT_SEPARATOR, FEED_COUNTRY_RE, type ISelectOption, LISTING_LABELS, MISSING_SETTINGS_TEXT, REASON_LABELS, } from '../../service/ai-shopping-feeds/ai-shopping-feeds.constants'; import type { BrandMode, IFeedGroup, IFeedProductRow, IFeedRules, IFeedSelectionRules, ProductMode, } from '../../service/ai-shopping-feeds/ai-shopping-feeds.interface'; type RuleListKey = | 'excluded_brands' | 'excluded_categories' | 'excluded_products' | 'parent_brands' | 'parent_products' | 'full_products' | 'approved_variants'; const RULE_LIST_KEYS: RuleListKey[] = [ 'excluded_brands', 'excluded_categories', 'excluded_products', 'parent_brands', 'parent_products', 'full_products', 'approved_variants', ]; const RULE_FIELD_KEYS: Array< 'item_per_variant' | 'new_products' | 'country' | 'seller_name' > = ['item_per_variant', 'new_products', 'country', 'seller_name']; /** * A rule list with one value set or cleared, sorted and without repeats. * * @param {string[]} values - The list. * @param {string} value - The value. * @param {boolean} isIn - Whether the value belongs in the list. * @return {string[]} The new list. */ export function withListValue( values: string[], value: string, isIn: boolean ): string[] { const rest = values.filter(entry => entry !== value); return (isIn ? [...rest, value] : rest).sort(); } /** * Whether a brand is named in a list, without case, as the agent compares brands. * * @param {string[]} values - The list. * @param {string} brand - The brand. * @return {boolean} True when named. */ function namesBrand(values: string[], brand: string): boolean { const folded = brand.toLowerCase(); return values.some(entry => entry.toLowerCase() === folded); } /** * How a brand is listed under the rules. * * @param {IFeedRules} rules - The rules. * @param {string} brand - The brand. * @return {BrandMode} Its mode. */ export function brandMode(rules: IFeedRules, brand: string): BrandMode { if (namesBrand(rules.excluded_brands, brand)) return 'excluded'; if (namesBrand(rules.parent_brands, brand)) return 'parent'; return 'default'; } /** * The rules with a brand's mode changed. * * @param {IFeedRules} rules - The rules. * @param {string} brand - The brand. * @param {BrandMode} mode - Its new mode. * @return {IFeedRules} The new rules. */ export function withBrandMode( rules: IFeedRules, brand: string, mode: BrandMode ): IFeedRules { const others = (values: string[]): string[] => values.filter(entry => entry.toLowerCase() !== brand.toLowerCase()); return { ...rules, excluded_brands: withListValue( others(rules.excluded_brands), brand, mode === 'excluded' ), parent_brands: withListValue( others(rules.parent_brands), brand, mode === 'parent' ), }; } /** * How a product is listed by its own rule. * * @param {IFeedRules} rules - The rules. * @param {string} productId - The product. * @return {ProductMode} Its mode. */ export function productMode(rules: IFeedRules, productId: string): ProductMode { if (rules.excluded_products.includes(productId)) return 'excluded'; if (rules.full_products.includes(productId)) return 'full'; if (rules.parent_products.includes(productId)) return 'parent'; return 'default'; } /** * The rules with a product's own rule changed; approved variations stay only while it is listed once. * * @param {IFeedRules} rules - The rules. * @param {string} productId - The product. * @param {ProductMode} mode - Its new mode. * @return {IFeedRules} The new rules. */ export function withProductMode( rules: IFeedRules, productId: string, mode: ProductMode ): IFeedRules { const prefix = `${productId}${APPROVED_VARIANT_SEPARATOR}`; const keepsVariants = mode === 'parent' || mode === 'default'; return { ...rules, excluded_products: withListValue( rules.excluded_products, productId, mode === 'excluded' ), full_products: withListValue( rules.full_products, productId, mode === 'full' ), parent_products: withListValue( rules.parent_products, productId, mode === 'parent' ), approved_variants: keepsVariants ? rules.approved_variants : rules.approved_variants.filter(entry => !entry.startsWith(prefix)), }; } /** * The rules with one list's value set or cleared. * * @param {IFeedRules} rules - The rules. * @param {RuleListKey} key - The list. * @param {string} value - The value. * @param {boolean} isIn - Whether it belongs in the list. * @return {IFeedRules} The new rules. */ export function withRuleValue( rules: IFeedRules, key: RuleListKey, value: string, isIn: boolean ): IFeedRules { return { ...rules, [key]: withListValue(rules[key], value, isIn) }; } /** * How a rule names one variation. * * @param {string} productId - The product. * @param {string} variantId - The variation. * @return {string} ``product:variation``. */ export function approvedVariantKey( productId: string, variantId: string ): string { return `${productId}${APPROVED_VARIANT_SEPARATOR}${variantId}`; } /** * The rules in one canonical text, to tell whether a draft is still the one previewed. * * @param {IFeedRules} rules - The rules. * @return {string} The text. */ export function rulesKey(rules: IFeedRules): string { const entries = Object.entries(rules).sort(([left], [right]) => left.localeCompare(right) ); const canonical = entries.map(([key, value]) => [ key, Array.isArray(value) ? [...value].sort() : value, ]); return JSON.stringify(canonical); } /** * The brands or categories whose name holds the search text. * * @param {IFeedGroup[]} groups - The brands or categories. * @param {string} query - The search text. * @return {IFeedGroup[]} The matches; every one for an empty search. */ export function filterGroups( groups: IFeedGroup[], query: string ): IFeedGroup[] { const needle = query.trim().toLowerCase(); if (!needle) return groups; return groups.filter(group => group.name.toLowerCase().includes(needle)); } /** * How many variations of a product the rules list on their own while it is listed once. * * @param {IFeedRules} rules - The rules. * @param {string} productId - The product. * @return {number} The count. */ export function approvedVariantCount( rules: IFeedRules, productId: string ): number { const prefix = `${productId}${APPROVED_VARIANT_SEPARATOR}`; return rules.approved_variants.filter(entry => entry.startsWith(prefix)) .length; } /** * How a product stands under the rules, in a few words: listed or not, and what decided it. * * @param {IFeedProductRow} product - The product as the search answered it. * @param {number} approvedCount - Its variations listed on their own. * @return {string} E.g. ``Left out · brand Acme`` or ``Every variation (3) · the default``. */ export function standingText( product: IFeedProductRow, approvedCount: number ): string { const variationCount = product.variants.length; const listing = product.listing === 'every' ? `${LISTING_LABELS.every} (${variationCount})` : LISTING_LABELS[product.listing]; const extra = product.listing === 'one' && approvedCount > 0 ? ` + ${approvedCount} on their own` : ''; const reason = product.reason_name ? `${REASON_LABELS[product.reason]} ${product.reason_name}` : REASON_LABELS[product.reason]; return `${listing}${extra} · ${reason}`; } /** * How many rule entries and settings differ between the saved rules and the draft. * * @param {IFeedRules} saved - The saved rules, or the starting rules before the first save. * @param {IFeedRules} draft - The rules as edited. * @return {number} Entries added or removed in each list, plus each setting changed. */ export function changedRuleCount(saved: IFeedRules, draft: IFeedRules): number { const listChanges = RULE_LIST_KEYS.reduce((total, key) => { const before = new Set(saved[key]); const after = new Set(draft[key]); const added = [...after].filter(value => !before.has(value)).length; const removed = [...before].filter(value => !after.has(value)).length; return total + added + removed; }, 0); return ( listChanges + RULE_FIELD_KEYS.filter(key => saved[key] !== draft[key]).length ); } /** * How many pages a search's results fill. * * @param {number} total - The products matching. * @param {number} pageSize - Products per page. * @return {number} At least one. */ export function pageCount(total: number, pageSize: number): number { return Math.max(1, Math.ceil(total / pageSize)); } /** * Whether the draft can be saved: a preview exists for exactly these rules and they name a seller. * * @param {IFeedRules} draft - The rules as edited. * @param {string | undefined} previewedRules - The rules the preview was made for, as ``rulesKey`` text. * @return {boolean} True when the save button can send them. */ export function canSaveDraft( draft: IFeedRules, previewedRules: string | undefined ): boolean { return ( Boolean(previewedRules) && previewedRules === rulesKey(draft) && draft.seller_name.trim().length > 0 ); } /** * A filter's choices: every brand or category first, then each one by name. * * @param {IFeedGroup[]} groups - The brands or categories. * @param {string} anyLabel - The label of the choice that keeps every one. * @return {ISelectOption[]} The choices. */ export function groupOptions( groups: IFeedGroup[], anyLabel: string ): ISelectOption[] { return [ { value: ANY_FILTER_VALUE, label: anyLabel }, ...groups.map(group => ({ value: group.id, label: group.name })), ]; } /** * A filter's value as the search sends it: empty for every brand or category. * * @param {string | null} value - The select's value. * @return {string} The filter. */ export function filterValue(value: string | null): string { return !value || value === ANY_FILTER_VALUE ? '' : value; } /** * The rules without the business name and country, which change no product's listing: typing in those fields * does not search again. * * @param {IFeedRules} rules - The rules. * @return {IFeedSelectionRules} The rule lists, the default and the new-products choice. */ export function selectionRules(rules: IFeedRules): IFeedSelectionRules { return { item_per_variant: rules.item_per_variant, excluded_brands: rules.excluded_brands, excluded_categories: rules.excluded_categories, excluded_products: rules.excluded_products, parent_brands: rules.parent_brands, parent_products: rules.parent_products, full_products: rules.full_products, approved_variants: rules.approved_variants, new_products: rules.new_products, }; } /** * What the draft still needs before it can be previewed: the business name and the country the files carry. * * @param {IFeedRules} rules - The rules as edited. * @return {string | null} What to add, null when nothing is missing. */ export function missingSettings(rules: IFeedRules): string | null { const hasName = rules.seller_name.trim().length > 0; const hasCountry = FEED_COUNTRY_RE.test(rules.country.trim()); return hasName && hasCountry ? null : MISSING_SETTINGS_TEXT; }