content
stringlengths 28
1.34M
|
---|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { InitialData } from '@vendure/core/dist/data-import/index';
export const initialData: InitialData = {
defaultLanguage: LanguageCode.en,
defaultZone: 'Europe',
taxRates: [
{ name: 'Standard Tax', percentage: 20 },
{ name: 'Reduced Tax', percentage: 10 },
{ name: 'Zero Tax', percentage: 0 },
],
shippingMethods: [
{ name: 'Standard Shipping', price: 500 },
{ name: 'Express Shipping', price: 1000 },
],
paymentMethods: [],
countries: [
{ name: 'Australia', code: 'AU', zone: 'Oceania' },
{ name: 'Austria', code: 'AT', zone: 'Europe' },
{ name: 'Canada', code: 'CA', zone: 'Americas' },
{ name: 'China', code: 'CN', zone: 'Asia' },
{ name: 'South Africa', code: 'ZA', zone: 'Africa' },
{ name: 'United Kingdom', code: 'GB', zone: 'Europe' },
{ name: 'United States of America', code: 'US', zone: 'Americas' },
],
collections: [
{
name: 'Plants',
filters: [
{ code: 'facet-value-filter', args: { facetValueNames: ['plants'], containsAny: false } },
],
},
],
};
|
import { mergeConfig } from '@vendure/core';
import {
MysqlInitializer,
PostgresInitializer,
registerInitializer,
SqljsInitializer,
testConfig as defaultTestConfig,
} from '@vendure/testing';
import fs from 'fs-extra';
import path from 'path';
import { DataSourceOptions } from 'typeorm';
import { fileURLToPath } from 'url';
import { getPackageDir } from './get-package-dir';
declare global {
namespace NodeJS {
interface Global {
e2eServerPortsUsed: number[];
}
}
}
/**
* We use a relatively long timeout on the initial beforeAll() function of the
* e2e tests because on the first run (and always in CI) the sqlite databases
* need to be generated, which can take a while.
*/
export const TEST_SETUP_TIMEOUT_MS = process.env.E2E_DEBUG ? 1800 * 1000 : 120000;
const packageDir = getPackageDir();
registerInitializer('sqljs', new SqljsInitializer(path.join(packageDir, '__data__')));
registerInitializer('postgres', new PostgresInitializer());
registerInitializer('mysql', new MysqlInitializer());
registerInitializer('mariadb', new MysqlInitializer());
export const testConfig = () => {
// @ts-ignore
const portsFile = fileURLToPath(new URL('ports.json', import.meta.url));
fs.ensureFileSync(portsFile);
let usedPorts: number[];
try {
usedPorts = fs.readJSONSync(portsFile) ?? [3010];
} catch (e: any) {
usedPorts = [3010];
}
const nextPort = Math.max(...usedPorts) + 1;
usedPorts.push(nextPort);
if (100 < usedPorts.length) {
// reset the used ports after it gets 100 entries long
usedPorts = [3010];
}
fs.writeJSONSync(portsFile, usedPorts);
return mergeConfig(defaultTestConfig, {
apiOptions: {
port: nextPort,
},
importExportOptions: {
importAssetsDir: path.join(packageDir, 'fixtures/assets'),
},
dbConnectionOptions: getDbConfig(),
});
};
function getDbConfig(): DataSourceOptions {
const dbType = process.env.DB || 'sqljs';
switch (dbType) {
case 'postgres':
return {
synchronize: true,
type: 'postgres',
host: '127.0.0.1',
port: process.env.CI ? +(process.env.E2E_POSTGRES_PORT || 5432) : 5432,
username: 'admin',
password: 'secret',
};
case 'mariadb':
return {
synchronize: true,
type: 'mariadb',
host: '127.0.0.1',
port: process.env.CI ? +(process.env.E2E_MARIADB_PORT || 3306) : 3306,
username: 'root',
password: '',
};
case 'mysql':
return {
synchronize: true,
type: 'mysql',
host: '127.0.0.1',
port: process.env.CI ? +(process.env.E2E_MYSQL_PORT || 3306) : 3306,
username: 'root',
password: '',
};
case 'sqljs':
default:
return defaultTestConfig.dbConnectionOptions;
}
}
|
import path from 'path';
import swc from 'unplugin-swc';
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['**/*.bench.ts'],
/**
* For local debugging of the e2e tests, we set a very long timeout value otherwise tests will
* automatically fail for going over the 5 second default timeout.
*/
testTimeout: process.env.E2E_DEBUG ? 1800 * 1000 : process.env.CI ? 30 * 1000 : 15 * 1000,
// threads: false,
// singleThread: true,
// reporters: ['verbose'],
typecheck: {
tsconfig: path.join(__dirname, 'tsconfig.e2e.json'),
},
// In jobs-queue.e2e-spec.ts, we use `it.only()` for sqljs, so we need this
// set to true to avoid failures in CI.
allowOnly: true,
},
plugins: [
// SWC required to support decorators used in test plugins
// See https://github.com/vitest-dev/vitest/issues/708#issuecomment-1118628479
// Vite plugin
swc.vite({
jsc: {
transform: {
// See https://github.com/vendure-ecommerce/vendure/issues/2099
useDefineForClassFields: false,
},
},
}),
],
});
|
/* eslint-disable no-console */
import { execSync, spawn } from 'child_process';
import fs from 'fs-extra';
import path from 'path';
const compiledUiDir = path.join(__dirname, 'lib/admin-ui');
console.log('Building admin-ui from source...');
fs.removeSync(compiledUiDir);
const adminUiDir = path.join(__dirname, '../admin-ui');
const buildProcess = spawn('npm', ['run', 'build:app', `--prefix "${adminUiDir}"`], {
cwd: adminUiDir,
shell: true,
stdio: 'inherit',
});
buildProcess.on('close', code => {
if (code === 0) {
fs.copySync(path.join(__dirname, '../admin-ui/dist'), compiledUiDir);
} else {
console.log('Could not build!');
process.exitCode = 1;
}
});
|
export * from './src/plugin';
|
import { LanguageCode } from '@vendure/core';
import path from 'path';
export const DEFAULT_APP_PATH = path.join(__dirname, '../admin-ui');
export const loggerCtx = 'AdminUiPlugin';
export const defaultLanguage = LanguageCode.en;
export const defaultLocale = undefined;
export const defaultAvailableLanguages = [
LanguageCode.he,
LanguageCode.ar,
LanguageCode.de,
LanguageCode.en,
LanguageCode.es,
LanguageCode.pl,
LanguageCode.zh_Hans,
LanguageCode.zh_Hant,
LanguageCode.pt_BR,
LanguageCode.pt_PT,
LanguageCode.cs,
LanguageCode.fr,
LanguageCode.ru,
LanguageCode.uk,
LanguageCode.it,
LanguageCode.fa,
LanguageCode.ne,
LanguageCode.hr,
LanguageCode.sv,
LanguageCode.nb,
];
export const defaultAvailableLocales = [
'AF',
'AL',
'DZ',
'AS',
'AD',
'AO',
'AI',
'AQ',
'AG',
'AR',
'AM',
'AW',
'AU',
'AT',
'AZ',
'BS',
'BH',
'BD',
'BB',
'BY',
'BE',
'BZ',
'BJ',
'BM',
'BT',
'BO',
'BQ',
'BA',
'BW',
'BV',
'BR',
'IO',
'BN',
'BG',
'BF',
'BI',
'CV',
'KH',
'CM',
'CA',
'KY',
'CF',
'TD',
'CL',
'CN',
'CX',
'CC',
'CO',
'KM',
'CD',
'CG',
'CK',
'CR',
'HR',
'CU',
'CW',
'CY',
'CZ',
'CI',
'DK',
'DJ',
'DM',
'DO',
'EC',
'EG',
'SV',
'GQ',
'ER',
'EE',
'SZ',
'ET',
'FK',
'FO',
'FJ',
'FI',
'FR',
'GF',
'PF',
'TF',
'GA',
'GM',
'GE',
'DE',
'GH',
'GI',
'GR',
'GL',
'GD',
'GP',
'GU',
'GT',
'GG',
'GN',
'GW',
'GY',
'HT',
'HM',
'VA',
'HN',
'HK',
'HU',
'IS',
'IN',
'ID',
'IR',
'IQ',
'IE',
'IM',
'IL',
'IT',
'JM',
'JP',
'JE',
'JO',
'KZ',
'KE',
'KI',
'KP',
'KR',
'KW',
'KG',
'LA',
'LV',
'LB',
'LS',
'LR',
'LY',
'LI',
'LT',
'LU',
'MO',
'MG',
'MW',
'MY',
'MV',
'ML',
'MT',
'MH',
'MQ',
'MR',
'MU',
'YT',
'MX',
'FM',
'MD',
'MC',
'MN',
'ME',
'MS',
'MA',
'MZ',
'MM',
'NA',
'NR',
'NP',
'NL',
'NC',
'NZ',
'NI',
'NE',
'NG',
'NU',
'NF',
'MK',
'MP',
'NO',
'OM',
'PK',
'PW',
'PS',
'PA',
'PG',
'PY',
'PE',
'PH',
'PN',
'PL',
'PT',
'PR',
'QA',
'RO',
'RU',
'RW',
'RE',
'BL',
'SH',
'KN',
'LC',
'MF',
'PM',
'VC',
'WS',
'SM',
'ST',
'SA',
'SN',
'RS',
'SC',
'SL',
'SG',
'SX',
'SK',
'SI',
'SB',
'SO',
'ZA',
'GS',
'SS',
'ES',
'LK',
'SD',
'SR',
'SJ',
'SE',
'CH',
'SY',
'TW',
'TJ',
'TZ',
'TH',
'TL',
'TG',
'TK',
'TO',
'TT',
'TN',
'TR',
'TM',
'TC',
'TV',
'UG',
'UA',
'AE',
'GB',
'UM',
'US',
'UY',
'UZ',
'VU',
'VE',
'VN',
'VG',
'VI',
'WF',
'EH',
'YE',
'ZM',
'ZW',
'AX',
];
|
import { MiddlewareConsumer, NestModule } from '@nestjs/common';
import {
DEFAULT_AUTH_TOKEN_HEADER_KEY,
DEFAULT_CHANNEL_TOKEN_KEY,
} from '@vendure/common/lib/shared-constants';
import {
AdminUiAppConfig,
AdminUiAppDevModeConfig,
AdminUiConfig,
Type,
} from '@vendure/common/lib/shared-types';
import {
ConfigService,
createProxyHandler,
Logger,
PluginCommonModule,
ProcessContext,
registerPluginStartupMessage,
VendurePlugin,
} from '@vendure/core';
import express from 'express';
import fs from 'fs-extra';
import path from 'path';
import { adminApiExtensions } from './api/api-extensions';
import { MetricsResolver } from './api/metrics.resolver';
import {
defaultAvailableLanguages,
defaultLanguage,
defaultLocale,
DEFAULT_APP_PATH,
loggerCtx,
defaultAvailableLocales,
} from './constants';
import { MetricsService } from './service/metrics.service';
/**
* @description
* Configuration options for the {@link AdminUiPlugin}.
*
* @docsCategory core plugins/AdminUiPlugin
*/
export interface AdminUiPluginOptions {
/**
* @description
* The route to the Admin UI.
*
* Note: If you are using the {@link compileUiExtensions} function to compile a custom version of the Admin UI, then
* the route should match the `baseHref` option passed to that function. The default value of `baseHref` is `/admin/`,
* so it only needs to be changed if you set this `route` option to something other than `"admin"`.
*/
route: string;
/**
* @description
* The port on which the server will listen. This port will be proxied by the AdminUiPlugin to the same port that
* the Vendure server is running on.
*/
port: number;
/**
* @description
* The hostname of the server serving the static admin ui files.
*
* @default 'localhost'
*/
hostname?: string;
/**
* @description
* By default, the AdminUiPlugin comes bundles with a pre-built version of the
* Admin UI. This option can be used to override this default build with a different
* version, e.g. one pre-compiled with one or more ui extensions.
*/
app?: AdminUiAppConfig | AdminUiAppDevModeConfig;
/**
* @description
* Allows the contents of the `vendure-ui-config.json` file to be set, e.g.
* for specifying the Vendure GraphQL API host, available UI languages, etc.
*/
adminUiConfig?: Partial<AdminUiConfig>;
}
/**
* @description
* This plugin starts a static server for the Admin UI app, and proxies it via the `/admin/` path of the main Vendure server.
*
* The Admin UI allows you to administer all aspects of your store, from inventory management to order tracking. It is the tool used by
* store administrators on a day-to-day basis for the management of the store.
*
* ## Installation
*
* `yarn add \@vendure/admin-ui-plugin`
*
* or
*
* `npm install \@vendure/admin-ui-plugin`
*
* @example
* ```ts
* import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
*
* const config: VendureConfig = {
* // Add an instance of the plugin to the plugins array
* plugins: [
* AdminUiPlugin.init({ port: 3002 }),
* ],
* };
* ```
*
* ## Metrics
*
* This plugin also defines a `metricSummary` query which is used by the Admin UI to display the order metrics on the dashboard.
*
* If you are building a stand-alone version of the Admin UI app, and therefore don't need this plugin to server the Admin UI,
* you can still use the `metricSummary` query by adding the `AdminUiPlugin` to the `plugins` array, but without calling the `init()` method:
*
* @example
* ```ts
* import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
*
* const config: VendureConfig = {
* plugins: [
* AdminUiPlugin, // <-- no call to .init()
* ],
* // ...
* };
* ```
*
* @docsCategory core plugins/AdminUiPlugin
*/
@VendurePlugin({
imports: [PluginCommonModule],
adminApiExtensions: {
schema: adminApiExtensions,
resolvers: [MetricsResolver],
},
providers: [MetricsService],
compatibility: '^2.0.0',
})
export class AdminUiPlugin implements NestModule {
private static options: AdminUiPluginOptions | undefined;
constructor(private configService: ConfigService, private processContext: ProcessContext) {}
/**
* @description
* Set the plugin options
*/
static init(options: AdminUiPluginOptions): Type<AdminUiPlugin> {
this.options = options;
return AdminUiPlugin;
}
async configure(consumer: MiddlewareConsumer) {
if (this.processContext.isWorker) {
return;
}
if (!AdminUiPlugin.options) {
Logger.info(
`AdminUiPlugin's init() method was not called. The Admin UI will not be served.`,
loggerCtx,
);
return;
}
const { app, hostname, route, adminUiConfig } = AdminUiPlugin.options;
const adminUiAppPath = AdminUiPlugin.isDevModeApp(app)
? path.join(app.sourcePath, 'src')
: (app && app.path) || DEFAULT_APP_PATH;
const adminUiConfigPath = path.join(adminUiAppPath, 'vendure-ui-config.json');
const indexHtmlPath = path.join(adminUiAppPath, 'index.html');
const overwriteConfig = async () => {
const uiConfig = this.getAdminUiConfig(adminUiConfig);
await this.overwriteAdminUiConfig(adminUiConfigPath, uiConfig);
await this.overwriteBaseHref(indexHtmlPath, route);
};
let port: number;
if (AdminUiPlugin.isDevModeApp(app)) {
port = app.port;
} else {
port = AdminUiPlugin.options.port;
}
if (AdminUiPlugin.isDevModeApp(app)) {
Logger.info('Creating admin ui middleware (dev mode)', loggerCtx);
consumer
.apply(
createProxyHandler({
hostname,
port,
route,
label: 'Admin UI',
basePath: route,
}),
)
.forRoutes(route);
consumer
.apply(
createProxyHandler({
hostname,
port,
route: 'sockjs-node',
label: 'Admin UI live reload',
basePath: 'sockjs-node',
}),
)
.forRoutes('sockjs-node');
Logger.info('Compiling Admin UI app in development mode', loggerCtx);
app.compile().then(
() => {
Logger.info('Admin UI compiling and watching for changes...', loggerCtx);
},
(err: any) => {
Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
},
);
await overwriteConfig();
} else {
Logger.info('Creating admin ui middleware (prod mode)', loggerCtx);
consumer.apply(await this.createStaticServer(app)).forRoutes(route);
if (app && typeof app.compile === 'function') {
Logger.info('Compiling Admin UI app in production mode...', loggerCtx);
app.compile()
.then(overwriteConfig)
.then(
() => {
Logger.info('Admin UI successfully compiled', loggerCtx);
},
(err: any) => {
Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
},
);
} else {
await overwriteConfig();
}
}
registerPluginStartupMessage('Admin UI', route);
}
private async createStaticServer(app?: AdminUiAppConfig) {
const adminUiAppPath = (app && app.path) || DEFAULT_APP_PATH;
const adminUiServer = express.Router();
adminUiServer.use(express.static(adminUiAppPath));
adminUiServer.use((req, res) => {
res.sendFile(path.join(adminUiAppPath, 'index.html'));
});
return adminUiServer;
}
/**
* Takes an optional AdminUiConfig provided in the plugin options, and returns a complete
* config object for writing to disk.
*/
private getAdminUiConfig(partialConfig?: Partial<AdminUiConfig>): AdminUiConfig {
const { authOptions, apiOptions } = this.configService;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const options = AdminUiPlugin.options!;
const propOrDefault = <Prop extends keyof AdminUiConfig>(
prop: Prop,
defaultVal: AdminUiConfig[Prop],
isArray: boolean = false,
): AdminUiConfig[Prop] => {
if (isArray) {
const isValidArray = !!partialConfig
? !!((partialConfig as AdminUiConfig)[prop] as any[])?.length
: false;
return !!partialConfig && isValidArray ? (partialConfig as AdminUiConfig)[prop] : defaultVal;
} else {
return partialConfig ? (partialConfig as AdminUiConfig)[prop] || defaultVal : defaultVal;
}
};
return {
adminApiPath: propOrDefault('adminApiPath', apiOptions.adminApiPath),
apiHost: propOrDefault('apiHost', 'auto'),
apiPort: propOrDefault('apiPort', 'auto'),
tokenMethod: propOrDefault(
'tokenMethod',
authOptions.tokenMethod === 'bearer' ? 'bearer' : 'cookie',
),
authTokenHeaderKey: propOrDefault(
'authTokenHeaderKey',
authOptions.authTokenHeaderKey || DEFAULT_AUTH_TOKEN_HEADER_KEY,
),
channelTokenKey: propOrDefault(
'channelTokenKey',
apiOptions.channelTokenKey || DEFAULT_CHANNEL_TOKEN_KEY,
),
defaultLanguage: propOrDefault('defaultLanguage', defaultLanguage),
defaultLocale: propOrDefault('defaultLocale', defaultLocale),
availableLanguages: propOrDefault('availableLanguages', defaultAvailableLanguages, true),
availableLocales: propOrDefault('availableLocales', defaultAvailableLocales, true),
loginUrl: options.adminUiConfig?.loginUrl,
brand: options.adminUiConfig?.brand,
hideVendureBranding: propOrDefault(
'hideVendureBranding',
options.adminUiConfig?.hideVendureBranding || false,
),
hideVersion: propOrDefault('hideVersion', options.adminUiConfig?.hideVersion || false),
loginImageUrl: options.adminUiConfig?.loginImageUrl,
cancellationReasons: propOrDefault('cancellationReasons', undefined),
};
}
/**
* Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
* the server admin API.
*/
private async overwriteAdminUiConfig(adminUiConfigPath: string, config: AdminUiConfig) {
try {
const content = await this.pollForFile(adminUiConfigPath);
} catch (e: any) {
Logger.error(e.message, loggerCtx);
throw e;
}
try {
await fs.writeFile(adminUiConfigPath, JSON.stringify(config, null, 2));
} catch (e: any) {
throw new Error(
'[AdminUiPlugin] Could not write vendure-ui-config.json file:\n' + JSON.stringify(e.message),
);
}
Logger.verbose('Applied configuration to vendure-ui-config.json file', loggerCtx);
}
/**
* Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
* the server admin API.
*/
private async overwriteBaseHref(indexHtmlPath: string, baseHref: string) {
let indexHtmlContent: string;
try {
indexHtmlContent = await this.pollForFile(indexHtmlPath);
} catch (e: any) {
Logger.error(e.message, loggerCtx);
throw e;
}
try {
const withCustomBaseHref = indexHtmlContent.replace(
/<base href=".+"\s*\/>/,
`<base href="/${baseHref}/" />`,
);
await fs.writeFile(indexHtmlPath, withCustomBaseHref);
} catch (e: any) {
throw new Error('[AdminUiPlugin] Could not write index.html file:\n' + JSON.stringify(e.message));
}
Logger.verbose(`Applied baseHref "/${baseHref}/" to index.html file`, loggerCtx);
}
/**
* It might be that the ui-devkit compiler has not yet copied the config
* file to the expected location (particularly when running in watch mode),
* so polling is used to check multiple times with a delay.
*/
private async pollForFile(filePath: string) {
const maxRetries = 10;
const retryDelay = 200;
let attempts = 0;
const pause = () => new Promise(resolve => setTimeout(resolve, retryDelay));
while (attempts < maxRetries) {
try {
Logger.verbose(`Checking for admin ui file: ${filePath}`, loggerCtx);
const configFileContent = await fs.readFile(filePath, 'utf-8');
return configFileContent;
} catch (e: any) {
attempts++;
Logger.verbose(
`Unable to locate admin ui file: ${filePath} (attempt ${attempts})`,
loggerCtx,
);
}
await pause();
}
throw new Error(`Unable to locate admin ui file: ${filePath}`);
}
private static isDevModeApp(
app?: AdminUiAppConfig | AdminUiAppDevModeConfig,
): app is AdminUiAppDevModeConfig {
if (!app) {
return false;
}
return !!(app as AdminUiAppDevModeConfig).sourcePath;
}
}
|
import { ID } from '@vendure/core';
export type MetricSummary = {
interval: MetricInterval;
type: MetricType;
title: string;
entries: MetricSummaryEntry[];
};
export enum MetricType {
OrderCount = 'OrderCount',
OrderTotal = 'OrderTotal',
AverageOrderValue = 'AverageOrderValue',
}
export enum MetricInterval {
Daily = 'Daily',
}
export type MetricSummaryEntry = {
label: string;
value: number;
};
export interface MetricSummaryInput {
interval: MetricInterval;
types: MetricType[];
refresh?: boolean;
}
|
import gql from 'graphql-tag';
export const adminApiExtensions = gql`
type MetricSummary {
interval: MetricInterval!
type: MetricType!
title: String!
entries: [MetricSummaryEntry!]!
}
enum MetricInterval {
Daily
}
enum MetricType {
OrderCount
OrderTotal
AverageOrderValue
}
type MetricSummaryEntry {
label: String!
value: Float!
}
input MetricSummaryInput {
interval: MetricInterval!
types: [MetricType!]!
refresh: Boolean
}
extend type Query {
"""
Get metrics for the given interval and metric types.
"""
metricSummary(input: MetricSummaryInput): [MetricSummary!]!
}
`;
|
import { Args, Query, Resolver } from '@nestjs/graphql';
import { Allow, Ctx, Permission, RequestContext } from '@vendure/core';
import { MetricsService } from '../service/metrics.service';
import { MetricSummary, MetricSummaryInput } from '../types';
@Resolver()
export class MetricsResolver {
constructor(private service: MetricsService) {}
@Query()
@Allow(Permission.ReadOrder)
async metricSummary(
@Ctx() ctx: RequestContext,
@Args('input') input: MetricSummaryInput,
): Promise<MetricSummary[]> {
return this.service.getMetrics(ctx, input);
}
}
|
import { RequestContext } from '@vendure/core';
import { MetricData } from '../service/metrics.service';
import { MetricInterval, MetricSummaryEntry, MetricType } from '../types';
/**
* Calculate your metric data based on the given input.
* Be careful with heavy queries and calculations,
* as this function is executed everytime a user views its dashboard
*
*/
export interface MetricCalculation {
type: MetricType;
getTitle(ctx: RequestContext): string;
calculateEntry(ctx: RequestContext, interval: MetricInterval, data: MetricData): MetricSummaryEntry;
}
export function getMonthName(monthNr: number): string {
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return monthNames[monthNr];
}
/**
* Calculates the average order value per month/week
*/
export class AverageOrderValueMetric implements MetricCalculation {
readonly type = MetricType.AverageOrderValue;
getTitle(ctx: RequestContext): string {
return 'average-order-value';
}
calculateEntry(ctx: RequestContext, interval: MetricInterval, data: MetricData): MetricSummaryEntry {
const label = data.date.toISOString();
if (!data.orders.length) {
return {
label,
value: 0,
};
}
const total = data.orders.map(o => o.totalWithTax).reduce((_total, current) => _total + current);
const average = Math.round(total / data.orders.length);
return {
label,
value: average,
};
}
}
/**
* Calculates number of orders
*/
export class OrderCountMetric implements MetricCalculation {
readonly type = MetricType.OrderCount;
getTitle(ctx: RequestContext): string {
return 'order-count';
}
calculateEntry(ctx: RequestContext, interval: MetricInterval, data: MetricData): MetricSummaryEntry {
const label = data.date.toISOString();
return {
label,
value: data.orders.length,
};
}
}
/**
* Calculates order total
*/
export class OrderTotalMetric implements MetricCalculation {
readonly type = MetricType.OrderTotal;
getTitle(ctx: RequestContext): string {
return 'order-totals';
}
calculateEntry(ctx: RequestContext, interval: MetricInterval, data: MetricData): MetricSummaryEntry {
const label = data.date.toISOString();
return {
label,
value: data.orders.map(o => o.totalWithTax).reduce((_total, current) => _total + current, 0),
};
}
}
|
import { Injectable } from '@nestjs/common';
import { assertNever } from '@vendure/common/lib/shared-utils';
import {
ConfigService,
Logger,
Order,
RequestContext,
TransactionalConnection,
TtlCache,
} from '@vendure/core';
import {
Duration,
endOfDay,
getDayOfYear,
getISOWeek,
getMonth,
setDayOfYear,
startOfDay,
sub,
} from 'date-fns';
import {
AverageOrderValueMetric,
MetricCalculation,
OrderCountMetric,
OrderTotalMetric,
} from '../config/metrics-strategies';
import { loggerCtx } from '../constants';
import { MetricInterval, MetricSummary, MetricSummaryEntry, MetricSummaryInput } from '../types';
export type MetricData = {
date: Date;
orders: Order[];
};
@Injectable()
export class MetricsService {
private cache = new TtlCache<string, MetricSummary[]>({ ttl: 1000 * 60 * 60 * 24 });
metricCalculations: MetricCalculation[];
constructor(private connection: TransactionalConnection, private configService: ConfigService) {
this.metricCalculations = [
new AverageOrderValueMetric(),
new OrderCountMetric(),
new OrderTotalMetric(),
];
}
async getMetrics(
ctx: RequestContext,
{ interval, types, refresh }: MetricSummaryInput,
): Promise<MetricSummary[]> {
// Set 23:59:59.999 as endDate
const endDate = endOfDay(new Date());
// Check if we have cached result
const cacheKey = JSON.stringify({
endDate,
types: types.sort(),
interval,
channel: ctx.channel.token,
});
const cachedMetricList = this.cache.get(cacheKey);
if (cachedMetricList && refresh !== true) {
Logger.verbose(`Returning cached metrics for channel ${ctx.channel.token}`, loggerCtx);
return cachedMetricList;
}
// No cache, calculating new metrics
Logger.verbose(
`No cache hit, calculating ${interval} metrics until ${endDate.toISOString()} for channel ${
ctx.channel.token
} for all orders`,
loggerCtx,
);
const data = await this.loadData(ctx, interval, endDate);
const metrics: MetricSummary[] = [];
for (const type of types) {
const metric = this.metricCalculations.find(m => m.type === type);
if (!metric) {
continue;
}
// Calculate entry (month or week)
const entries: MetricSummaryEntry[] = [];
data.forEach(dataPerTick => {
entries.push(metric.calculateEntry(ctx, interval, dataPerTick));
});
// Create metric with calculated entries
metrics.push({
interval,
title: metric.getTitle(ctx),
type: metric.type,
entries,
});
}
this.cache.set(cacheKey, metrics);
return metrics;
}
async loadData(
ctx: RequestContext,
interval: MetricInterval,
endDate: Date,
): Promise<Map<number, MetricData>> {
let nrOfEntries: number;
let backInTimeAmount: Duration;
const orderRepo = this.connection.getRepository(ctx, Order);
// What function to use to get the current Tick of a date (i.e. the week or month number)
let getTickNrFn: typeof getMonth | typeof getISOWeek;
let maxTick: number;
switch (interval) {
case MetricInterval.Daily: {
nrOfEntries = 30;
backInTimeAmount = { days: nrOfEntries };
getTickNrFn = getDayOfYear;
maxTick = 365;
break;
}
default:
assertNever(interval);
}
const startDate = startOfDay(sub(endDate, backInTimeAmount));
const startTick = getTickNrFn(startDate);
// Get orders in a loop until we have all
let skip = 0;
const take = 1000;
let hasMoreOrders = true;
const orders: Order[] = [];
while (hasMoreOrders) {
const query = orderRepo
.createQueryBuilder('order')
.leftJoin('order.channels', 'orderChannel')
.where('orderChannel.id=:channelId', { channelId: ctx.channelId })
.andWhere('order.orderPlacedAt >= :startDate', {
startDate: startDate.toISOString(),
})
.skip(skip)
.take(take);
const [items, nrOfOrders] = await query.getManyAndCount();
orders.push(...items);
Logger.verbose(
`Fetched orders ${skip}-${skip + take} for channel ${
ctx.channel.token
} for ${interval} metrics`,
loggerCtx,
);
skip += items.length;
if (orders.length >= nrOfOrders) {
hasMoreOrders = false;
}
}
Logger.verbose(
`Finished fetching all ${orders.length} orders for channel ${ctx.channel.token} for ${interval} metrics`,
loggerCtx,
);
const dataPerInterval = new Map<number, MetricData>();
const ticks = [];
for (let i = 1; i <= nrOfEntries; i++) {
if (startTick + i >= maxTick) {
// make sure we dont go over month 12 or week 52
ticks.push(startTick + i - maxTick);
} else {
ticks.push(startTick + i);
}
}
ticks.forEach(tick => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const ordersInCurrentTick = orders.filter(order => getTickNrFn(order.orderPlacedAt!) === tick);
dataPerInterval.set(tick, {
orders: ordersInCurrentTick,
date: setDayOfYear(endDate, tick),
});
});
return dataPerInterval;
}
}
|
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { loadAppConfig } from '@vendure/admin-ui/core';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
loadAppConfig()
.then(() => platformBrowserDynamic().bootstrapModule(AppModule))
.catch(err => {
/* eslint-disable no-console */
console.log(err);
});
|
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
/* eslint-disable */
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), {
teardown: { destroyAfterEach: false },
});
|
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent, AppComponentModule } from '@vendure/admin-ui/core';
import { routes } from './app.routes';
@NgModule({
declarations: [],
imports: [CommonModule, AppComponentModule, RouterModule.forRoot(routes, { useHash: false })],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
|
import { Route } from '@angular/router';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { AppShellComponent, AuthGuard } from '@vendure/admin-ui/core';
export const routes: Route[] = [
{ path: 'login', loadChildren: () => import('@vendure/admin-ui/login').then(m => m.LoginModule) },
{
path: '',
canActivate: [AuthGuard],
component: AppShellComponent,
data: {
breadcrumb: _('breadcrumb.dashboard'),
},
children: [
{
path: '',
pathMatch: 'full',
loadChildren: () => import('@vendure/admin-ui/dashboard').then(m => m.DashboardModule),
},
{
path: 'catalog',
loadChildren: () => import('@vendure/admin-ui/catalog').then(m => m.CatalogModule),
},
{
path: 'customer',
loadChildren: () => import('@vendure/admin-ui/customer').then(m => m.CustomerModule),
},
{
path: 'orders',
loadChildren: () => import('@vendure/admin-ui/order').then(m => m.OrderModule),
},
{
path: 'marketing',
loadChildren: () => import('@vendure/admin-ui/marketing').then(m => m.MarketingModule),
},
{
path: 'settings',
loadChildren: () => import('@vendure/admin-ui/settings').then(m => m.SettingsModule),
},
{
path: 'system',
loadChildren: () => import('@vendure/admin-ui/system').then(m => m.SystemModule),
},
],
},
];
|
export const environment = {
production: true,
};
|
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
};
/*
* In development mode, to ignore zone related error stack frames such as
* `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can
* import the following file, but please comment it out in production mode
* because it will have performance impact when throw error
*/
// import 'zone.js/plugins/zone-error'; // Included with Angular CLI.
|
/**
* This is a placeholder. Please import from one of the sub-packages, e.g `@vendure/admin-ui/core`
*/
export const placeholder = 'Vendure Admin UI';
|
import { NgModule } from '@angular/core';
import { RouterModule, ROUTES } from '@angular/router';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
AssetDetailQueryDocument,
BulkActionRegistryService,
CollectionDetailQueryDocument,
detailComponentWithResolver,
GetFacetDetailDocument,
GetProductDetailDocument,
GetProductVariantDetailDocument,
PageService,
SharedModule,
} from '@vendure/admin-ui/core';
import { SortOrder } from '@vendure/common/lib/generated-types';
import { createRoutes } from './catalog.routes';
import { ApplyFacetDialogComponent } from './components/apply-facet-dialog/apply-facet-dialog.component';
import { AssetDetailComponent } from './components/asset-detail/asset-detail.component';
import { AssetListComponent } from './components/asset-list/asset-list.component';
import { AssignProductsToChannelDialogComponent } from './components/assign-products-to-channel-dialog/assign-products-to-channel-dialog.component';
import { BulkAddFacetValuesDialogComponent } from './components/bulk-add-facet-values-dialog/bulk-add-facet-values-dialog.component';
import { CollectionContentsComponent } from './components/collection-contents/collection-contents.component';
import { CollectionDataTableComponent } from './components/collection-data-table/collection-data-table.component';
import { CollectionDetailComponent } from './components/collection-detail/collection-detail.component';
import { CollectionBreadcrumbPipe } from './components/collection-list/collection-breadcrumb.pipe';
import {
assignCollectionsToChannelBulkAction,
deleteCollectionsBulkAction,
duplicateCollectionsBulkAction,
moveCollectionsBulkAction,
removeCollectionsFromChannelBulkAction,
} from './components/collection-list/collection-list-bulk-actions';
import { CollectionListComponent } from './components/collection-list/collection-list.component';
import { CollectionTreeNodeComponent } from './components/collection-tree/collection-tree-node.component';
import { CollectionTreeComponent } from './components/collection-tree/collection-tree.component';
import { ConfirmVariantDeletionDialogComponent } from './components/confirm-variant-deletion-dialog/confirm-variant-deletion-dialog.component';
import { CreateFacetValueDialogComponent } from './components/create-facet-value-dialog/create-facet-value-dialog.component';
import { CreateProductOptionGroupDialogComponent } from './components/create-product-option-group-dialog/create-product-option-group-dialog.component';
import { CreateProductVariantDialogComponent } from './components/create-product-variant-dialog/create-product-variant-dialog.component';
import { FacetDetailComponent } from './components/facet-detail/facet-detail.component';
import {
assignFacetsToChannelBulkAction,
deleteFacetsBulkAction,
duplicateFacetsBulkAction,
removeFacetsFromChannelBulkAction,
} from './components/facet-list/facet-list-bulk-actions';
import { FacetListComponent } from './components/facet-list/facet-list.component';
import { GenerateProductVariantsComponent } from './components/generate-product-variants/generate-product-variants.component';
import { MoveCollectionsDialogComponent } from './components/move-collections-dialog/move-collections-dialog.component';
import { OptionValueInputComponent } from './components/option-value-input/option-value-input.component';
import { ProductDetailComponent } from './components/product-detail/product-detail.component';
import {
assignFacetValuesToProductsBulkAction,
assignProductsToChannelBulkAction,
deleteProductsBulkAction,
duplicateProductsBulkAction,
removeProductsFromChannelBulkAction,
} from './components/product-list/product-list-bulk-actions';
import { ProductListComponent } from './components/product-list/product-list.component';
import { ProductOptionsEditorComponent } from './components/product-options-editor/product-options-editor.component';
import { ProductVariantDetailComponent } from './components/product-variant-detail/product-variant-detail.component';
import {
assignFacetValuesToProductVariantsBulkAction,
assignProductVariantsToChannelBulkAction,
deleteProductVariantsBulkAction,
removeProductVariantsFromChannelBulkAction,
} from './components/product-variant-list/product-variant-list-bulk-actions';
import { ProductVariantListComponent } from './components/product-variant-list/product-variant-list.component';
import { ProductVariantQuickJumpComponent } from './components/product-variant-quick-jump/product-variant-quick-jump.component';
import { ProductVariantsEditorComponent } from './components/product-variants-editor/product-variants-editor.component';
import { ProductVariantsTableComponent } from './components/product-variants-table/product-variants-table.component';
import { UpdateProductOptionDialogComponent } from './components/update-product-option-dialog/update-product-option-dialog.component';
import { VariantPriceDetailComponent } from './components/variant-price-detail/variant-price-detail.component';
import { VariantPriceStrategyDetailComponent } from './components/variant-price-strategy-detail/variant-price-strategy-detail.component';
const CATALOG_COMPONENTS = [
ProductListComponent,
ProductDetailComponent,
FacetListComponent,
FacetDetailComponent,
GenerateProductVariantsComponent,
ApplyFacetDialogComponent,
AssetListComponent,
VariantPriceDetailComponent,
VariantPriceStrategyDetailComponent,
CollectionListComponent,
CollectionDetailComponent,
CollectionTreeComponent,
CollectionTreeNodeComponent,
CollectionContentsComponent,
ProductVariantsTableComponent,
OptionValueInputComponent,
UpdateProductOptionDialogComponent,
ProductVariantsEditorComponent,
AssignProductsToChannelDialogComponent,
AssetDetailComponent,
ConfirmVariantDeletionDialogComponent,
ProductOptionsEditorComponent,
BulkAddFacetValuesDialogComponent,
CollectionDataTableComponent,
CollectionBreadcrumbPipe,
MoveCollectionsDialogComponent,
ProductVariantListComponent,
ProductDetailComponent,
ProductVariantDetailComponent,
CreateProductVariantDialogComponent,
CreateProductOptionGroupDialogComponent,
ProductVariantQuickJumpComponent,
CreateFacetValueDialogComponent,
];
@NgModule({
imports: [SharedModule, RouterModule.forChild([])],
exports: [...CATALOG_COMPONENTS],
declarations: [...CATALOG_COMPONENTS],
providers: [
{
provide: ROUTES,
useFactory: (pageService: PageService) => createRoutes(pageService),
multi: true,
deps: [PageService],
},
],
})
export class CatalogModule {
private static hasRegisteredTabsAndBulkActions = false;
constructor(bulkActionRegistryService: BulkActionRegistryService, pageService: PageService) {
if (CatalogModule.hasRegisteredTabsAndBulkActions) {
return;
}
bulkActionRegistryService.registerBulkAction(assignFacetValuesToProductsBulkAction);
bulkActionRegistryService.registerBulkAction(assignProductsToChannelBulkAction);
bulkActionRegistryService.registerBulkAction(assignProductVariantsToChannelBulkAction);
bulkActionRegistryService.registerBulkAction(removeProductsFromChannelBulkAction);
bulkActionRegistryService.registerBulkAction(removeProductVariantsFromChannelBulkAction);
bulkActionRegistryService.registerBulkAction(duplicateProductsBulkAction);
bulkActionRegistryService.registerBulkAction(deleteProductsBulkAction);
bulkActionRegistryService.registerBulkAction(deleteProductVariantsBulkAction);
bulkActionRegistryService.registerBulkAction(assignFacetValuesToProductVariantsBulkAction);
bulkActionRegistryService.registerBulkAction(assignFacetsToChannelBulkAction);
bulkActionRegistryService.registerBulkAction(removeFacetsFromChannelBulkAction);
bulkActionRegistryService.registerBulkAction(duplicateFacetsBulkAction);
bulkActionRegistryService.registerBulkAction(deleteFacetsBulkAction);
bulkActionRegistryService.registerBulkAction(moveCollectionsBulkAction);
bulkActionRegistryService.registerBulkAction(assignCollectionsToChannelBulkAction);
bulkActionRegistryService.registerBulkAction(removeCollectionsFromChannelBulkAction);
bulkActionRegistryService.registerBulkAction(duplicateCollectionsBulkAction);
bulkActionRegistryService.registerBulkAction(deleteCollectionsBulkAction);
pageService.registerPageTab({
priority: 0,
location: 'product-list',
tab: _('catalog.products'),
route: '',
component: ProductListComponent,
});
pageService.registerPageTab({
priority: 0,
location: 'product-detail',
tab: _('catalog.product'),
route: '',
component: detailComponentWithResolver({
component: ProductDetailComponent,
query: GetProductDetailDocument,
entityKey: 'product',
getBreadcrumbs: entity => [
{
label: entity ? entity.name : _('catalog.create-new-product'),
link: [entity?.id],
},
],
}),
});
pageService.registerPageTab({
priority: 0,
location: 'product-list',
tab: _('catalog.product-variants'),
route: 'variants',
component: ProductVariantListComponent,
});
pageService.registerPageTab({
priority: 0,
location: 'product-variant-detail',
tab: _('catalog.product-variants'),
route: '',
component: detailComponentWithResolver({
component: ProductVariantDetailComponent,
query: GetProductVariantDetailDocument,
entityKey: 'productVariant',
getBreadcrumbs: entity => [
{
label: `${entity?.product.name}`,
link: ['/catalog', 'products', entity?.product.id],
},
{
label: `${entity?.name} (${entity?.sku})`,
link: ['variants', entity?.id],
},
],
}),
});
pageService.registerPageTab({
priority: 0,
location: 'facet-list',
tab: _('catalog.facets'),
route: '',
component: FacetListComponent,
});
pageService.registerPageTab({
priority: 0,
location: 'facet-detail',
tab: _('catalog.facet'),
route: '',
component: detailComponentWithResolver({
component: FacetDetailComponent,
query: GetFacetDetailDocument,
variables: {
facetValueListOptions: {
take: 10,
skip: 0,
sort: {
createdAt: SortOrder.DESC,
},
},
},
entityKey: 'facet',
getBreadcrumbs: entity => [
{
label: entity ? entity.name : _('catalog.create-new-facet'),
link: [entity?.id],
},
],
}),
});
pageService.registerPageTab({
priority: 0,
location: 'collection-list',
tab: _('catalog.collections'),
route: '',
component: CollectionListComponent,
});
pageService.registerPageTab({
priority: 0,
location: 'collection-detail',
tab: _('catalog.collection'),
route: '',
component: detailComponentWithResolver({
component: CollectionDetailComponent,
query: CollectionDetailQueryDocument,
entityKey: 'collection',
getBreadcrumbs: entity => [
{
label: entity ? entity.name : _('catalog.create-new-collection'),
link: [entity?.id],
},
],
}),
});
pageService.registerPageTab({
priority: 0,
location: 'asset-list',
tab: _('catalog.assets'),
route: '',
component: AssetListComponent,
});
pageService.registerPageTab({
priority: 0,
location: 'asset-detail',
tab: _('catalog.asset'),
route: '',
component: detailComponentWithResolver({
component: AssetDetailComponent,
query: AssetDetailQueryDocument,
entityKey: 'asset',
getBreadcrumbs: entity => [
{
label: `${entity?.name}`,
link: [entity?.id],
},
],
}),
});
CatalogModule.hasRegisteredTabsAndBulkActions = true;
}
}
|
import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, Route } from '@angular/router';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
CanDeactivateDetailGuard,
createResolveData,
DataService,
PageComponent,
PageService,
} from '@vendure/admin-ui/core';
import { map } from 'rxjs/operators';
import { ProductOptionsEditorComponent } from './components/product-options-editor/product-options-editor.component';
import { ProductVariantsEditorComponent } from './components/product-variants-editor/product-variants-editor.component';
import { ProductVariantsResolver } from './providers/routing/product-variants-resolver';
export const createRoutes = (pageService: PageService): Route[] => [
{
path: 'products',
component: PageComponent,
data: {
locationId: 'product-list',
breadcrumb: _('breadcrumb.products'),
},
children: pageService.getPageTabRoutes('product-list'),
},
{
path: 'inventory',
redirectTo: 'products',
},
{
path: 'products/:id',
component: PageComponent,
data: {
locationId: 'product-detail',
breadcrumb: { label: _('breadcrumb.products'), link: ['../', 'products'] },
},
children: [
{
path: 'manage-variants',
component: ProductVariantsEditorComponent,
canDeactivate: [CanDeactivateDetailGuard],
data: {
breadcrumb: ({ product }) => [
{
label: `${product.name}`,
link: ['../'],
},
{
label: _('breadcrumb.manage-variants'),
link: ['manage-variants'],
},
],
},
resolve: {
product: (route: ActivatedRouteSnapshot) =>
inject(DataService)
.product.getProductVariantsOptions(route.parent?.params.id)
.mapSingle(data => data.product),
},
},
...pageService.getPageTabRoutes('product-detail'),
],
},
{
path: 'products/:productId/variants/:id',
component: PageComponent,
data: {
locationId: 'product-variant-detail',
breadcrumb: { label: _('breadcrumb.products'), link: ['../', 'products'] },
},
children: pageService.getPageTabRoutes('product-variant-detail'),
},
{
path: 'products/:id/options',
component: ProductOptionsEditorComponent,
resolve: createResolveData(ProductVariantsResolver),
canDeactivate: [CanDeactivateDetailGuard],
data: {
breadcrumb: productOptionsEditorBreadcrumb,
},
},
{
path: 'facets',
component: PageComponent,
data: {
locationId: 'facet-list',
breadcrumb: _('breadcrumb.facets'),
},
children: pageService.getPageTabRoutes('facet-list'),
},
{
path: 'facets/:id',
component: PageComponent,
data: {
locationId: 'facet-detail',
breadcrumb: { label: _('breadcrumb.facets'), link: ['../', 'facets'] },
},
children: pageService.getPageTabRoutes('facet-detail'),
},
{
path: 'collections',
component: PageComponent,
data: {
locationId: 'collection-list',
breadcrumb: _('breadcrumb.collections'),
},
children: pageService.getPageTabRoutes('collection-list'),
},
{
path: 'collections/:id',
component: PageComponent,
data: {
locationId: 'collection-detail',
breadcrumb: { label: _('breadcrumb.collections'), link: ['../', 'collections'] },
},
children: pageService.getPageTabRoutes('collection-detail'),
},
{
path: 'assets',
component: PageComponent,
data: {
locationId: 'asset-list',
breadcrumb: _('breadcrumb.assets'),
},
children: pageService.getPageTabRoutes('asset-list'),
},
{
path: 'assets/:id',
component: PageComponent,
data: {
locationId: 'asset-detail',
breadcrumb: { label: _('breadcrumb.assets'), link: ['../', 'assets'] },
},
children: pageService.getPageTabRoutes('asset-detail'),
},
];
export function productOptionsEditorBreadcrumb(data: any, params: any) {
return data.entity.pipe(
map((entity: any) => [
{
label: _('breadcrumb.products'),
link: ['../', 'products'],
},
{
label: `${entity.name}`,
link: ['../', 'products', params.id],
},
{
label: _('breadcrumb.product-options'),
link: ['options'],
},
]),
);
}
|
// This file was generated by the build-public-api.ts script
export * from './catalog.module';
export * from './catalog.routes';
export * from './components/apply-facet-dialog/apply-facet-dialog.component';
export * from './components/asset-detail/asset-detail.component';
export * from './components/asset-list/asset-list.component';
export * from './components/assign-products-to-channel-dialog/assign-products-to-channel-dialog.component';
export * from './components/bulk-add-facet-values-dialog/bulk-add-facet-values-dialog.component';
export * from './components/bulk-add-facet-values-dialog/bulk-add-facet-values-dialog.graphql';
export * from './components/collection-contents/collection-contents.component';
export * from './components/collection-data-table/collection-data-table.component';
export * from './components/collection-detail/collection-detail.component';
export * from './components/collection-list/collection-breadcrumb.pipe';
export * from './components/collection-list/collection-list-bulk-actions';
export * from './components/collection-list/collection-list.component';
export * from './components/collection-tree/array-to-tree';
export * from './components/collection-tree/collection-tree-node.component';
export * from './components/collection-tree/collection-tree.component';
export * from './components/collection-tree/collection-tree.service';
export * from './components/collection-tree/collection-tree.types';
export * from './components/confirm-variant-deletion-dialog/confirm-variant-deletion-dialog.component';
export * from './components/create-facet-value-dialog/create-facet-value-dialog.component';
export * from './components/create-product-option-group-dialog/create-product-option-group-dialog.component';
export * from './components/create-product-variant-dialog/create-product-variant-dialog.component';
export * from './components/facet-detail/facet-detail.component';
export * from './components/facet-list/facet-list-bulk-actions';
export * from './components/facet-list/facet-list.component';
export * from './components/generate-product-variants/generate-product-variants.component';
export * from './components/move-collections-dialog/move-collections-dialog.component';
export * from './components/option-value-input/option-value-input.component';
export * from './components/product-detail/product-detail.component';
export * from './components/product-list/product-list-bulk-actions';
export * from './components/product-list/product-list.component';
export * from './components/product-list/product-list.graphql';
export * from './components/product-options-editor/product-options-editor.component';
export * from './components/product-variant-detail/product-variant-detail.component';
export * from './components/product-variant-detail/product-variant-detail.graphql';
export * from './components/product-variant-list/product-variant-list-bulk-actions';
export * from './components/product-variant-list/product-variant-list.component';
export * from './components/product-variant-list/product-variant-list.graphql';
export * from './components/product-variant-quick-jump/product-variant-quick-jump.component';
export * from './components/product-variants-editor/product-variants-editor.component';
export * from './components/product-variants-table/product-variants-table.component';
export * from './components/update-product-option-dialog/update-product-option-dialog.component';
export * from './components/variant-price-detail/variant-price-detail.component';
export * from './components/variant-price-strategy-detail/variant-price-strategy-detail.component';
export * from './providers/product-detail/product-detail.service';
export * from './providers/product-detail/replace-last';
export * from './providers/routing/product-variants-resolver';
|
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ViewChild,
} from '@angular/core';
import {
Dialog,
FacetValue,
FacetValueSelectorComponent,
FacetWithValuesFragment,
} from '@vendure/admin-ui/core';
@Component({
selector: 'vdr-apply-facet-dialog',
templateUrl: './apply-facet-dialog.component.html',
styleUrls: ['./apply-facet-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ApplyFacetDialogComponent implements Dialog<FacetValue[]>, AfterViewInit {
@ViewChild(FacetValueSelectorComponent) private selector: FacetValueSelectorComponent;
resolveWith: (result?: FacetValue[]) => void;
selectedValues: FacetValue[] = [];
// Provided by caller
facets: FacetWithValuesFragment[];
constructor(private changeDetector: ChangeDetectorRef) {}
ngAfterViewInit() {
setTimeout(() => this.selector.focus(), 0);
}
selectValues() {
this.resolveWith(this.selectedValues);
}
cancel() {
this.resolveWith();
}
}
|
import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl, FormGroup, UntypedFormBuilder } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
ASSET_FRAGMENT,
AssetDetailQueryDocument,
AssetDetailQueryQuery,
DataService,
getCustomFieldsDefaults,
LanguageCode,
NotificationService,
TAG_FRAGMENT,
TypedBaseDetailComponent,
} from '@vendure/admin-ui/core';
import { gql } from 'apollo-angular';
export const ASSET_DETAIL_QUERY = gql`
query AssetDetailQuery($id: ID!) {
asset(id: $id) {
...Asset
tags {
...Tag
}
}
}
${ASSET_FRAGMENT}
${TAG_FRAGMENT}
`;
@Component({
selector: 'vdr-asset-detail',
templateUrl: './asset-detail.component.html',
styleUrls: ['./asset-detail.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AssetDetailComponent
extends TypedBaseDetailComponent<typeof AssetDetailQueryDocument, 'asset'>
implements OnInit, OnDestroy
{
readonly customFields = this.getCustomFieldConfig('Asset');
detailForm = new FormGroup({
name: new FormControl(''),
tags: new FormControl([] as string[]),
customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)),
});
constructor(
private notificationService: NotificationService,
protected dataService: DataService,
private formBuilder: UntypedFormBuilder,
) {
super();
}
ngOnInit() {
this.init();
}
ngOnDestroy() {
this.destroy();
}
onAssetChange(event: { id: string; name: string; tags: string[] }) {
this.detailForm.get('name')?.setValue(event.name);
this.detailForm.get('tags')?.setValue(event.tags);
this.detailForm.markAsDirty();
}
save() {
this.dataService.product
.updateAsset({
id: this.id,
name: this.detailForm.value.name,
tags: this.detailForm.value.tags,
customFields: this.detailForm.value.customFields,
})
.subscribe(
() => {
this.notificationService.success(_('common.notify-update-success'), { entity: 'Asset' });
},
err => {
this.notificationService.error(_('common.notify-update-error'), {
entity: 'Asset',
});
},
);
}
protected setFormValues(
entity: NonNullable<AssetDetailQueryQuery['asset']>,
languageCode: LanguageCode,
): void {
this.detailForm.get('name')?.setValue(entity.name);
this.detailForm.get('tags')?.setValue(entity.tags.map(t => t.id));
if (this.customFields.length) {
this.setCustomFieldFormValues(this.customFields, this.detailForm.get(['customFields']), entity);
}
}
}
|
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
Asset,
BaseListComponent,
DataService,
DeletionResult,
GetAssetListQuery,
GetAssetListQueryVariables,
ItemOf,
LogicalOperator,
ModalService,
NotificationService,
SortOrder,
TagFragment,
} from '@vendure/admin-ui/core';
import { PaginationInstance } from 'ngx-pagination';
import { BehaviorSubject, combineLatest, EMPTY, Observable } from 'rxjs';
import { debounceTime, finalize, map, switchMap, takeUntil } from 'rxjs/operators';
@Component({
selector: 'vdr-asset-list',
templateUrl: './asset-list.component.html',
styleUrls: ['./asset-list.component.scss'],
})
export class AssetListComponent
extends BaseListComponent<
GetAssetListQuery,
ItemOf<GetAssetListQuery, 'assets'>,
GetAssetListQueryVariables
>
implements OnInit
{
searchTerm$ = new BehaviorSubject<string | undefined>(undefined);
filterByTags$ = new BehaviorSubject<TagFragment[] | undefined>(undefined);
uploading = false;
allTags$: Observable<TagFragment[]>;
paginationConfig$: Observable<PaginationInstance>;
constructor(
private notificationService: NotificationService,
private modalService: ModalService,
private dataService: DataService,
router: Router,
route: ActivatedRoute,
) {
super(router, route);
super.setQueryFn(
(...args: any[]) => this.dataService.product.getAssetList(...args).refetchOnChannelChange(),
data => data.assets,
(skip, take) => {
const searchTerm = this.searchTerm$.value;
const tags = this.filterByTags$.value?.map(t => t.value);
return {
options: {
skip,
take,
...(searchTerm
? {
filter: {
name: { contains: searchTerm },
},
}
: {}),
sort: {
createdAt: SortOrder.DESC,
},
tags,
tagsOperator: LogicalOperator.AND,
},
};
},
{ take: 25, skip: 0 },
);
}
ngOnInit() {
super.ngOnInit();
this.paginationConfig$ = combineLatest(this.itemsPerPage$, this.currentPage$, this.totalItems$).pipe(
map(([itemsPerPage, currentPage, totalItems]) => ({ itemsPerPage, currentPage, totalItems })),
);
this.searchTerm$.pipe(debounceTime(250), takeUntil(this.destroy$)).subscribe(() => this.refresh());
this.filterByTags$.pipe(takeUntil(this.destroy$)).subscribe(() => this.refresh());
this.allTags$ = this.dataService.product.getTagList().mapStream(data => data.tags.items);
}
filesSelected(files: File[]) {
if (files.length) {
this.uploading = true;
this.dataService.product
.createAssets(files)
.pipe(finalize(() => (this.uploading = false)))
.subscribe(({ createAssets }) => {
let successCount = 0;
for (const result of createAssets) {
switch (result.__typename) {
case 'Asset':
successCount++;
break;
case 'MimeTypeError':
this.notificationService.error(result.message);
break;
}
}
if (0 < successCount) {
super.refresh();
this.notificationService.success(_('asset.notify-create-assets-success'), {
count: successCount,
});
}
});
}
}
deleteAssets(assets: Asset[]) {
this.showModalAndDelete(assets.map(a => a.id))
.pipe(
switchMap(response => {
if (response.result === DeletionResult.DELETED) {
return [true];
} else {
return this.showModalAndDelete(
assets.map(a => a.id),
response.message || '',
).pipe(map(r => r.result === DeletionResult.DELETED));
}
}),
)
.subscribe(
() => {
this.notificationService.success(_('common.notify-delete-success'), {
entity: 'Assets',
});
this.refresh();
},
err => {
this.notificationService.error(_('common.notify-delete-error'), {
entity: 'Assets',
});
},
);
}
private showModalAndDelete(assetIds: string[], message?: string) {
return this.modalService
.dialog({
title: _('catalog.confirm-delete-assets'),
translationVars: {
count: assetIds.length,
},
body: message,
buttons: [
{ type: 'secondary', label: _('common.cancel') },
{ type: 'danger', label: _('common.delete'), returnValue: true },
],
})
.pipe(
switchMap(res => (res ? this.dataService.product.deleteAssets(assetIds, !!message) : EMPTY)),
map(res => res.deleteAssets),
);
}
}
|
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { UntypedFormControl } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
DataService,
Dialog,
GetChannelsQuery,
ItemOf,
LogicalOperator,
NotificationService,
} from '@vendure/admin-ui/core';
import { combineLatest, from, lastValueFrom, Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
type Channel = ItemOf<GetChannelsQuery, 'channels'>;
@Component({
selector: 'vdr-assign-products-to-channel-dialog',
templateUrl: './assign-products-to-channel-dialog.component.html',
styleUrls: ['./assign-products-to-channel-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AssignProductsToChannelDialogComponent implements OnInit, Dialog<any> {
selectedChannel: Channel | null | undefined;
currentChannel: Channel;
availableChannels: Channel[];
resolveWith: (result?: any) => void;
variantsPreview$: Observable<Array<{ id: string; name: string; price: number; pricePreview: number }>>;
priceFactorControl = new UntypedFormControl(1);
selectedChannelIdControl = new UntypedFormControl();
// assigned by ModalService.fromComponent() call
productIds: string[];
productVariantIds: string[] | undefined;
currentChannelIds: string[];
get isProductVariantMode(): boolean {
return this.productVariantIds != null;
}
constructor(private dataService: DataService, private notificationService: NotificationService) {}
ngOnInit() {
const activeChannelId$ = this.dataService.client
.userStatus()
.mapSingle(({ userStatus }) => userStatus.activeChannelId);
const allChannels$ = this.dataService.settings.getChannels().mapSingle(data => data.channels);
combineLatest(activeChannelId$, allChannels$).subscribe(([activeChannelId, channels]) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.currentChannel = channels.items.find(c => c.id === activeChannelId)!;
this.availableChannels = channels.items;
});
this.selectedChannelIdControl.valueChanges.subscribe(ids => {
this.selectChannel(ids);
});
this.variantsPreview$ = combineLatest(
from(this.getTopVariants(10)),
this.priceFactorControl.valueChanges.pipe(startWith(1)),
).pipe(
map(([variants, factor]) =>
variants.map(v => ({
id: v.id,
name: v.name,
price: v.price,
pricePreview: v.price * +factor,
})),
),
);
}
selectChannel(channelIds: string[]) {
this.selectedChannel = this.availableChannels.find(c => c.id === channelIds[0]);
}
assign() {
const selectedChannel = this.selectedChannel;
if (selectedChannel) {
if (!this.isProductVariantMode) {
this.dataService.product
.assignProductsToChannel({
channelId: selectedChannel.id,
productIds: this.productIds,
priceFactor: +this.priceFactorControl.value,
})
.subscribe(() => {
this.notificationService.success(_('catalog.assign-product-to-channel-success'), {
channel: selectedChannel.code,
count: this.productIds.length,
});
this.resolveWith(true);
});
} else if (this.productVariantIds) {
this.dataService.product
.assignVariantsToChannel({
channelId: selectedChannel.id,
productVariantIds: this.productVariantIds,
priceFactor: +this.priceFactorControl.value,
})
.subscribe(() => {
this.notificationService.success(_('catalog.assign-variant-to-channel-success'), {
channel: selectedChannel.code,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
count: this.productVariantIds!.length,
});
this.resolveWith(true);
});
}
}
}
cancel() {
this.resolveWith();
}
private async getTopVariants(take: number) {
return (
await lastValueFrom(
this.dataService.product.getProductVariants({
filterOperator: LogicalOperator.OR,
filter: {
productId: { in: this.productIds },
id: { in: this.productVariantIds },
},
take,
}).single$,
)
).productVariants.items;
}
}
|
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import {
DataService,
Dialog,
FacetWithValuesFragment,
GetProductsWithFacetValuesByIdsQuery,
GetProductsWithFacetValuesByIdsQueryVariables,
GetVariantsWithFacetValuesByIdsQuery,
UpdateProductsBulkMutation,
UpdateProductsBulkMutationVariables,
UpdateVariantsBulkMutation,
UpdateVariantsBulkMutationVariables,
} from '@vendure/admin-ui/core';
import { unique } from '@vendure/common/lib/unique';
import { Observable, Subscription } from 'rxjs';
import { shareReplay, switchMap } from 'rxjs/operators';
import {
GET_PRODUCTS_WITH_FACET_VALUES_BY_IDS,
GET_VARIANTS_WITH_FACET_VALUES_BY_IDS,
UPDATE_PRODUCTS_BULK,
UPDATE_VARIANTS_BULK,
} from './bulk-add-facet-values-dialog.graphql';
interface ProductOrVariant {
id: string;
name: string;
sku?: string;
facetValues: Array<{
id: string;
name: string;
code: string;
facet: Array<{
id: string;
name: string;
code: string;
}>;
}>;
}
@Component({
selector: 'vdr-bulk-add-facet-values-dialog',
templateUrl: './bulk-add-facet-values-dialog.component.html',
styleUrls: ['./bulk-add-facet-values-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BulkAddFacetValuesDialogComponent
implements OnInit, OnDestroy, Dialog<FacetWithValuesFragment[]>
{
resolveWith: (result?: FacetWithValuesFragment[]) => void;
/* provided by call to ModalService */
mode: 'product' | 'variant' = 'product';
ids?: string[];
state: 'loading' | 'ready' | 'saving' = 'loading';
selectedValues: FacetWithValuesFragment[] = [];
items: ProductOrVariant[] = [];
facetValuesRemoved = false;
private subscription: Subscription;
constructor(private dataService: DataService, private changeDetectorRef: ChangeDetectorRef) {}
ngOnInit(): void {
const fetchData$: Observable<any> =
this.mode === 'product'
? this.dataService
.query<
GetProductsWithFacetValuesByIdsQuery,
GetProductsWithFacetValuesByIdsQueryVariables
>(GET_PRODUCTS_WITH_FACET_VALUES_BY_IDS, {
ids: this.ids ?? [],
})
.mapSingle(({ products }) =>
products.items.map(p => ({ ...p, facetValues: [...p.facetValues] })),
)
: this.dataService
.query<
GetVariantsWithFacetValuesByIdsQuery,
GetProductsWithFacetValuesByIdsQueryVariables
>(GET_VARIANTS_WITH_FACET_VALUES_BY_IDS, {
ids: this.ids ?? [],
})
.mapSingle(({ productVariants }) =>
productVariants.items.map(p => ({ ...p, facetValues: [...p.facetValues] })),
);
this.subscription = fetchData$.subscribe({
next: items => {
this.items = items;
this.state = 'ready';
this.changeDetectorRef.markForCheck();
},
});
}
ngOnDestroy() {
this.subscription?.unsubscribe();
}
cancel() {
this.resolveWith();
}
removeFacetValue(item: ProductOrVariant, facetValueId: string) {
item.facetValues = item.facetValues.filter(fv => fv.id !== facetValueId);
this.facetValuesRemoved = true;
}
addFacetValues() {
const selectedFacetValueIds = this.selectedValues.map(sv => sv.id);
this.state = 'saving';
const save$: Observable<any> =
this.mode === 'product'
? this.dataService.mutate<UpdateProductsBulkMutation, UpdateProductsBulkMutationVariables>(
UPDATE_PRODUCTS_BULK,
{
input: this.items?.map(product => ({
id: product.id,
facetValueIds: unique([
...product.facetValues.map(fv => fv.id),
...selectedFacetValueIds,
]),
})),
},
)
: this.dataService.mutate<UpdateVariantsBulkMutation, UpdateVariantsBulkMutationVariables>(
UPDATE_VARIANTS_BULK,
{
input: this.items?.map(product => ({
id: product.id,
facetValueIds: unique([
...product.facetValues.map(fv => fv.id),
...selectedFacetValueIds,
]),
})),
},
);
return save$.subscribe(result => {
this.resolveWith(this.selectedValues);
});
}
}
|
import { gql } from 'apollo-angular';
export const GET_PRODUCTS_WITH_FACET_VALUES_BY_IDS = gql`
query GetProductsWithFacetValuesByIds($ids: [String!]!) {
products(options: { filter: { id: { in: $ids } } }) {
items {
id
name
facetValues {
id
name
code
facet {
id
name
code
}
}
}
}
}
`;
export const GET_VARIANTS_WITH_FACET_VALUES_BY_IDS = gql`
query GetVariantsWithFacetValuesByIds($ids: [String!]!) {
productVariants(options: { filter: { id: { in: $ids } } }) {
items {
id
name
sku
facetValues {
id
name
code
facet {
id
name
code
}
}
}
}
}
`;
export const UPDATE_PRODUCTS_BULK = gql`
mutation UpdateProductsBulk($input: [UpdateProductInput!]!) {
updateProducts(input: $input) {
id
name
facetValues {
id
name
code
}
}
}
`;
export const UPDATE_VARIANTS_BULK = gql`
mutation UpdateVariantsBulk($input: [UpdateProductVariantInput!]!) {
updateProductVariants(input: $input) {
id
name
facetValues {
id
name
code
}
}
}
`;
|
import {
ChangeDetectionStrategy,
Component,
ContentChild,
Input,
OnChanges,
OnDestroy,
OnInit,
SimpleChanges,
TemplateRef,
} from '@angular/core';
import { UntypedFormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import {
CollectionFilterParameter,
ConfigurableOperationInput,
DataService,
GetCollectionContentsQuery,
} from '@vendure/admin-ui/core';
import { BehaviorSubject, combineLatest, Observable, of, Subject } from 'rxjs';
import {
catchError,
debounceTime,
distinctUntilChanged,
filter,
finalize,
map,
startWith,
switchMap,
takeUntil,
tap,
} from 'rxjs/operators';
@Component({
selector: 'vdr-collection-contents',
templateUrl: './collection-contents.component.html',
styleUrls: ['./collection-contents.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CollectionContentsComponent implements OnInit, OnChanges, OnDestroy {
@Input() collectionId: string;
@Input() parentId: string;
@Input() inheritFilters: boolean;
@Input() updatedFilters: ConfigurableOperationInput[] | undefined;
@Input() previewUpdatedFilters = false;
@ContentChild(TemplateRef, { static: true }) headerTemplate: TemplateRef<any>;
contents$: Observable<NonNullable<GetCollectionContentsQuery['collection']>['productVariants']['items']>;
contentsTotalItems$: Observable<number>;
contentsItemsPerPage$: Observable<number>;
contentsCurrentPage$: Observable<number>;
filterTermControl = new UntypedFormControl('');
isLoading = false;
private collectionIdChange$ = new BehaviorSubject<string>('');
private parentIdChange$ = new BehaviorSubject<string>('');
private filterChanges$ = new BehaviorSubject<ConfigurableOperationInput[]>([]);
private inheritFiltersChanges$ = new BehaviorSubject<boolean>(true);
private refresh$ = new BehaviorSubject<boolean>(true);
private destroy$ = new Subject<void>();
constructor(private route: ActivatedRoute, private router: Router, private dataService: DataService) {}
ngOnInit() {
this.contentsCurrentPage$ = this.route.queryParamMap.pipe(
map(qpm => qpm.get('contentsPage')),
map(page => (!page ? 1 : +page)),
startWith(1),
distinctUntilChanged(),
);
this.contentsItemsPerPage$ = this.route.queryParamMap.pipe(
map(qpm => qpm.get('contentsPerPage')),
map(perPage => (!perPage ? 10 : +perPage)),
startWith(10),
distinctUntilChanged(),
);
const filterTerm$ = this.filterTermControl.valueChanges.pipe(
debounceTime(250),
tap(() => this.setContentsPageNumber(1)),
startWith(''),
);
const filterChanges$ = this.filterChanges$.asObservable().pipe(
filter(() => this.previewUpdatedFilters),
tap(() => this.setContentsPageNumber(1)),
startWith([]),
);
const inheritFiltersChanges$ = this.inheritFiltersChanges$.asObservable().pipe(
filter(() => this.inheritFilters != null),
distinctUntilChanged(),
tap(() => this.setContentsPageNumber(1)),
startWith(true),
);
const fetchUpdate$ = combineLatest(
this.collectionIdChange$,
this.parentIdChange$,
this.contentsCurrentPage$,
this.contentsItemsPerPage$,
filterTerm$,
filterChanges$,
inheritFiltersChanges$,
this.refresh$,
);
const collection$ = fetchUpdate$.pipe(
takeUntil(this.destroy$),
tap(() => (this.isLoading = true)),
debounceTime(50),
switchMap(([id, parentId, currentPage, itemsPerPage, filterTerm, filters, inheritFilters]) => {
const take = itemsPerPage;
const skip = (currentPage - 1) * itemsPerPage;
if (filters.length && this.previewUpdatedFilters) {
const filterClause = filterTerm
? ({ name: { contains: filterTerm } } as CollectionFilterParameter)
: undefined;
return this.dataService.collection
.previewCollectionVariants(
{
parentId,
filters,
inheritFilters,
},
{
take,
skip,
filter: filterClause,
},
)
.mapSingle(data => data.previewCollectionVariants)
.pipe(catchError(() => of({ items: [], totalItems: 0 })));
} else if (id) {
return this.dataService.collection
.getCollectionContents(id, take, skip, filterTerm)
.mapSingle(data => data.collection?.productVariants);
} else {
return of(null);
}
}),
tap(() => (this.isLoading = false)),
finalize(() => (this.isLoading = false)),
);
this.contents$ = collection$.pipe(map(result => (result ? result.items : [])));
this.contentsTotalItems$ = collection$.pipe(map(result => (result ? result.totalItems : 0)));
}
ngOnChanges(changes: SimpleChanges): void {
if ('collectionId' in changes) {
this.collectionIdChange$.next(changes.collectionId.currentValue);
}
if ('parentId' in changes) {
this.parentIdChange$.next(changes.parentId.currentValue);
}
if ('inheritFilters' in changes) {
this.inheritFiltersChanges$.next(changes.inheritFilters.currentValue);
}
if ('updatedFilters' in changes) {
if (this.updatedFilters) {
this.filterChanges$.next(this.updatedFilters);
}
}
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
setContentsPageNumber(page: number) {
this.setParam('contentsPage', page);
}
setContentsItemsPerPage(perPage: number) {
this.setParam('contentsPerPage', perPage);
}
refresh() {
this.refresh$.next(true);
}
private setParam(key: string, value: any) {
this.router.navigate(['./'], {
relativeTo: this.route,
queryParams: {
[key]: value,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
}
|
import { CdkDrag, CdkDragDrop, CdkDropList, DragDrop, DragRef } from '@angular/cdk/drag-drop';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
QueryList,
SimpleChanges,
ViewChild,
ViewChildren,
} from '@angular/core';
import {
DataService,
DataTable2Component,
GetCollectionListQuery,
ItemOf,
LocalStorageService,
} from '@vendure/admin-ui/core';
export type CollectionTableItem = ItemOf<GetCollectionListQuery, 'collections'>;
export type CollectionOrderEvent = {
collectionId: string;
parentId: string;
index: number;
};
@Component({
selector: 'vdr-collection-data-table',
templateUrl: './collection-data-table.component.html',
styleUrls: [
'../../../../core/src/shared/components/data-table-2/data-table2.component.scss',
'./collection-data-table.component.scss',
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CollectionDataTableComponent
extends DataTable2Component<CollectionTableItem>
implements OnChanges, AfterViewInit
{
@Input() subCollections: CollectionTableItem[];
@Output() changeOrder = new EventEmitter<CollectionOrderEvent>();
@ViewChild(CdkDropList, { static: true }) dropList: CdkDropList<{
depth: number;
collection: CollectionTableItem;
}>;
@ViewChildren('collectionRow', { read: CdkDrag }) collectionRowList: QueryList<CdkDrag>;
dragRefs: DragRef[] = [];
absoluteIndex: { [id: string]: number } = {};
constructor(
protected changeDetectorRef: ChangeDetectorRef,
protected localStorageService: LocalStorageService,
protected dataService: DataService,
private dragDrop: DragDrop,
) {
super(changeDetectorRef, localStorageService, dataService);
}
ngOnChanges(changes: SimpleChanges) {
super.ngOnChanges(changes);
if (changes.subCollections || changes.items) {
const allCollections: CollectionTableItem[] = [];
for (const collection of this.items ?? []) {
allCollections.push(collection);
const subCollectionMatches = this.getSubcollections(collection);
allCollections.push(...subCollectionMatches.flat());
}
allCollections.forEach((collection, index) => (this.absoluteIndex[collection.id] = index));
}
}
ngAfterViewInit() {
this.collectionRowList.changes.subscribe((val: QueryList<CdkDrag>) => {
this.dropList.getSortedItems().forEach(item => this.dropList.removeItem(item));
for (const ref of val.toArray()) {
ref.dropContainer = this.dropList;
ref._dragRef._withDropContainer(this.dropList._dropListRef);
this.dropList.addItem(ref);
}
});
}
getSubcollections(item: CollectionTableItem) {
return this.subCollections?.filter(c => c.parentId === item.id) ?? [];
}
sortPredicate = (index: number, item: CdkDrag<{ depth: number; collection: CollectionTableItem }>) => {
const itemAtIndex = this.dropList.getSortedItems()[index];
return itemAtIndex?.data.collection.parentId === item.data.collection.parentId;
};
onDrop(
event: CdkDragDrop<{
depth: number;
collection: CollectionTableItem;
}>,
) {
const isTopLevel = event.item.data.collection.breadcrumbs.length === 2;
const pageIndexOffset = isTopLevel ? (this.currentPage - 1) * this.itemsPerPage : 0;
const parentId = event.item.data.collection.parentId;
const parentIndex = this.items.findIndex(i => i.id === parentId);
const adjustedIndex = pageIndexOffset + event.currentIndex - parentIndex - 1;
this.changeOrder.emit({
collectionId: event.item.data.collection.id,
index: adjustedIndex,
parentId: event.item.data.collection.parentId,
});
if (isTopLevel) {
this.items = [...this.items];
this.items.splice(event.previousIndex, 1);
this.items.splice(event.currentIndex, 0, event.item.data.collection);
} else {
const parent = this.items.find(i => i.id === parentId);
if (parent) {
const subCollections = this.getSubcollections(parent);
const adjustedPreviousIndex = pageIndexOffset + event.previousIndex - parentIndex - 1;
subCollections.splice(adjustedPreviousIndex, 1);
subCollections.splice(event.currentIndex, 0, event.item.data.collection);
}
}
this.changeDetectorRef.markForCheck();
}
}
|
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
OnDestroy,
OnInit,
ViewChild,
} from '@angular/core';
import { FormBuilder, UntypedFormArray, UntypedFormControl, Validators } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
Asset,
COLLECTION_FRAGMENT,
CollectionDetailQueryDocument,
CollectionFragment,
ConfigurableOperation,
ConfigurableOperationDefinition,
ConfigurableOperationInput,
CreateCollectionInput,
createUpdatedTranslatable,
DataService,
encodeConfigArgValue,
findTranslation,
getConfigArgValue,
getCustomFieldsDefaults,
LanguageCode,
LocalStorageService,
ModalService,
NotificationService,
Permission,
TypedBaseDetailComponent,
unicodePatternValidator,
UpdateCollectionInput,
} from '@vendure/admin-ui/core';
import { normalizeString } from '@vendure/common/lib/normalize-string';
import { gql } from 'apollo-angular';
import { combineLatest, merge, Observable, of, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, map, mergeMap, switchMap, take } from 'rxjs/operators';
import { CollectionContentsComponent } from '../collection-contents/collection-contents.component';
export const COLLECTION_DETAIL_QUERY = gql`
query CollectionDetailQuery($id: ID!) {
collection(id: $id) {
...Collection
}
}
${COLLECTION_FRAGMENT}
`;
@Component({
selector: 'vdr-collection-detail',
templateUrl: './collection-detail.component.html',
styleUrls: ['./collection-detail.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CollectionDetailComponent
extends TypedBaseDetailComponent<typeof CollectionDetailQueryDocument, 'collection'>
implements OnInit, OnDestroy
{
customFields = this.getCustomFieldConfig('Collection');
detailForm = this.formBuilder.group({
name: ['', Validators.required],
slug: ['', unicodePatternValidator(/^[\p{Letter}0-9._-]+$/)],
description: '',
visible: false,
inheritFilters: true,
filters: this.formBuilder.array([]),
customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)),
});
assetChanges: { assets?: Asset[]; featuredAsset?: Asset } = {};
filters: ConfigurableOperation[] = [];
allFilters: ConfigurableOperationDefinition[] = [];
updatedFilters$: Observable<ConfigurableOperationInput[]>;
inheritFilters$: Observable<boolean>;
livePreview = false;
parentId$: Observable<string | undefined>;
readonly updatePermission = [Permission.UpdateCatalog, Permission.UpdateCollection];
private filterRemoved$ = new Subject<void>();
@ViewChild('collectionContents') contentsComponent: CollectionContentsComponent;
constructor(
private changeDetector: ChangeDetectorRef,
protected dataService: DataService,
private formBuilder: FormBuilder,
private notificationService: NotificationService,
private modalService: ModalService,
private localStorageService: LocalStorageService,
) {
super();
this.livePreview = this.localStorageService.get('livePreviewCollectionContents') ?? false;
}
ngOnInit() {
this.init();
this.dataService.collection.getCollectionFilters().single$.subscribe(res => {
this.allFilters = res.collectionFilters;
});
const filtersFormArray = this.detailForm.get('filters') as UntypedFormArray;
const inheritFiltersControl = this.detailForm.get('inheritFilters') as UntypedFormControl;
this.inheritFilters$ = inheritFiltersControl.valueChanges.pipe(distinctUntilChanged());
this.updatedFilters$ = merge(filtersFormArray.statusChanges, this.filterRemoved$).pipe(
debounceTime(200),
filter(() => filtersFormArray.touched),
map(() =>
this.mapOperationsToInputs(this.filters, filtersFormArray.value).filter(_filter => {
// ensure all the arguments have valid values. E.g. a newly-added
// filter will not yet have valid values
for (const arg of _filter.arguments) {
if (arg.value === '') {
return false;
}
}
return true;
}),
),
);
this.parentId$ = this.route.paramMap.pipe(
map(pm => pm.get('parentId') || undefined),
switchMap(parentId => {
if (parentId) {
return of(parentId);
} else {
return this.entity$.pipe(map(collection => collection.parent?.id));
}
}),
);
}
ngOnDestroy() {
this.destroy();
}
getFilterDefinition(_filter: ConfigurableOperation): ConfigurableOperationDefinition | undefined {
return this.allFilters.find(f => f.code === _filter.code);
}
assetsChanged(): boolean {
return !!Object.values(this.assetChanges).length;
}
/**
* If creating a new Collection, automatically generate the slug based on the collection name.
*/
updateSlug(nameValue: string) {
const slugControl = this.detailForm.get(['slug']);
const currentTranslation = this.entity ? findTranslation(this.entity, this.languageCode) : undefined;
const currentSlugIsEmpty = !currentTranslation || !currentTranslation.slug;
if (slugControl && slugControl.pristine && currentSlugIsEmpty) {
slugControl.setValue(normalizeString(`${nameValue}`, '-'));
}
}
addFilter(collectionFilter: ConfigurableOperation) {
const filtersArray = this.detailForm.get('filters') as UntypedFormArray;
const argsHash = collectionFilter.args.reduce(
(output, arg) => ({
...output,
[arg.name]: getConfigArgValue(arg.value),
}),
{},
);
filtersArray.push(
this.formBuilder.control({
code: collectionFilter.code,
args: argsHash,
}),
);
this.filters.push({
code: collectionFilter.code,
args: collectionFilter.args.map(a => ({ name: a.name, value: getConfigArgValue(a.value) })),
});
}
removeFilter(index: number) {
const filtersArray = this.detailForm.get('filters') as UntypedFormArray;
if (index !== -1) {
filtersArray.removeAt(index);
filtersArray.markAsDirty();
filtersArray.markAsTouched();
this.filters.splice(index, 1);
this.filterRemoved$.next();
}
}
create() {
if (!this.detailForm.dirty) {
return;
}
const input = this.getUpdatedCollection(
{
id: '',
createdAt: '',
updatedAt: '',
languageCode: this.languageCode,
name: '',
slug: '',
isPrivate: false,
breadcrumbs: [],
description: '',
featuredAsset: null,
assets: [],
translations: [],
inheritFilters: true,
filters: [],
parent: {} as any,
children: null,
},
this.detailForm,
this.languageCode,
) as CreateCollectionInput;
const parentId = this.route.snapshot.paramMap.get('parentId');
if (parentId) {
input.parentId = parentId;
}
this.dataService.collection.createCollection(input).subscribe(
data => {
this.notificationService.success(_('common.notify-create-success'), {
entity: 'Collection',
});
this.assetChanges = {};
this.detailForm.markAsPristine();
this.changeDetector.markForCheck();
this.router.navigate(['../', data.createCollection.id], { relativeTo: this.route });
},
err => {
this.notificationService.error(_('common.notify-create-error'), {
entity: 'Collection',
});
},
);
}
save() {
combineLatest(this.entity$, this.languageCode$)
.pipe(
take(1),
mergeMap(([category, languageCode]) => {
const input = this.getUpdatedCollection(
category,
this.detailForm,
languageCode,
) as UpdateCollectionInput;
return this.dataService.collection.updateCollection(input);
}),
)
.subscribe(
() => {
this.assetChanges = {};
this.detailForm.markAsPristine();
this.changeDetector.markForCheck();
this.notificationService.success(_('common.notify-update-success'), {
entity: 'Collection',
});
this.contentsComponent.refresh();
},
err => {
this.notificationService.error(_('common.notify-update-error'), {
entity: 'Collection',
});
},
);
}
canDeactivate(): boolean {
return super.canDeactivate() && !this.assetChanges.assets && !this.assetChanges.featuredAsset;
}
toggleLivePreview() {
this.livePreview = !this.livePreview;
this.localStorageService.set('livePreviewCollectionContents', this.livePreview);
}
trackByFn(index: number, item: ConfigurableOperation) {
return JSON.stringify(item);
}
/**
* Sets the values of the form on changes to the category or current language.
*/
protected setFormValues(entity: CollectionFragment, languageCode: LanguageCode) {
const currentTranslation = findTranslation(entity, languageCode);
this.detailForm.patchValue({
name: currentTranslation ? currentTranslation.name : '',
slug: currentTranslation ? currentTranslation.slug : '',
description: currentTranslation ? currentTranslation.description : '',
visible: !entity.isPrivate,
inheritFilters: entity.inheritFilters,
});
const formArray = this.detailForm.get('filters') as UntypedFormArray;
if (formArray.length !== entity.filters.length) {
formArray.clear();
this.filters = [];
entity.filters.forEach(f => this.addFilter(f));
}
if (this.customFields.length) {
this.setCustomFieldFormValues(
this.customFields,
this.detailForm.get(['customFields']),
entity,
currentTranslation,
);
}
}
/**
* Given a category and the value of the form, this method creates an updated copy of the category which
* can then be persisted to the API.
*/
private getUpdatedCollection(
category: CollectionFragment,
form: typeof this.detailForm,
languageCode: LanguageCode,
): CreateCollectionInput | UpdateCollectionInput {
const updatedCategory = createUpdatedTranslatable({
translatable: category,
updatedFields: form.value,
customFieldConfig: this.customFields,
languageCode,
defaultTranslation: {
languageCode,
name: category.name || '',
slug: category.slug || '',
description: category.description || '',
},
});
return {
...updatedCategory,
assetIds: this.assetChanges.assets?.map(a => a.id),
featuredAssetId: this.assetChanges.featuredAsset?.id,
isPrivate: !form.value.visible,
filters: this.mapOperationsToInputs(this.filters, this.detailForm.value.filters),
};
}
/**
* Maps an array of conditions or actions to the input format expected by the GraphQL API.
*/
private mapOperationsToInputs(
operations: ConfigurableOperation[],
formValueOperations: any,
): ConfigurableOperationInput[] {
return operations.map((o, i) => ({
code: o.code,
arguments: Object.entries(formValueOperations[i].args).map(([name, value], j) => ({
name,
value: encodeConfigArgValue(value),
})),
}));
}
}
|
import { Pipe, PipeTransform } from '@angular/core';
import { GetCollectionListQuery, ItemOf } from '@vendure/admin-ui/core';
/**
* Removes the root collection and self breadcrumb from the collection breadcrumb list.
*/
@Pipe({
name: 'collectionBreadcrumb',
})
export class CollectionBreadcrumbPipe implements PipeTransform {
transform(value: ItemOf<GetCollectionListQuery, 'collections'>): unknown {
return value?.breadcrumbs.slice(1, -1);
}
}
|
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
BulkAction,
createBulkAssignToChannelAction,
createBulkDeleteAction,
createBulkRemoveFromChannelAction,
DataService,
DuplicateEntityDialogComponent,
GetCollectionListQuery,
ItemOf,
ModalService,
MoveCollectionInput,
NotificationService,
Permission,
} from '@vendure/admin-ui/core';
import { EMPTY } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { CollectionPartial } from '../collection-tree/collection-tree.types';
import { MoveCollectionsDialogComponent } from '../move-collections-dialog/move-collections-dialog.component';
import { CollectionListComponent } from './collection-list.component';
export const deleteCollectionsBulkAction = createBulkDeleteAction<
ItemOf<GetCollectionListQuery, 'collections'>
>({
location: 'collection-list',
requiresPermission: userPermissions =>
userPermissions.includes(Permission.DeleteCollection) ||
userPermissions.includes(Permission.DeleteCatalog),
getItemName: item => item.name,
bulkDelete: (dataService, ids) =>
dataService.collection.deleteCollections(ids).pipe(map(res => res.deleteCollections)),
});
export const moveCollectionsBulkAction: BulkAction<CollectionPartial, CollectionListComponent> = {
location: 'collection-list',
label: _('catalog.move-collections'),
icon: 'drag-handle',
requiresPermission: userPermissions =>
userPermissions.includes(Permission.UpdateCatalog) ||
userPermissions.includes(Permission.UpdateCollection),
onClick: ({ injector, selection, hostComponent, clearSelection }) => {
const modalService = injector.get(ModalService);
const dataService = injector.get(DataService);
const notificationService = injector.get(NotificationService);
modalService
.fromComponent(MoveCollectionsDialogComponent, {
size: 'xl',
closable: true,
})
.pipe(
switchMap(result => {
if (result) {
const inputs: MoveCollectionInput[] = selection.map(c => ({
collectionId: c.id,
parentId: result.id,
index: 0,
}));
return dataService.collection.moveCollection(inputs);
} else {
return EMPTY;
}
}),
)
.subscribe(result => {
notificationService.success(_('catalog.move-collections-success'), {
count: selection.length,
});
clearSelection();
hostComponent.refresh();
});
},
};
export const assignCollectionsToChannelBulkAction = createBulkAssignToChannelAction<
ItemOf<GetCollectionListQuery, 'collections'>
>({
location: 'collection-list',
requiresPermission: userPermissions =>
userPermissions.includes(Permission.UpdateCatalog) ||
userPermissions.includes(Permission.UpdateCollection),
getItemName: item => item.name,
bulkAssignToChannel: (dataService, collectionIds, channelIds) =>
channelIds.map(channelId =>
dataService.collection
.assignCollectionsToChannel({
collectionIds,
channelId,
})
.pipe(map(res => res.assignCollectionsToChannel)),
),
});
export const removeCollectionsFromChannelBulkAction = createBulkRemoveFromChannelAction<
ItemOf<GetCollectionListQuery, 'collections'>
>({
location: 'collection-list',
requiresPermission: userPermissions =>
userPermissions.includes(Permission.DeleteCatalog) ||
userPermissions.includes(Permission.DeleteCollection),
getItemName: item => item.name,
bulkRemoveFromChannel: (dataService, collectionIds, channelId) =>
dataService.collection
.removeCollectionsFromChannel({
channelId: channelId,
collectionIds,
})
.pipe(map(res => res.removeCollectionsFromChannel)),
});
export const duplicateCollectionsBulkAction: BulkAction<
ItemOf<GetCollectionListQuery, 'collections'>,
CollectionListComponent
> = {
location: 'collection-list',
label: _('common.duplicate'),
icon: 'copy',
onClick: ({ injector, selection, hostComponent, clearSelection }) => {
const modalService = injector.get(ModalService);
modalService
.fromComponent(DuplicateEntityDialogComponent<ItemOf<GetCollectionListQuery, 'collections'>>, {
locals: {
entities: selection,
entityName: 'Collection',
title: _('catalog.duplicate-collections'),
getEntityName: entity => entity.name,
},
})
.subscribe(result => {
if (result) {
clearSelection();
hostComponent.refresh();
}
});
},
};
|
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
DataService,
GetCollectionListDocument,
GetCollectionListQuery,
ItemOf,
LanguageCode,
NotificationService,
TypedBaseListComponent,
} from '@vendure/admin-ui/core';
import { combineLatest, Observable, of } from 'rxjs';
import { distinctUntilChanged, map, switchMap, takeUntil } from 'rxjs/operators';
import { CollectionOrderEvent } from '../collection-data-table/collection-data-table.component';
@Component({
selector: 'vdr-collection-list',
templateUrl: './collection-list.component.html',
styleUrls: ['./collection-list.component.scss', './collection-list-common.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CollectionListComponent
extends TypedBaseListComponent<typeof GetCollectionListDocument, 'collections'>
implements OnInit
{
activeCollectionId$: Observable<string | null>;
activeCollectionIndex$: Observable<number>;
activeCollectionTitle$: Observable<string>;
subCollections$: Observable<Array<ItemOf<GetCollectionListQuery, 'collections'>>>;
expandedIds: string[] = [];
readonly customFields = this.getCustomFieldConfig('Collection');
readonly filters = this.createFilterCollection()
.addIdFilter()
.addDateFilters()
.addFilter({
name: 'slug',
label: _('common.slug'),
type: { kind: 'text' },
filterField: 'slug',
})
.addFilter({
name: 'visibility',
type: { kind: 'boolean' },
label: _('common.visibility'),
toFilterInput: value => ({
isPrivate: { eq: !value },
}),
})
.addCustomFieldFilters(this.customFields)
.connectToRoute(this.route);
readonly sorts = this.createSortCollection()
.defaultSort('position', 'ASC')
.addSort({ name: 'createdAt' })
.addSort({ name: 'updatedAt' })
.addSort({ name: 'name' })
.addSort({ name: 'slug' })
.addSort({ name: 'position' })
.addCustomFieldSorts(this.customFields)
.connectToRoute(this.route);
constructor(protected dataService: DataService, private notificationService: NotificationService) {
super();
super.configure({
document: GetCollectionListDocument,
getItems: data => data.collections,
setVariables: (skip, _take) => {
const topLevelOnly =
this.searchTermControl.value === '' && this.filters.activeFilters.length === 0
? true
: undefined;
return {
options: {
skip,
take: _take,
filter: {
name: { contains: this.searchTermControl.value },
...this.filters.createFilterInput(),
},
topLevelOnly,
sort: this.sorts.createSortInput(),
},
};
},
refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges],
});
}
ngOnInit() {
super.ngOnInit();
this.activeCollectionId$ = this.route.paramMap.pipe(
map(pm => pm.get('contents')),
distinctUntilChanged(),
);
const expandedIds$ = this.route.queryParamMap.pipe(
map(qpm => qpm.get('expanded')),
distinctUntilChanged(),
map(ids => (ids ? ids.split(',') : [])),
);
expandedIds$.pipe(takeUntil(this.destroy$)).subscribe(ids => {
this.expandedIds = ids;
});
this.subCollections$ = combineLatest(expandedIds$, this.refresh$).pipe(
switchMap(([ids]) => {
if (ids.length) {
return this.dataService.collection
.getCollections({
take: 999,
filter: {
parentId: { in: ids },
},
})
.mapStream(data => data.collections.items);
} else {
return of([]);
}
}),
);
this.activeCollectionTitle$ = combineLatest(
this.activeCollectionId$,
this.items$,
this.subCollections$,
).pipe(
map(([id, collections, subCollections]) => {
if (id) {
const match = [...collections, ...subCollections].find(c => c.id === id);
return match ? match.name : '';
}
return '';
}),
);
this.activeCollectionIndex$ = combineLatest(
this.activeCollectionId$,
this.items$,
this.subCollections$,
).pipe(
map(([id, collections, subCollections]) => {
if (id) {
const allCollections: typeof collections = [];
for (const collection of collections) {
allCollections.push(collection);
const subCollectionMatches = subCollections.filter(
c => c.parentId && c.parentId === collection.id,
);
allCollections.push(...subCollectionMatches);
}
return allCollections.findIndex(c => c.id === id);
}
return -1;
}),
);
}
onRearrange(event: CollectionOrderEvent) {
this.dataService.collection.moveCollection([event]).subscribe({
next: () => {
this.notificationService.success(_('common.notify-saved-changes'));
this.refresh();
},
error: err => {
this.notificationService.error(_('common.notify-save-changes-error'));
},
});
}
closeContents() {
const params = { ...this.route.snapshot.params };
delete params.contents;
this.router.navigate(['./', params], { relativeTo: this.route, queryParamsHandling: 'preserve' });
}
setLanguage(code: LanguageCode) {
this.dataService.client.setContentLanguage(code).subscribe();
}
toggleExpanded(collection: ItemOf<GetCollectionListQuery, 'collections'>) {
let expandedIds = this.expandedIds;
if (!expandedIds.includes(collection.id)) {
expandedIds.push(collection.id);
} else {
expandedIds = expandedIds.filter(id => id !== collection.id);
}
this.router.navigate(['./'], {
queryParams: {
expanded: expandedIds.filter(id => !!id).join(','),
},
queryParamsHandling: 'merge',
relativeTo: this.route,
});
}
}
|
import { arrayToTree, HasParent, RootNode, TreeNode } from './array-to-tree';
describe('arrayToTree()', () => {
it('preserves ordering', () => {
const result1 = arrayToTree([
{ id: '13', parent: { id: '1' } },
{ id: '12', parent: { id: '1' } },
]);
expect(result1.children.map(i => i.id)).toEqual(['13', '12']);
const result2 = arrayToTree([
{ id: '12', parent: { id: '1' } },
{ id: '13', parent: { id: '1' } },
]);
expect(result2.children.map(i => i.id)).toEqual(['12', '13']);
});
it('converts an array to a tree', () => {
const input: HasParent[] = [
{ id: '12', parent: { id: '1' } },
{ id: '13', parent: { id: '1' } },
{ id: '132', parent: { id: '13' } },
{ id: '131', parent: { id: '13' } },
{ id: '1211', parent: { id: '121' } },
{ id: '121', parent: { id: '12' } },
];
const result = arrayToTree(input);
expect(result).toEqual({
id: '1',
children: [
{
id: '12',
parent: { id: '1' },
expanded: false,
children: [
{
id: '121',
parent: { id: '12' },
expanded: false,
children: [{ id: '1211', expanded: false, parent: { id: '121' }, children: [] }],
},
],
},
{
id: '13',
parent: { id: '1' },
expanded: false,
children: [
{ id: '132', expanded: false, parent: { id: '13' }, children: [] },
{ id: '131', expanded: false, parent: { id: '13' }, children: [] },
],
},
],
});
});
it('preserves expanded state from existing RootNode', () => {
const existing: RootNode<TreeNode<any>> = {
id: '1',
children: [
{
id: '12',
parent: { id: '1' },
expanded: false,
children: [
{
id: '121',
parent: { id: '12' },
expanded: false,
children: [{ id: '1211', expanded: false, parent: { id: '121' }, children: [] }],
},
],
},
{
id: '13',
parent: { id: '1' },
expanded: true,
children: [
{ id: '132', expanded: true, parent: { id: '13' }, children: [] },
{ id: '131', expanded: false, parent: { id: '13' }, children: [] },
],
},
],
};
const input: HasParent[] = [
{ id: '12', parent: { id: '1' } },
{ id: '13', parent: { id: '1' } },
{ id: '132', parent: { id: '13' } },
{ id: '131', parent: { id: '13' } },
{ id: '1211', parent: { id: '121' } },
{ id: '121', parent: { id: '12' } },
];
const result = arrayToTree(input, existing);
expect(result).toEqual(existing);
});
});
|
export type HasParent = { id: string; parent?: { id: string } | null };
export type TreeNode<T extends HasParent> = T & { children: Array<TreeNode<T>>; expanded: boolean };
export type RootNode<T extends HasParent> = { id?: string; children: Array<TreeNode<T>> };
/**
* Builds a tree from an array of nodes which have a parent.
* Based on https://stackoverflow.com/a/31247960/772859, modified to preserve ordering.
*/
export function arrayToTree<T extends HasParent>(
nodes: T[],
currentState?: RootNode<T>,
expandedIds: string[] = [],
): RootNode<T> {
const topLevelNodes: Array<TreeNode<T>> = [];
const mappedArr: { [id: string]: TreeNode<T> } = {};
const currentStateMap = treeToMap(currentState);
// First map the nodes of the array to an object -> create a hash table.
for (const node of nodes) {
mappedArr[node.id] = { ...(node as any), children: [] };
}
for (const id of nodes.map(n => n.id)) {
if (mappedArr.hasOwnProperty(id)) {
const mappedElem = mappedArr[id];
mappedElem.expanded = currentStateMap.get(id)?.expanded ?? expandedIds.includes(id);
const parent = mappedElem.parent;
if (!parent) {
continue;
}
// If the element is not at the root level, add it to its parent array of children.
const parentIsRoot = !mappedArr[parent.id];
if (!parentIsRoot) {
if (mappedArr[parent.id]) {
mappedArr[parent.id].children.push(mappedElem);
} else {
mappedArr[parent.id] = { children: [mappedElem] } as any;
}
} else {
topLevelNodes.push(mappedElem);
}
}
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const rootId = topLevelNodes.length ? topLevelNodes[0].parent!.id : undefined;
return { id: rootId, children: topLevelNodes };
}
/**
* Converts an existing tree (as generated by the arrayToTree function) into a flat
* Map. This is used to persist certain states (e.g. `expanded`) when re-building the
* tree.
*/
function treeToMap<T extends HasParent>(tree?: RootNode<T>): Map<string, TreeNode<T>> {
const nodeMap = new Map<string, TreeNode<T>>();
function visit(node: TreeNode<T>) {
nodeMap.set(node.id, node);
node.children.forEach(visit);
}
if (tree) {
visit(tree as TreeNode<T>);
}
return nodeMap;
}
|
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Input,
OnChanges,
OnDestroy,
OnInit,
Optional,
SimpleChanges,
SkipSelf,
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DataService, Permission, SelectionManager } from '@vendure/admin-ui/core';
import { Observable, Subscription } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
import { RootNode, TreeNode } from './array-to-tree';
import { CollectionTreeService } from './collection-tree.service';
import { CollectionPartial } from './collection-tree.types';
@Component({
selector: 'vdr-collection-tree-node',
templateUrl: './collection-tree-node.component.html',
styleUrls: ['./collection-tree-node.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CollectionTreeNodeComponent implements OnInit, OnChanges, OnDestroy {
depth = 0;
parentName: string;
@Input() collectionTree: TreeNode<CollectionPartial>;
@Input() activeCollectionId: string;
@Input() expandAll = false;
@Input() selectionManager: SelectionManager<CollectionPartial>;
hasUpdatePermission$: Observable<boolean>;
hasDeletePermission$: Observable<boolean>;
moveListItems: Array<{ path: string; id: string }> = [];
private subscription: Subscription;
constructor(
@SkipSelf() @Optional() private parent: CollectionTreeNodeComponent,
private dataService: DataService,
private collectionTreeService: CollectionTreeService,
private router: Router,
private route: ActivatedRoute,
private changeDetectorRef: ChangeDetectorRef,
) {
if (parent) {
this.depth = parent.depth + 1;
}
}
ngOnInit() {
this.parentName = this.collectionTree.name || '<root>';
const permissions$ = this.dataService.client
.userStatus()
.mapStream(data => data.userStatus.permissions)
.pipe(shareReplay(1));
this.hasUpdatePermission$ = permissions$.pipe(
map(
perms =>
perms.includes(Permission.UpdateCatalog) || perms.includes(Permission.UpdateCollection),
),
);
this.hasDeletePermission$ = permissions$.pipe(
map(
perms =>
perms.includes(Permission.DeleteCatalog) || perms.includes(Permission.DeleteCollection),
),
);
this.subscription = this.selectionManager?.selectionChanges$.subscribe(() =>
this.changeDetectorRef.markForCheck(),
);
}
ngOnChanges(changes: SimpleChanges) {
const expandAllChange = changes['expandAll'];
if (expandAllChange) {
if (expandAllChange.previousValue === true && expandAllChange.currentValue === false) {
this.collectionTree.children.forEach(c => (c.expanded = false));
}
}
}
ngOnDestroy() {
this.subscription?.unsubscribe();
}
trackByFn(index: number, item: CollectionPartial) {
return item.id;
}
toggleExpanded(collection: TreeNode<CollectionPartial>) {
collection.expanded = !collection.expanded;
let expandedIds = this.route.snapshot.queryParamMap.get('expanded')?.split(',') ?? [];
if (collection.expanded) {
expandedIds.push(collection.id);
} else {
expandedIds = expandedIds.filter(id => id !== collection.id);
}
this.router.navigate(['./'], {
queryParams: {
expanded: expandedIds.filter(id => !!id).join(','),
},
queryParamsHandling: 'merge',
relativeTo: this.route,
});
}
getMoveListItems(collection: CollectionPartial) {
this.moveListItems = this.collectionTreeService.getMoveListItems(collection);
}
move(collection: CollectionPartial, parentId: string) {
this.collectionTreeService.onMove({
index: 0,
parentId,
collectionId: collection.id,
});
}
moveUp(collection: CollectionPartial, currentIndex: number) {
if (!collection.parent) {
return;
}
this.collectionTreeService.onMove({
index: currentIndex - 1,
parentId: collection.parent.id,
collectionId: collection.id,
});
}
moveDown(collection: CollectionPartial, currentIndex: number) {
if (!collection.parent) {
return;
}
this.collectionTreeService.onMove({
index: currentIndex + 1,
parentId: collection.parent.id,
collectionId: collection.id,
});
}
drop(event: CdkDragDrop<CollectionPartial | RootNode<CollectionPartial>>) {
moveItemInArray(this.collectionTree.children, event.previousIndex, event.currentIndex);
this.collectionTreeService.onDrop(event);
}
delete(id: string) {
this.collectionTreeService.onDelete(id);
}
}
|
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
SimpleChanges,
} from '@angular/core';
import { Collection, SelectionManager } from '@vendure/admin-ui/core';
import { arrayToTree, RootNode } from './array-to-tree';
import { CollectionTreeService } from './collection-tree.service';
import { CollectionPartial, RearrangeEvent } from './collection-tree.types';
@Component({
selector: 'vdr-collection-tree',
templateUrl: 'collection-tree.component.html',
styleUrls: ['./collection-tree.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [CollectionTreeService],
})
export class CollectionTreeComponent implements OnInit, OnChanges {
@Input() collections: CollectionPartial[];
@Input() activeCollectionId: string;
@Input() expandAll = false;
@Input() expandedIds: string[] = [];
@Input() selectionManager: SelectionManager<CollectionPartial>;
@Output() rearrange = new EventEmitter<RearrangeEvent>();
@Output() deleteCollection = new EventEmitter<string>();
collectionTree: RootNode<CollectionPartial>;
constructor(private collectionTreeService: CollectionTreeService) {}
ngOnChanges(changes: SimpleChanges) {
if ('collections' in changes && this.collections) {
this.collectionTree = arrayToTree(this.collections, this.collectionTree, this.expandedIds);
this.collectionTreeService.setCollectionTree(this.collectionTree);
this.collectionTreeService.resetMoveList();
}
}
ngOnInit() {
this.collectionTreeService.rearrange$.subscribe(event => this.rearrange.emit(event));
this.collectionTreeService.delete$.subscribe(id => this.deleteCollection.emit(id));
}
}
|
import { CdkDragDrop } from '@angular/cdk/drag-drop';
import { Injectable, OnDestroy } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { RootNode, TreeNode } from './array-to-tree';
import { CollectionPartial, RearrangeEvent } from './collection-tree.types';
/**
* Facilitates communication between the CollectionTreeComponent and child CollectionTreeNodeComponents
* without introducing a cyclic dependency.
*/
@Injectable()
export class CollectionTreeService implements OnDestroy {
private allMoveListItems: Array<{ path: string; id: string; ancestorIdPath: Set<string> }> = [];
private collectionTree: RootNode<CollectionPartial>;
private _rearrange$ = new Subject<RearrangeEvent>();
private _delete$ = new Subject<string>();
public rearrange$: Observable<RearrangeEvent>;
public delete$: Observable<string>;
constructor() {
this.rearrange$ = this._rearrange$.asObservable();
this.delete$ = this._delete$.asObservable();
}
ngOnDestroy() {
this._rearrange$.complete();
this._delete$.complete();
}
setCollectionTree(tree: RootNode<CollectionPartial>) {
this.collectionTree = tree;
}
resetMoveList() {
this.allMoveListItems = [];
}
getMoveListItems(collection: CollectionPartial) {
if (this.allMoveListItems.length === 0) {
this.allMoveListItems = this.calculateAllMoveListItems();
}
return this.allMoveListItems.filter(
item =>
item.id !== collection.id &&
!item.ancestorIdPath.has(collection.id) &&
item.id !== collection.parent?.id,
);
}
onDrop(event: CdkDragDrop<CollectionPartial | RootNode<CollectionPartial>>) {
const item = event.item.data as CollectionPartial;
const newParent = event.container.data;
const newParentId = newParent.id;
if (newParentId == null) {
throw new Error(`Could not determine the ID of the root Collection`);
}
this._rearrange$.next({
collectionId: item.id,
parentId: newParentId,
index: event.currentIndex,
});
}
onMove(event: RearrangeEvent) {
this._rearrange$.next(event);
}
onDelete(id: string) {
this._delete$.next(id);
}
private calculateAllMoveListItems() {
const visit = (
node: TreeNode<any>,
parentPath: string[],
ancestorIdPath: Set<string>,
output: Array<{ path: string; id: string; ancestorIdPath: Set<string> }>,
) => {
const path = parentPath.concat(node.name);
output.push({ path: path.slice(1).join(' / ') || 'root', id: node.id, ancestorIdPath });
node.children.forEach(child =>
visit(child, path, new Set<string>([...ancestorIdPath, node.id]), output),
);
return output;
};
return visit(this.collectionTree, [], new Set<string>(), []);
}
}
|
import { CollectionFragment } from '@vendure/admin-ui/core';
export type RearrangeEvent = { collectionId: string; parentId: string; index: number };
export type CollectionPartial = Pick<CollectionFragment, 'id' | 'parent' | 'name'>;
|
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Dialog, GetProductVariantOptionsQuery } from '@vendure/admin-ui/core';
@Component({
selector: 'vdr-confirm-variant-deletion-dialog',
templateUrl: './confirm-variant-deletion-dialog.component.html',
styleUrls: ['./confirm-variant-deletion-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ConfirmVariantDeletionDialogComponent implements Dialog<boolean> {
resolveWith: (result?: boolean) => void;
variants: NonNullable<GetProductVariantOptionsQuery['product']>['variants'] = [];
confirm() {
this.resolveWith(true);
}
cancel() {
this.resolveWith();
}
}
|
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { CreateFacetValueInput, Dialog, LanguageCode } from '@vendure/admin-ui/core';
import { normalizeString } from '@vendure/common/lib/normalize-string';
@Component({
selector: 'vdr-create-facet-value-dialog',
templateUrl: './create-facet-value-dialog.component.html',
styleUrls: ['./create-facet-value-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CreateFacetValueDialogComponent implements Dialog<CreateFacetValueInput> {
resolveWith: (result?: CreateFacetValueInput) => void;
languageCode: LanguageCode;
form = this.formBuilder.group({
name: ['', Validators.required],
code: ['', Validators.required],
});
facetId: string;
constructor(private formBuilder: FormBuilder) {}
updateCode() {
const nameControl = this.form.get('name');
const codeControl = this.form.get('code');
if (nameControl && codeControl && codeControl.pristine) {
codeControl.setValue(normalizeString(`${nameControl.value}`, '-'));
}
}
confirm() {
const { name, code } = this.form.value;
if (!name || !code) {
return;
}
this.resolveWith({
facetId: this.facetId,
code,
translations: [{ languageCode: this.languageCode, name }],
});
}
cancel() {
this.resolveWith();
}
}
|
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import {
CreateProductOptionGroupInput,
Dialog,
findTranslation,
GetProductVariantOptionsQuery,
LanguageCode,
ServerConfigService,
} from '@vendure/admin-ui/core';
import { normalizeString } from '@vendure/common/lib/normalize-string';
@Component({
selector: 'vdr-create-product-option-group-dialog',
templateUrl: './create-product-option-group-dialog.component.html',
styleUrls: ['./create-product-option-group-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CreateProductOptionGroupDialogComponent implements Dialog<CreateProductOptionGroupInput> {
resolveWith: (result?: CreateProductOptionGroupInput) => void;
languageCode: LanguageCode;
form = this.formBuilder.group({
name: ['', Validators.required],
code: ['', Validators.required],
});
constructor(private formBuilder: FormBuilder) {}
updateCode() {
const nameControl = this.form.get('name');
const codeControl = this.form.get('code');
if (nameControl && codeControl && codeControl.pristine) {
codeControl.setValue(normalizeString(`${nameControl.value}`, '-'));
}
}
confirm() {
const { name, code } = this.form.value;
if (!name || !code) {
return;
}
this.resolveWith({
code,
options: [],
translations: [{ languageCode: this.languageCode, name }],
});
}
cancel() {
this.resolveWith();
}
}
|
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, FormRecord, Validators } from '@angular/forms';
import {
CreateProductVariantInput,
CurrencyCode,
Dialog,
GetProductVariantOptionsQuery,
} from '@vendure/admin-ui/core';
import { notNullOrUndefined } from '@vendure/common/lib/shared-utils';
import { combineLatest } from 'rxjs';
@Component({
selector: 'vdr-create-product-variant-dialog',
templateUrl: './create-product-variant-dialog.component.html',
styleUrls: ['./create-product-variant-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CreateProductVariantDialogComponent implements Dialog<CreateProductVariantInput>, OnInit {
resolveWith: (result?: CreateProductVariantInput) => void;
product: NonNullable<GetProductVariantOptionsQuery['product']>;
form = this.formBuilder.group({
name: ['', Validators.required],
sku: ['', Validators.required],
price: [''],
options: this.formBuilder.record<string>({}),
});
existingVariant: NonNullable<GetProductVariantOptionsQuery['product']>['variants'][number] | undefined;
currencyCode: CurrencyCode;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.currencyCode = this.product.variants[0]?.currencyCode;
for (const optionGroup of this.product.optionGroups) {
(this.form.get('options') as FormRecord).addControl(
optionGroup.code,
new FormControl('', Validators.required),
);
}
const optionsRecord = this.form.get('options') as FormRecord;
optionsRecord.valueChanges.subscribe(value => {
const nameControl = this.form.get('name');
const allNull = Object.values(value).every(v => v == null);
if (!allNull && value && nameControl && !nameControl.dirty) {
const name = Object.entries(value)
.map(
([groupCode, optionId]) =>
this.product.optionGroups
.find(og => og.code === groupCode)
?.options.find(o => o.id === optionId)?.name,
)
.join(' ');
nameControl.setValue(`${this.product.name} ${name}`);
}
const allSelected = Object.values(value).every(v => v != null);
if (allSelected) {
this.existingVariant = this.product.variants.find(v =>
Object.entries(value).every(
([groupCode, optionId]) =>
v.options.find(o => o.groupId === this.getGroupIdFromCode(groupCode))?.id ===
optionId,
),
);
}
});
}
confirm() {
const { name, sku, options, price } = this.form.value;
if (!name || !sku || !options || !price) {
return;
}
const optionIds = Object.values(options).filter(notNullOrUndefined);
this.resolveWith({
productId: this.product.id,
sku,
price: Number(price),
optionIds,
translations: [
{
languageCode: this.product.languageCode,
name,
},
],
});
}
cancel() {
this.resolveWith();
}
private getGroupCodeFromId(id: string): string {
return this.product.optionGroups.find(og => og.id === id)?.code ?? '';
}
private getGroupIdFromCode(code: string): string {
return this.product.optionGroups.find(og => og.code === code)?.id ?? '';
}
}
|
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import {
FormBuilder,
FormControl,
FormGroup,
FormRecord,
UntypedFormControl,
UntypedFormGroup,
Validators,
} from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
CreateFacetInput,
createUpdatedTranslatable,
DataService,
DeletionResult,
FACET_WITH_VALUE_LIST_FRAGMENT,
FacetWithValueListFragment,
findTranslation,
getCustomFieldsDefaults,
GetFacetDetailDocument,
GetFacetDetailQuery,
GetFacetDetailQueryVariables,
LanguageCode,
ModalService,
NotificationService,
Permission,
TypedBaseDetailComponent,
UpdateFacetInput,
UpdateFacetValueInput,
} from '@vendure/admin-ui/core';
import { SortOrder } from '@vendure/common/lib/generated-types';
import { normalizeString } from '@vendure/common/lib/normalize-string';
import { notNullOrUndefined } from '@vendure/common/lib/shared-utils';
import { gql } from 'apollo-angular';
import { BehaviorSubject, combineLatest, EMPTY, forkJoin, Observable } from 'rxjs';
import { debounceTime, map, mergeMap, switchMap, take, takeUntil } from 'rxjs/operators';
import { CreateFacetValueDialogComponent } from '../create-facet-value-dialog/create-facet-value-dialog.component';
export const FACET_DETAIL_QUERY = gql`
query GetFacetDetail($id: ID!, $facetValueListOptions: FacetValueListOptions) {
facet(id: $id) {
...FacetWithValueList
}
}
${FACET_WITH_VALUE_LIST_FRAGMENT}
`;
type ValueItem =
| FacetWithValueListFragment['valueList']['items'][number]
| { id: string; name: string; code: string };
@Component({
selector: 'vdr-facet-detail',
templateUrl: './facet-detail.component.html',
styleUrls: ['./facet-detail.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FacetDetailComponent
extends TypedBaseDetailComponent<typeof GetFacetDetailDocument, 'facet'>
implements OnInit, OnDestroy
{
readonly customFields = this.getCustomFieldConfig('Facet');
readonly customValueFields = this.getCustomFieldConfig('FacetValue');
detailForm = this.formBuilder.group({
facet: this.formBuilder.group({
code: ['', Validators.required],
name: '',
visible: true,
customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)),
}),
values: this.formBuilder.record<
FormGroup<{
id: FormControl<string>;
name: FormControl<string>;
code: FormControl<string>;
customFields: FormGroup;
}>
>({}),
});
currentPage = 1;
itemsPerPage = 10;
totalItems = 0;
filterControl = new FormControl('');
values$ = new BehaviorSubject<ValueItem[]>([]);
readonly updatePermission = [Permission.UpdateCatalog, Permission.UpdateFacet];
constructor(
private changeDetector: ChangeDetectorRef,
protected dataService: DataService,
private formBuilder: FormBuilder,
private notificationService: NotificationService,
private modalService: ModalService,
) {
super();
}
ngOnInit() {
this.init();
this.filterControl.valueChanges
.pipe(debounceTime(200), takeUntil(this.destroy$))
.subscribe(filterTerm => {
this.currentPage = 1;
this.fetchFacetValues(this.currentPage, this.itemsPerPage, filterTerm);
});
}
ngOnDestroy() {
this.destroy();
}
updateCode(currentCode: string, nameValue: string) {
if (!currentCode) {
const codeControl = this.detailForm.get(['facet', 'code']);
if (codeControl && codeControl.pristine) {
codeControl.setValue(normalizeString(nameValue, '-'));
}
}
}
updateValueCode(currentCode: string, nameValue: string, valueId: string) {
if (!currentCode) {
const codeControl = this.detailForm.get(['values', valueId, 'code']);
if (codeControl && codeControl.pristine) {
codeControl.setValue(normalizeString(nameValue, '-'));
}
}
}
customValueFieldIsSet(index: number, name: string): boolean {
return !!this.detailForm.get(['values', index, 'customFields', name]);
}
addFacetValue() {
this.modalService
.fromComponent(CreateFacetValueDialogComponent, {
locals: {
languageCode: this.languageCode,
facetId: this.id,
},
})
.pipe(
switchMap(result => {
if (!result) {
return EMPTY;
} else {
return this.dataService.facet.createFacetValues([result]);
}
}),
)
.subscribe(result => {
if (result.createFacetValues) {
this.notificationService.success(_('common.notify-create-success'), {
entity: 'FacetValue',
});
this.currentPage = 1;
this.fetchFacetValues(this.currentPage, this.itemsPerPage);
}
});
}
create() {
const facetForm = this.detailForm.get('facet') as (typeof this.detailForm)['controls']['facet'];
if (!facetForm || !facetForm.dirty) {
return;
}
const newFacet = this.getUpdatedFacet(
{
id: '',
createdAt: '',
updatedAt: '',
isPrivate: false,
languageCode: this.languageCode,
name: '',
code: '',
translations: [],
},
facetForm,
this.languageCode,
) as CreateFacetInput;
this.dataService.facet.createFacet(newFacet).subscribe(
data => {
this.notificationService.success(_('common.notify-create-success'), { entity: 'Facet' });
this.detailForm.markAsPristine();
this.changeDetector.markForCheck();
this.router.navigate(['../', data.createFacet.id], { relativeTo: this.route });
},
err => {
this.notificationService.error(_('common.notify-create-error'), {
entity: 'Facet',
});
},
);
}
save() {
const valuesFormRecord = this.detailForm.get(
'values',
) as (typeof this.detailForm)['controls']['values'];
combineLatest(this.entity$, this.languageCode$)
.pipe(
take(1),
mergeMap(([facet, languageCode]) => {
const facetForm = this.detailForm.get(
'facet',
) as (typeof this.detailForm)['controls']['facet'];
const updateOperations: Array<Observable<any>> = [];
if (facetForm && facetForm.dirty) {
const updatedFacetInput = this.getUpdatedFacet(
facet,
facetForm,
languageCode,
) as UpdateFacetInput;
if (updatedFacetInput) {
updateOperations.push(this.dataService.facet.updateFacet(updatedFacetInput));
}
}
if (valuesFormRecord && valuesFormRecord.dirty) {
const updatedValues = this.getUpdatedFacetValues(valuesFormRecord, languageCode);
if (updatedValues.length) {
updateOperations.push(this.dataService.facet.updateFacetValues(updatedValues));
}
}
return forkJoin(updateOperations);
}),
)
.subscribe(
() => {
this.detailForm.markAsPristine();
this.changeDetector.markForCheck();
this.notificationService.success(_('common.notify-update-success'), { entity: 'Facet' });
},
err => {
this.notificationService.error(_('common.notify-update-error'), {
entity: 'Facet',
});
},
);
}
deleteFacetValue(facetValueId: string) {
this.showModalAndDelete(facetValueId)
.pipe(
switchMap(response => {
if (response.result === DeletionResult.DELETED) {
return [true];
} else {
return this.showModalAndDelete(facetValueId, response.message || '').pipe(
map(r => r.result === DeletionResult.DELETED),
);
}
}),
switchMap(deleted =>
deleted
? this.dataService.query(GetFacetDetailDocument, {
id: this.id,
}).single$
: [],
),
)
.subscribe(
() => {
this.notificationService.success(_('common.notify-delete-success'), {
entity: 'FacetValue',
});
this.fetchFacetValues(this.currentPage, this.itemsPerPage, this.filterControl.value);
},
err => {
this.notificationService.error(_('common.notify-delete-error'), {
entity: 'FacetValue',
});
},
);
}
private showModalAndDelete(facetValueId: string, message?: string) {
return this.modalService
.dialog({
title: _('catalog.confirm-delete-facet-value'),
body: message,
buttons: [
{ type: 'secondary', label: _('common.cancel') },
{ type: 'danger', label: _('common.delete'), returnValue: true },
],
})
.pipe(
switchMap(result =>
result ? this.dataService.facet.deleteFacetValues([facetValueId], !!message) : EMPTY,
),
map(result => result.deleteFacetValues[0]),
);
}
protected setCurrentPage(newPage: number) {
this.currentPage = newPage;
this.fetchFacetValues(this.currentPage, this.itemsPerPage, this.filterControl.value);
}
protected setItemsPerPage(itemsPerPage: number) {
this.itemsPerPage = itemsPerPage;
this.fetchFacetValues(this.currentPage, this.itemsPerPage, this.filterControl.value);
}
private fetchFacetValues(currentPage: number, itemsPerPage: number, filterTerm?: string | null) {
this.dataService
.query<GetFacetDetailQuery, GetFacetDetailQueryVariables>(FACET_DETAIL_QUERY, {
id: this.id,
facetValueListOptions: {
take: itemsPerPage,
skip: (currentPage - 1) * itemsPerPage,
sort: {
createdAt: SortOrder.DESC,
},
...(filterTerm ? { filter: { name: { contains: filterTerm } } } : {}),
},
})
.single$.subscribe(({ facet }) => {
if (facet) {
this.values$.next([...facet.valueList.items]);
this.totalItems = facet.valueList.totalItems;
this.setFacetValueFormValues(facet, this.languageCode);
}
});
}
/**
* Sets the values of the form on changes to the facet or current language.
*/
protected setFormValues(facet: FacetWithValueListFragment, languageCode: LanguageCode) {
const currentTranslation = findTranslation(facet, languageCode);
this.detailForm.patchValue({
facet: {
code: facet.code,
visible: !facet.isPrivate,
name: currentTranslation?.name ?? '',
},
});
if (this.customFields.length) {
this.setCustomFieldFormValues(
this.customFields,
this.detailForm.get(['facet', 'customFields']),
facet,
currentTranslation,
);
}
this.values$.next([...facet.valueList.items]);
this.totalItems = facet.valueList.totalItems;
this.setFacetValueFormValues(facet, languageCode);
}
private setFacetValueFormValues(facet: FacetWithValueListFragment, languageCode: LanguageCode) {
const currentValuesFormGroup = this.detailForm.get('values') as FormRecord;
facet.valueList.items.forEach(value => {
const valueTranslation = findTranslation(value, languageCode);
const group = {
id: value.id,
code: value.code,
name: valueTranslation ? valueTranslation.name : '',
};
let valueControl = currentValuesFormGroup.get(value.id) as FormGroup;
if (!valueControl) {
valueControl = this.formBuilder.group(group);
currentValuesFormGroup.addControl(value.id, valueControl);
}
if (this.customValueFields.length) {
let customValueFieldsGroup = valueControl.get(['customFields']) as
| UntypedFormGroup
| undefined;
if (!customValueFieldsGroup) {
customValueFieldsGroup = new UntypedFormGroup({});
valueControl.addControl('customFields', customValueFieldsGroup);
}
if (customValueFieldsGroup) {
for (const fieldDef of this.customValueFields) {
const key = fieldDef.name;
const fieldValue =
fieldDef.type === 'localeString'
? (valueTranslation as any | undefined)?.customFields?.[key]
: (value as any).customFields[key];
const control = customValueFieldsGroup.get(key);
if (control) {
control.setValue(fieldValue);
} else {
customValueFieldsGroup.addControl(key, new UntypedFormControl(fieldValue));
}
}
}
}
});
}
/**
* Given a facet and the value of the detailForm, this method creates an updated copy of the facet which
* can then be persisted to the API.
*/
private getUpdatedFacet(
facet: Omit<FacetWithValueListFragment, 'valueList'>,
facetFormGroup: (typeof this.detailForm)['controls']['facet'],
languageCode: LanguageCode,
): CreateFacetInput | UpdateFacetInput {
const input = createUpdatedTranslatable({
translatable: facet,
updatedFields: facetFormGroup.value,
customFieldConfig: this.customFields,
languageCode,
defaultTranslation: {
languageCode,
name: facet.name || '',
},
});
input.isPrivate = !facetFormGroup.value.visible;
return input;
}
/**
* Given an array of facet values and the values from the detailForm, this method creates a new array
* which can be persisted to the API via an updateFacetValues mutation.
*/
private getUpdatedFacetValues(
valuesFormGroup: FormGroup,
languageCode: LanguageCode,
): UpdateFacetValueInput[] {
const dirtyValueValues = Object.values(valuesFormGroup.controls)
.filter(c => c.dirty)
.map(c => c.value);
return dirtyValueValues
.map((value, i) =>
createUpdatedTranslatable({
translatable: value,
updatedFields: value,
customFieldConfig: this.customValueFields,
languageCode,
defaultTranslation: {
languageCode,
name: '',
},
}),
)
.filter(notNullOrUndefined);
}
}
|
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
BulkAction,
createBulkAssignToChannelAction,
createBulkDeleteAction,
createBulkRemoveFromChannelAction,
currentChannelIsNotDefault,
DataService,
DuplicateEntityDialogComponent,
getChannelCodeFromUserStatus,
GetFacetListQuery,
ItemOf,
ModalService,
NotificationService,
Permission,
RemoveFacetsFromChannelMutation,
} from '@vendure/admin-ui/core';
import { unique } from '@vendure/common/lib/unique';
import { EMPTY, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { FacetListComponent } from './facet-list.component';
export const deleteFacetsBulkAction = createBulkDeleteAction<ItemOf<GetFacetListQuery, 'facets'>>({
location: 'facet-list',
requiresPermission: userPermissions =>
userPermissions.includes(Permission.DeleteFacet) ||
userPermissions.includes(Permission.DeleteCatalog),
getItemName: item => item.name,
shouldRetryItem: (response, item) => !!response.message,
bulkDelete: (dataService, ids, retrying) =>
dataService.facet.deleteFacets(ids, retrying).pipe(map(res => res.deleteFacets)),
});
export const assignFacetsToChannelBulkAction = createBulkAssignToChannelAction<
ItemOf<GetFacetListQuery, 'facets'>
>({
location: 'facet-list',
requiresPermission: userPermissions =>
userPermissions.includes(Permission.UpdateCatalog) ||
userPermissions.includes(Permission.UpdateFacet),
getItemName: item => item.name,
bulkAssignToChannel: (dataService, facetIds, channelIds) =>
channelIds.map(channelId =>
dataService.facet
.assignFacetsToChannel({
facetIds,
channelId,
})
.pipe(map(res => res.assignFacetsToChannel)),
),
});
export const removeFacetsFromChannelBulkAction = createBulkRemoveFromChannelAction<
ItemOf<GetFacetListQuery, 'facets'>,
RemoveFacetsFromChannelMutation['removeFacetsFromChannel'][number]
>({
location: 'facet-list',
requiresPermission: userPermissions =>
userPermissions.includes(Permission.DeleteCatalog) ||
userPermissions.includes(Permission.DeleteFacet),
getItemName: item => item.name,
bulkRemoveFromChannel: (dataService, facetIds, channelId, retrying) =>
dataService.facet
.removeFacetsFromChannel({
channelId: channelId,
facetIds,
force: retrying,
})
.pipe(map(res => res.removeFacetsFromChannel)),
isErrorResult: result => (result.__typename === 'FacetInUseError' ? result.message : undefined),
});
export const removeFacetsFromChannelBulkAction2: BulkAction<
ItemOf<GetFacetListQuery, 'facets'>,
FacetListComponent
> = {
location: 'facet-list',
label: _('catalog.remove-from-channel'),
getTranslationVars: ({ injector }) => getChannelCodeFromUserStatus(injector.get(DataService)),
icon: 'layers',
iconClass: 'is-warning',
requiresPermission: userPermissions =>
userPermissions.includes(Permission.UpdateFacet) ||
userPermissions.includes(Permission.UpdateCatalog),
isVisible: ({ injector }) => currentChannelIsNotDefault(injector.get(DataService)),
onClick: ({ injector, selection, hostComponent, clearSelection }) => {
const modalService = injector.get(ModalService);
const dataService = injector.get(DataService);
const notificationService = injector.get(NotificationService);
const activeChannelId$ = dataService.client
.userStatus()
.mapSingle(({ userStatus }) => userStatus.activeChannelId);
function showModalAndDelete(facetIds: string[], message?: string) {
return modalService
.dialog({
title: _('catalog.remove-from-channel'),
translationVars: {
count: selection.length,
},
size: message ? 'lg' : 'md',
body: message,
buttons: [
{ type: 'secondary', label: _('common.cancel') },
{
type: 'danger',
label: message ? _('common.force-remove') : _('common.remove'),
returnValue: true,
},
],
})
.pipe(
switchMap(res =>
res
? activeChannelId$.pipe(
switchMap(activeChannelId =>
activeChannelId
? dataService.facet.removeFacetsFromChannel({
channelId: activeChannelId,
facetIds,
force: !!message,
})
: EMPTY,
),
map(res2 => res2.removeFacetsFromChannel),
)
: EMPTY,
),
);
}
showModalAndDelete(unique(selection.map(f => f.id)))
.pipe(
switchMap(result => {
let removedCount = selection.length;
const errors: string[] = [];
const errorIds: string[] = [];
let i = 0;
for (const item of result) {
if (item.__typename === 'FacetInUseError') {
errors.push(item.message);
errorIds.push(selection[i]?.id);
removedCount--;
}
i++;
}
if (0 < errorIds.length) {
return showModalAndDelete(errorIds, errors.join('\n')).pipe(
map(result2 => {
const notRemovedCount = result2.filter(
r => r.__typename === 'FacetInUseError',
).length;
return selection.length - notRemovedCount;
}),
);
} else {
return of(removedCount);
}
}),
switchMap(removedCount =>
removedCount
? getChannelCodeFromUserStatus(dataService).then(({ channelCode }) => ({
channelCode,
removedCount,
}))
: EMPTY,
),
)
.subscribe(({ removedCount, channelCode }) => {
if (removedCount) {
hostComponent.refresh();
clearSelection();
notificationService.success(_('catalog.notify-remove-facets-from-channel-success'), {
count: removedCount,
channelCode,
});
}
});
},
};
export const duplicateFacetsBulkAction: BulkAction<
ItemOf<GetFacetListQuery, 'facets'>,
FacetListComponent
> = {
location: 'facet-list',
label: _('common.duplicate'),
icon: 'copy',
onClick: ({ injector, selection, hostComponent, clearSelection }) => {
const modalService = injector.get(ModalService);
modalService
.fromComponent(DuplicateEntityDialogComponent<ItemOf<GetFacetListQuery, 'facets'>>, {
locals: {
entities: selection,
entityName: 'Facet',
title: _('catalog.duplicate-facets'),
getEntityName: entity => entity.name,
},
})
.subscribe(result => {
if (result) {
clearSelection();
hostComponent.refresh();
}
});
},
};
|
import { Component, OnInit } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import {
DataService,
FACET_WITH_VALUE_LIST_FRAGMENT,
GetFacetListDocument,
GetFacetListQuery,
ItemOf,
LanguageCode,
TypedBaseListComponent,
} from '@vendure/admin-ui/core';
import { gql } from 'apollo-angular';
export const FACET_LIST_QUERY = gql`
query GetFacetList($options: FacetListOptions, $facetValueListOptions: FacetValueListOptions) {
facets(options: $options) {
items {
...FacetWithValueList
}
totalItems
}
}
${FACET_WITH_VALUE_LIST_FRAGMENT}
`;
@Component({
selector: 'vdr-facet-list',
templateUrl: './facet-list.component.html',
styleUrls: ['./facet-list.component.scss'],
})
export class FacetListComponent
extends TypedBaseListComponent<typeof GetFacetListDocument, 'facets'>
implements OnInit
{
readonly initialLimit = 3;
displayLimit: { [id: string]: number } = {};
readonly customFields = this.getCustomFieldConfig('Facet');
readonly filters = this.createFilterCollection()
.addIdFilter()
.addDateFilters()
.addFilter({
name: 'visibility',
type: { kind: 'boolean' },
label: _('common.visibility'),
toFilterInput: value => ({
isPrivate: { eq: !value },
}),
})
.addCustomFieldFilters(this.customFields)
.connectToRoute(this.route);
readonly sorts = this.createSortCollection()
.defaultSort('createdAt', 'DESC')
.addSort({ name: 'id' })
.addSort({ name: 'createdAt' })
.addSort({ name: 'updatedAt' })
.addSort({ name: 'name' })
.addSort({ name: 'code' })
.addCustomFieldSorts(this.customFields)
.connectToRoute(this.route);
constructor(protected dataService: DataService) {
super();
super.configure({
document: GetFacetListDocument,
getItems: data => data.facets,
setVariables: (skip, take) => ({
options: {
skip,
take,
filter: {
name: {
contains: this.searchTermControl.value,
},
...this.filters.createFilterInput(),
},
sort: this.sorts.createSortInput(),
},
facetValueListOptions: {
take: 100,
},
}),
refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges],
});
}
toggleDisplayLimit(facet: ItemOf<GetFacetListQuery, 'facets'>) {
if (this.displayLimit[facet.id] === facet.valueList.items.length) {
this.displayLimit[facet.id] = this.initialLimit;
} else {
this.displayLimit[facet.id] = facet.valueList.items.length;
}
}
setLanguage(code: LanguageCode) {
this.dataService.client.setContentLanguage(code).subscribe();
}
}
|
import { Component, ElementRef, EventEmitter, OnInit, Output, QueryList, ViewChildren } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms';
import {
CurrencyCode,
DataService,
GetStockLocationListDocument,
GetStockLocationListQuery,
ItemOf,
} from '@vendure/admin-ui/core';
import { generateAllCombinations } from '@vendure/common/lib/shared-utils';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { OptionValueInputComponent } from '../option-value-input/option-value-input.component';
const DEFAULT_VARIANT_CODE = '__DEFAULT_VARIANT__';
export type CreateVariantValues = {
optionValues: string[];
enabled: boolean;
sku: string;
price: number;
stock: number;
};
export type CreateProductVariantsConfig = {
groups: Array<{ name: string; values: string[] }>;
variants: CreateVariantValues[];
stockLocationId: string;
};
@Component({
selector: 'vdr-generate-product-variants',
templateUrl: './generate-product-variants.component.html',
styleUrls: ['./generate-product-variants.component.scss'],
})
export class GenerateProductVariantsComponent implements OnInit {
@Output() variantsChange = new EventEmitter<CreateProductVariantsConfig>();
@ViewChildren('optionGroupName', { read: ElementRef }) groupNameInputs: QueryList<ElementRef>;
optionGroups: Array<{ name: string; values: Array<{ name: string; locked: boolean }> }> = [];
currencyCode: CurrencyCode;
variants: Array<{ id: string; values: string[] }>;
variantFormValues: {
[id: string]: FormGroup<{
optionValues: FormControl<string[]>;
enabled: FormControl<boolean>;
price: FormControl<number>;
sku: FormControl<string>;
stock: FormControl<number>;
}>;
} = {};
stockLocations$: Observable<Array<ItemOf<GetStockLocationListQuery, 'stockLocations'>>>;
selectedStockLocationId: string | null = null;
constructor(private dataService: DataService, private formBuilder: FormBuilder) {}
ngOnInit() {
this.dataService.settings.getActiveChannel().single$.subscribe(data => {
this.currencyCode = data.activeChannel.defaultCurrencyCode;
});
this.stockLocations$ = this.dataService
.query(GetStockLocationListDocument, {
options: {
take: 999,
},
})
.refetchOnChannelChange()
.mapStream(({ stockLocations }) => stockLocations.items)
.pipe(
tap(items => {
if (items.length) {
this.selectedStockLocationId = items[0].id;
}
}),
);
this.generateVariants();
}
addOption() {
this.optionGroups.push({ name: '', values: [] });
const index = this.optionGroups.length - 1;
setTimeout(() => {
const input = this.groupNameInputs.get(index)?.nativeElement;
input?.focus();
});
}
removeOption(name: string) {
this.optionGroups = this.optionGroups.filter(g => g.name !== name);
this.generateVariants();
}
generateVariants() {
const totalValuesCount = this.optionGroups.reduce((sum, group) => sum + group.values.length, 0);
const groups = totalValuesCount
? this.optionGroups.map(g => g.values.map(v => v.name))
: [[DEFAULT_VARIANT_CODE]];
this.variants = generateAllCombinations(groups).map(values => ({ id: values.join('|'), values }));
this.variants.forEach((variant, index) => {
if (!this.variantFormValues[variant.id]) {
const formGroup = this.formBuilder.nonNullable.group({
optionValues: [variant.values],
enabled: true as boolean,
price: this.copyFromDefault(variant.id, 'price', 0),
sku: this.copyFromDefault(variant.id, 'sku', ''),
stock: this.copyFromDefault(variant.id, 'stock', 0),
});
formGroup.valueChanges.subscribe(() => this.onFormChange());
if (index === 0) {
formGroup.get('price')?.valueChanges.subscribe(value => {
this.copyValuesToPristine('price', formGroup.get('price'));
});
formGroup.get('sku')?.valueChanges.subscribe(value => {
this.copyValuesToPristine('sku', formGroup.get('sku'));
});
formGroup.get('stock')?.valueChanges.subscribe(value => {
this.copyValuesToPristine('stock', formGroup.get('stock'));
});
}
this.variantFormValues[variant.id] = formGroup;
}
});
}
trackByFn(index: number, variant: { name: string; values: string[] }) {
return variant.values.join('|');
}
handleEnter(event: KeyboardEvent, optionValueInputComponent: OptionValueInputComponent) {
event.preventDefault();
event.stopPropagation();
optionValueInputComponent.focus();
}
copyValuesToPristine(field: 'price' | 'sku' | 'stock', formControl: AbstractControl | null) {
if (!formControl) {
return;
}
Object.values(this.variantFormValues).forEach(formGroup => {
const correspondingFormControl = formGroup.get(field) as FormControl;
if (correspondingFormControl && correspondingFormControl.pristine) {
correspondingFormControl.setValue(formControl.value, { emitEvent: false });
}
});
}
onFormChange() {
const variantsToCreate = this.variants
.map(v => this.variantFormValues[v.id].value as CreateVariantValues)
.filter(v => v.enabled);
this.variantsChange.emit({
groups: this.optionGroups.map(og => ({ name: og.name, values: og.values.map(v => v.name) })),
variants: variantsToCreate,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
stockLocationId: this.selectedStockLocationId!,
});
}
private copyFromDefault<T extends keyof CreateVariantValues>(
variantId: string,
prop: T,
value: CreateVariantValues[T],
): CreateVariantValues[T] {
return variantId !== DEFAULT_VARIANT_CODE
? (this.variantFormValues[DEFAULT_VARIANT_CODE].get(prop)?.value as CreateVariantValues[T])
: value;
}
}
|
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { DataService, Dialog, GetCollectionListQuery, I18nService, ItemOf } from '@vendure/admin-ui/core';
import { BehaviorSubject, combineLatest, Observable, of, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, startWith, switchMap, tap } from 'rxjs/operators';
@Component({
selector: 'vdr-move-collections-dialog',
templateUrl: './move-collections-dialog.component.html',
styleUrls: ['./move-collections-dialog.component.scss', '../collection-list/collection-list-common.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MoveCollectionsDialogComponent
implements OnInit, Dialog<ItemOf<GetCollectionListQuery, 'collections'>>
{
resolveWith: (result?: ItemOf<GetCollectionListQuery, 'collections'>) => void;
searchTermControl = new FormControl('');
items$: Observable<Array<ItemOf<GetCollectionListQuery, 'collections'>>>;
totalItems$: Observable<number>;
currentPage$ = new BehaviorSubject(1);
itemsPerPage$ = new BehaviorSubject(10);
expandedIds$ = new Subject<string[]>();
expandedIds: string[] = [];
subCollections$: Observable<Array<ItemOf<GetCollectionListQuery, 'collections'>>>;
constructor(private dataService: DataService, private i18nService: I18nService) {}
ngOnInit() {
const getCollectionsResult = this.dataService.collection.getCollections();
const searchTerm$ = this.searchTermControl.valueChanges.pipe(
debounceTime(250),
distinctUntilChanged(),
startWith(''),
);
const currentPage$ = this.currentPage$.pipe(distinctUntilChanged());
const itemsPerPage$ = this.itemsPerPage$.pipe(distinctUntilChanged());
combineLatest(searchTerm$, currentPage$, itemsPerPage$).subscribe(
([searchTerm, currentPage, itemsPerPage]) => {
const topLevelOnly = searchTerm === '';
getCollectionsResult.ref.refetch({
options: {
skip: (currentPage - 1) * itemsPerPage,
take: itemsPerPage,
filter: {
name: { contains: searchTerm },
},
topLevelOnly,
},
});
},
);
const rootCollectionId$ = this.dataService.collection
.getCollections({
take: 1,
topLevelOnly: true,
})
.mapSingle(data => data.collections.items[0].parentId);
this.items$ = combineLatest(
getCollectionsResult.mapStream(({ collections }) => collections),
rootCollectionId$,
).pipe(
map(([collections, rootCollectionId]) => [
...(rootCollectionId
? [
{
id: rootCollectionId,
name: this.i18nService.translate('catalog.root-collection'),
slug: '',
parentId: '__',
position: 0,
featuredAsset: null,
children: [],
breadcrumbs: [],
isPrivate: false,
createdAt: '',
updatedAt: '',
} satisfies ItemOf<GetCollectionListQuery, 'collections'>,
]
: []),
...collections.items,
]),
);
this.totalItems$ = getCollectionsResult.mapStream(data => data.collections.totalItems);
this.subCollections$ = this.expandedIds$.pipe(
tap(val => (this.expandedIds = val)),
switchMap(ids => {
if (ids.length) {
return this.dataService.collection
.getCollections({
take: 999,
filter: {
parentId: { in: ids },
},
})
.mapStream(data => data.collections.items);
} else {
return of([]);
}
}),
);
}
toggleExpanded(collection: ItemOf<GetCollectionListQuery, 'collections'>) {
let expandedIds = this.expandedIds;
if (!expandedIds.includes(collection.id)) {
expandedIds.push(collection.id);
} else {
expandedIds = expandedIds.filter(id => id !== collection.id);
}
this.expandedIds$.next(expandedIds);
}
}
|
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
OnChanges,
OnInit,
Output,
Provider,
QueryList,
SimpleChanges,
ViewChild,
ViewChildren,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { unique } from '@vendure/common/lib/unique';
export const OPTION_VALUE_INPUT_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OptionValueInputComponent),
multi: true,
};
interface Option {
id?: string;
name: string;
locked: boolean;
}
@Component({
selector: 'vdr-option-value-input',
templateUrl: './option-value-input.component.html',
styleUrls: ['./option-value-input.component.scss'],
changeDetection: ChangeDetectionStrategy.Default,
providers: [OPTION_VALUE_INPUT_VALUE_ACCESSOR],
})
export class OptionValueInputComponent implements ControlValueAccessor {
@Input() groupName = '';
@ViewChild('textArea', { static: true }) textArea: ElementRef<HTMLTextAreaElement>;
@ViewChildren('editNameInput', { read: ElementRef }) nameInputs: QueryList<ElementRef>;
@Input() options: Option[];
@Output() add = new EventEmitter<Option>();
@Output() remove = new EventEmitter<Option>();
@Output() edit = new EventEmitter<{ index: number; option: Option }>();
@Input() disabled = false;
input = '';
isFocussed = false;
lastSelected = false;
formValue: Option[];
editingIndex = -1;
onChangeFn: (value: any) => void;
onTouchFn: (value: any) => void;
get optionValues(): Option[] {
return this.formValue ?? this.options ?? [];
}
constructor(private changeDetector: ChangeDetectorRef) {}
registerOnChange(fn: any): void {
this.onChangeFn = fn;
}
registerOnTouched(fn: any): void {
this.onTouchFn = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this.changeDetector.markForCheck();
}
writeValue(obj: any): void {
this.formValue = obj || [];
}
focus() {
this.textArea.nativeElement.focus();
}
editName(index: number, event: MouseEvent) {
const optionValue = this.optionValues[index];
if (!optionValue.locked && !optionValue.id) {
event.cancelBubble = true;
this.editingIndex = index;
const input = this.nameInputs.get(index)?.nativeElement;
setTimeout(() => input?.focus());
}
}
updateOption(index: number, event: InputEvent) {
const optionValue = this.optionValues[index];
const newName = (event.target as HTMLInputElement).value;
if (optionValue) {
if (newName) {
optionValue.name = newName;
this.edit.emit({ index, option: optionValue });
}
this.editingIndex = -1;
}
}
removeOption(option: Option) {
if (!option.locked) {
if (this.formValue) {
this.formValue = this.formValue?.filter(o => o.name !== option.name);
this.onChangeFn(this.formValue);
} else {
this.remove.emit(option);
}
}
}
handleKey(event: KeyboardEvent) {
switch (event.key) {
case ',':
case 'Enter':
this.addOptionValue();
event.preventDefault();
break;
case 'Backspace':
if (this.lastSelected) {
this.removeLastOption();
this.lastSelected = false;
} else if (this.input === '') {
this.lastSelected = true;
}
break;
default:
this.lastSelected = false;
}
}
handleBlur() {
this.isFocussed = false;
this.addOptionValue();
}
private addOptionValue() {
const options = this.parseInputIntoOptions(this.input).filter(option => {
// do not add an option with the same name
// as an existing option
const existing = this.options ?? this.formValue;
return !existing?.find(o => o?.name === option.name);
});
if (!this.formValue && this.options) {
for (const option of options) {
this.add.emit(option);
}
} else {
this.formValue = unique([...this.formValue, ...options]);
this.onChangeFn(this.formValue);
}
this.input = '';
}
private parseInputIntoOptions(input: string): Option[] {
return input
.split(/[,\n]/)
.map(s => s.trim())
.filter(s => s !== '')
.map(s => ({ name: s, locked: false }));
}
private removeLastOption() {
if (this.optionValues.length) {
const option = this.optionValues[this.optionValues.length - 1];
this.removeOption(option);
}
}
}
|
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 0