n8n/packages/nodes-base/nodes/WooCommerce/WooCommerce.node.ts

593 lines
19 KiB
TypeScript
Raw Normal View History

import { IExecuteFunctions } from 'n8n-core';
2020-02-16 10:43:51 -08:00
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
2020-02-16 10:43:51 -08:00
} from 'n8n-workflow';
import {
adjustMetadata,
2021-08-04 09:38:48 -07:00
setFields,
setMetadata,
toSnakeCase,
2020-02-16 10:43:51 -08:00
woocommerceApiRequest,
woocommerceApiRequestAllItems,
} from './GenericFunctions';
import { productFields, productOperations } from './ProductDescription';
import { orderFields, orderOperations } from './OrderDescription';
import { IDimension, IImage, IProduct } from './ProductInterface';
2020-02-24 16:19:04 -08:00
import {
IAddress,
ICouponLine,
IFeeLine,
ILineItem,
IOrder,
2020-02-24 16:19:04 -08:00
IShoppingLine,
} from './OrderInterface';
2020-02-16 10:43:51 -08:00
import { customerFields, customerOperations } from './descriptions';
2020-02-16 10:43:51 -08:00
export class WooCommerce implements INodeType {
description: INodeTypeDescription = {
displayName: 'WooCommerce',
name: 'wooCommerce',
icon: 'file:wooCommerce.svg',
2020-02-16 10:43:51 -08:00
group: ['output'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume WooCommerce API',
defaults: {
name: 'WooCommerce',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'wooCommerceApi',
required: true,
2020-10-22 06:46:03 -07:00
},
2020-02-16 10:43:51 -08:00
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
refactor: Apply more nodelinting rules (#3324) * :pencil2: Alphabetize lint rules * :fire: Remove duplicates * :zap: Update `lintfix` script * :shirt: Apply `node-param-operation-without-no-data-expression` (#3329) * :shirt: Apply `node-param-operation-without-no-data-expression` * :shirt: Add exceptions * :shirt: Apply `node-param-description-weak` (#3328) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-value-duplicate` (#3331) * :shirt: Apply `node-param-description-miscased-json` (#3337) * :shirt: Apply `node-param-display-name-excess-inner-whitespace` (#3335) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-type-options-missing-from-limit` (#3336) * Rule workig as intended * :pencil2: Uncomment rules Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-name-duplicate` (#3338) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-description-wrong-for-simplify` (#3334) * :zap: fix * :zap: exceptions * :zap: changed rule ignoring from file to line * :shirt: Apply `node-param-resource-without-no-data-expression` (#3339) * :shirt: Apply `node-param-display-name-untrimmed` (#3341) * :shirt: Apply `node-param-display-name-miscased-id` (#3340) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-resource-with-plural-option` (#3342) * :shirt: Apply `node-param-description-wrong-for-upsert` (#3333) * :zap: fix * :zap: replaced record with contact in description * :zap: fix Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-description-identical-to-name` (#3343) * :shirt: Apply `node-param-option-name-containing-star` (#3347) * :shirt: Apply `node-param-display-name-wrong-for-update-fields` (#3348) * :shirt: Apply `node-param-option-name-wrong-for-get-all` (#3345) * :zap: fix * :zap: exceptions * :shirt: Apply node-param-display-name-wrong-for-simplify (#3344) * Rule working as intended * Uncomented other rules * :shirt: Undo and add exceptions Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :zap: Alphabetize lint rules * :zap: Restore `lintfix` script Co-authored-by: Michael Kret <88898367+michael-radency@users.noreply.github.com> Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com>
2022-05-20 14:47:24 -07:00
noDataExpression: true,
2020-02-16 10:43:51 -08:00
options: [
{
name: 'Customer',
value: 'customer',
},
2020-02-24 16:19:04 -08:00
{
name: 'Order',
value: 'order',
},
{
name: 'Product',
value: 'product',
},
2020-02-16 10:43:51 -08:00
],
default: 'product',
},
...customerOperations,
...customerFields,
2020-02-16 10:43:51 -08:00
...productOperations,
...productFields,
2020-02-24 16:19:04 -08:00
...orderOperations,
...orderFields,
2020-02-16 10:43:51 -08:00
],
};
methods = {
loadOptions: {
// Get all the available categories to display them to user so that he can
// select them easily
async getCategories(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const categories = await woocommerceApiRequestAllItems.call(
this,
'GET',
'/products/categories',
{},
);
2020-02-16 10:43:51 -08:00
for (const category of categories) {
const categoryName = category.name;
const categoryId = category.id;
returnData.push({
name: categoryName,
value: categoryId,
});
}
return returnData;
},
// Get all the available tags to display them to user so that he can
// select them easily
async getTags(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const tags = await woocommerceApiRequestAllItems.call(this, 'GET', '/products/tags', {});
for (const tag of tags) {
const tagName = tag.name;
const tagId = tag.id;
returnData.push({
name: tagName,
value: tagId,
});
}
return returnData;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
refactor: Apply `eslint-plugin-n8n-nodes-base` autofixable rules (#3174) * :zap: Initial setup * :shirt: Update `.eslintignore` * :shirt: Autofix node-param-default-missing (#3173) * :fire: Remove duplicate key * :shirt: Add exceptions * :package: Update package-lock.json * :shirt: Apply `node-class-description-inputs-wrong-trigger-node` (#3176) * :shirt: Apply `node-class-description-inputs-wrong-regular-node` (#3177) * :shirt: Apply `node-class-description-outputs-wrong` (#3178) * :shirt: Apply `node-execute-block-double-assertion-for-items` (#3179) * :shirt: Apply `node-param-default-wrong-for-collection` (#3180) * :shirt: Apply node-param-default-wrong-for-boolean (#3181) * Autofixed default missing * Autofixed booleans, worked well * :zap: Fix params * :rewind: Undo exempted autofixes * :package: Update package-lock.json * :shirt: Apply node-class-description-missing-subtitle (#3182) * :zap: Fix missing comma * :shirt: Apply `node-param-default-wrong-for-fixed-collection` (#3184) * :shirt: Add exception for `node-class-description-missing-subtitle` * :shirt: Apply `node-param-default-wrong-for-multi-options` (#3185) * :shirt: Apply `node-param-collection-type-unsorted-items` (#3186) * Missing coma * :shirt: Apply `node-param-default-wrong-for-simplify` (#3187) * :shirt: Apply `node-param-description-comma-separated-hyphen` (#3190) * :shirt: Apply `node-param-description-empty-string` (#3189) * :shirt: Apply `node-param-description-excess-inner-whitespace` (#3191) * Rule looks good * Add whitespace rule in eslint config * :zao: fix * :shirt: Apply `node-param-description-identical-to-display-name` (#3193) * :shirt: Apply `node-param-description-missing-for-ignore-ssl-issues` (#3195) * :rewind: Revert ":zao: fix" This reverts commit ef8a76f3dfedffd1bdccf3178af8a8d90cf5a55c. * :shirt: Apply `node-param-description-missing-for-simplify` (#3196) * :shirt: Apply `node-param-description-missing-final-period` (#3194) * Rule working as intended * Add rule to eslint * :shirt: Apply node-param-description-missing-for-return-all (#3197) * :zap: Restore `lintfix` command Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com> Co-authored-by: Omar Ajoue <krynble@gmail.com> Co-authored-by: agobrech <ael.gobrecht@gmail.com> Co-authored-by: Michael Kret <michael.k@radency.com>
2022-04-22 09:29:51 -07:00
const length = items.length;
2020-02-16 10:43:51 -08:00
let responseData;
const qs: IDataObject = {};
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
for (let i = 0; i < length; i++) {
if (resource === 'customer') {
// **********************************************************************
// customer
// **********************************************************************
// https://woocommerce.github.io/woocommerce-rest-api-docs/?shell#customer-properties
if (operation === 'create') {
// ----------------------------------------
// customer: create
// ----------------------------------------
// https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#create-a-customer
const body = {
email: this.getNodeParameter('email', i),
} as IDataObject;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
if (Object.keys(additionalFields).length) {
Object.assign(body, adjustMetadata(additionalFields));
}
responseData = await woocommerceApiRequest.call(this, 'POST', '/customers', body);
} else if (operation === 'delete') {
// ----------------------------------------
// customer: delete
// ----------------------------------------
// https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#delete-a-customer
const customerId = this.getNodeParameter('customerId', i);
const qs: IDataObject = {
force: true, // required, customers do not support trashing
};
const endpoint = `/customers/${customerId}`;
responseData = await woocommerceApiRequest.call(this, 'DELETE', endpoint, {}, qs);
} else if (operation === 'get') {
// ----------------------------------------
// customer: get
// ----------------------------------------
// https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#retrieve-a-customer
const customerId = this.getNodeParameter('customerId', i);
const endpoint = `/customers/${customerId}`;
responseData = await woocommerceApiRequest.call(this, 'GET', endpoint);
} else if (operation === 'getAll') {
// ----------------------------------------
// customer: getAll
// ----------------------------------------
// https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#list-all-customers
const qs = {} as IDataObject;
const filters = this.getNodeParameter('filters', i) as IDataObject;
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
if (Object.keys(filters).length) {
Object.assign(qs, filters);
}
if (returnAll) {
responseData = await woocommerceApiRequestAllItems.call(
this,
'GET',
'/customers',
{},
qs,
);
} else {
qs.per_page = this.getNodeParameter('limit', i) as number;
responseData = await woocommerceApiRequest.call(this, 'GET', '/customers', {}, qs);
}
} else if (operation === 'update') {
// ----------------------------------------
// customer: update
// ----------------------------------------
// https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#update-a-customer
const body = {} as IDataObject;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
if (Object.keys(updateFields).length) {
Object.assign(body, adjustMetadata(updateFields));
}
const customerId = this.getNodeParameter('customerId', i);
const endpoint = `/customers/${customerId}`;
responseData = await woocommerceApiRequest.call(this, 'PUT', endpoint, body);
}
} else if (resource === 'product') {
2020-02-16 10:43:51 -08:00
//https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-product
if (operation === 'create') {
const name = this.getNodeParameter('name', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
2021-08-04 09:38:48 -07:00
const body: IProduct = {
2020-02-16 10:43:51 -08:00
name,
};
2021-08-04 09:38:48 -07:00
setFields(additionalFields, body);
2020-02-16 10:43:51 -08:00
if (additionalFields.categories) {
body.categories = (additionalFields.categories as string[]).map((category) => ({
id: parseInt(category, 10),
})) as unknown as IDataObject[];
2020-02-16 10:43:51 -08:00
}
const images = (this.getNodeParameter('imagesUi', i) as IDataObject)
.imagesValues as IImage[];
2020-02-16 10:43:51 -08:00
if (images) {
body.images = images;
}
const dimension = (this.getNodeParameter('dimensionsUi', i) as IDataObject)
.dimensionsValues as IDimension;
2020-02-16 10:43:51 -08:00
if (dimension) {
body.dimensions = dimension;
}
const metadata = (this.getNodeParameter('metadataUi', i) as IDataObject)
.metadataValues as IDataObject[];
2020-02-16 10:43:51 -08:00
if (metadata) {
body.meta_data = metadata;
}
responseData = await woocommerceApiRequest.call(this, 'POST', '/products', body);
}
//https://woocommerce.github.io/woocommerce-rest-api-docs/#update-a-product
if (operation === 'update') {
const productId = this.getNodeParameter('productId', i) as string;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
const body: IProduct = {};
2021-08-04 09:38:48 -07:00
setFields(updateFields, body);
const images = (this.getNodeParameter('imagesUi', i) as IDataObject)
.imagesValues as IImage[];
2020-02-16 10:43:51 -08:00
if (images) {
body.images = images;
}
const dimension = (this.getNodeParameter('dimensionsUi', i) as IDataObject)
.dimensionsValues as IDimension;
2020-02-16 10:43:51 -08:00
if (dimension) {
body.dimensions = dimension;
}
const metadata = (this.getNodeParameter('metadataUi', i) as IDataObject)
.metadataValues as IDataObject[];
2020-02-16 10:43:51 -08:00
if (metadata) {
body.meta_data = metadata;
}
responseData = await woocommerceApiRequest.call(
this,
'PUT',
`/products/${productId}`,
body,
);
2020-02-16 10:43:51 -08:00
}
//https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-a-product
if (operation === 'get') {
const productId = this.getNodeParameter('productId', i) as string;
responseData = await woocommerceApiRequest.call(
this,
'GET',
`/products/${productId}`,
{},
qs,
);
2020-02-16 10:43:51 -08:00
}
//https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-products
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const options = this.getNodeParameter('options', i) as IDataObject;
if (options.after) {
qs.after = options.after as string;
}
if (options.before) {
qs.before = options.before as string;
}
if (options.category) {
qs.category = options.category as string;
}
if (options.context) {
qs.context = options.context as string;
}
if (options.featured) {
qs.featured = options.featured as boolean;
}
if (options.maxPrice) {
qs.max_price = options.maxPrice as string;
}
if (options.minPrice) {
qs.max_price = options.minPrice as string;
}
if (options.order) {
qs.order = options.order as string;
}
if (options.orderBy) {
qs.orderby = options.orderBy as string;
}
if (options.search) {
qs.search = options.search as string;
}
if (options.sku) {
qs.sku = options.sku as string;
}
if (options.slug) {
qs.slug = options.slug as string;
}
if (options.status) {
qs.status = options.status as string;
}
if (options.stockStatus) {
qs.stock_status = options.stockStatus as string;
2020-02-16 10:43:51 -08:00
}
if (options.tag) {
qs.tag = options.tag as string;
}
if (options.taxClass) {
qs.tax_class = options.taxClass as string;
}
if (options.type) {
qs.type = options.type as string;
}
if (returnAll === true) {
responseData = await woocommerceApiRequestAllItems.call(
this,
'GET',
'/products',
{},
qs,
);
2020-02-16 10:43:51 -08:00
} else {
qs.per_page = this.getNodeParameter('limit', i) as number;
responseData = await woocommerceApiRequest.call(this, 'GET', '/products', {}, qs);
}
}
//https://woocommerce.github.io/woocommerce-rest-api-docs/#delete-a-product
if (operation === 'delete') {
const productId = this.getNodeParameter('productId', i) as string;
responseData = await woocommerceApiRequest.call(
this,
'DELETE',
`/products/${productId}`,
{},
{ force: true },
);
2020-02-16 10:43:51 -08:00
}
}
2020-02-24 16:19:04 -08:00
if (resource === 'order') {
//https://woocommerce.github.io/woocommerce-rest-api-docs/#create-an-order
if (operation === 'create') {
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IOrder = {};
2021-08-04 09:38:48 -07:00
setFields(additionalFields, body);
const billing = (this.getNodeParameter('billingUi', i) as IDataObject)
.billingValues as IAddress;
2020-02-24 16:19:04 -08:00
if (billing !== undefined) {
body.billing = billing;
toSnakeCase(billing as IDataObject);
}
const shipping = (this.getNodeParameter('shippingUi', i) as IDataObject)
.shippingValues as IAddress;
2020-02-24 16:19:04 -08:00
if (shipping !== undefined) {
body.shipping = shipping;
toSnakeCase(shipping as IDataObject);
}
const couponLines = (this.getNodeParameter('couponLinesUi', i) as IDataObject)
.couponLinesValues as ICouponLine[];
2020-02-24 16:19:04 -08:00
if (couponLines) {
body.coupon_lines = couponLines;
setMetadata(couponLines);
toSnakeCase(couponLines);
}
const feeLines = (this.getNodeParameter('feeLinesUi', i) as IDataObject)
.feeLinesValues as IFeeLine[];
2020-02-24 16:19:04 -08:00
if (feeLines) {
body.fee_lines = feeLines;
setMetadata(feeLines);
toSnakeCase(feeLines);
}
const lineItems = (this.getNodeParameter('lineItemsUi', i) as IDataObject)
.lineItemsValues as ILineItem[];
2020-02-24 16:19:04 -08:00
if (lineItems) {
body.line_items = lineItems;
setMetadata(lineItems);
toSnakeCase(lineItems);
//@ts-ignore
}
const metadata = (this.getNodeParameter('metadataUi', i) as IDataObject)
.metadataValues as IDataObject[];
2020-02-24 16:19:04 -08:00
if (metadata) {
body.meta_data = metadata;
}
const shippingLines = (this.getNodeParameter('shippingLinesUi', i) as IDataObject)
.shippingLinesValues as IShoppingLine[];
2020-02-24 16:19:04 -08:00
if (shippingLines) {
body.shipping_lines = shippingLines;
setMetadata(shippingLines);
toSnakeCase(shippingLines);
}
responseData = await woocommerceApiRequest.call(this, 'POST', '/orders', body);
}
//https://woocommerce.github.io/woocommerce-rest-api-docs/#update-an-order
if (operation === 'update') {
const orderId = this.getNodeParameter('orderId', i) as string;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
const body: IOrder = {};
2020-02-24 16:19:04 -08:00
if (updateFields.currency) {
body.currency = updateFields.currency as string;
}
if (updateFields.customerId) {
body.customer_id = parseInt(updateFields.customerId as string, 10);
}
if (updateFields.customerNote) {
body.customer_note = updateFields.customerNote as string;
}
if (updateFields.parentId) {
body.parent_id = parseInt(updateFields.parentId as string, 10);
}
if (updateFields.paymentMethodId) {
body.payment_method = updateFields.paymentMethodId as string;
2020-02-24 16:19:04 -08:00
}
if (updateFields.paymentMethodTitle) {
body.payment_method_title = updateFields.paymentMethodTitle as string;
2020-02-24 16:19:04 -08:00
}
if (updateFields.status) {
body.status = updateFields.status as string;
}
if (updateFields.transactionID) {
body.transaction_id = updateFields.transactionID as string;
}
const billing = (this.getNodeParameter('billingUi', i) as IDataObject)
.billingValues as IAddress;
2020-02-24 16:19:04 -08:00
if (billing !== undefined) {
body.billing = billing;
toSnakeCase(billing as IDataObject);
}
const shipping = (this.getNodeParameter('shippingUi', i) as IDataObject)
.shippingValues as IAddress;
2020-02-24 16:19:04 -08:00
if (shipping !== undefined) {
body.shipping = shipping;
toSnakeCase(shipping as IDataObject);
}
const couponLines = (this.getNodeParameter('couponLinesUi', i) as IDataObject)
.couponLinesValues as ICouponLine[];
2020-02-24 16:19:04 -08:00
if (couponLines) {
body.coupon_lines = couponLines;
setMetadata(couponLines);
toSnakeCase(couponLines);
}
const feeLines = (this.getNodeParameter('feeLinesUi', i) as IDataObject)
.feeLinesValues as IFeeLine[];
2020-02-24 16:19:04 -08:00
if (feeLines) {
body.fee_lines = feeLines;
setMetadata(feeLines);
toSnakeCase(feeLines);
}
const lineItems = (this.getNodeParameter('lineItemsUi', i) as IDataObject)
.lineItemsValues as ILineItem[];
2020-02-24 16:19:04 -08:00
if (lineItems) {
body.line_items = lineItems;
setMetadata(lineItems);
toSnakeCase(lineItems);
}
const metadata = (this.getNodeParameter('metadataUi', i) as IDataObject)
.metadataValues as IDataObject[];
2020-02-24 16:19:04 -08:00
if (metadata) {
body.meta_data = metadata;
}
const shippingLines = (this.getNodeParameter('shippingLinesUi', i) as IDataObject)
.shippingLinesValues as IShoppingLine[];
2020-02-24 16:19:04 -08:00
if (shippingLines) {
body.shipping_lines = shippingLines;
setMetadata(shippingLines);
toSnakeCase(shippingLines);
}
2020-02-24 16:19:04 -08:00
responseData = await woocommerceApiRequest.call(this, 'PUT', `/orders/${orderId}`, body);
}
//https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-an-order
if (operation === 'get') {
const orderId = this.getNodeParameter('orderId', i) as string;
responseData = await woocommerceApiRequest.call(
this,
'GET',
`/orders/${orderId}`,
{},
qs,
);
2020-02-24 16:19:04 -08:00
}
//https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const options = this.getNodeParameter('options', i) as IDataObject;
if (options.after) {
qs.after = options.after as string;
}
if (options.before) {
qs.before = options.before as string;
}
if (options.category) {
qs.category = options.category as string;
}
if (options.customer) {
qs.customer = parseInt(options.customer as string, 10);
}
if (options.decimalPoints) {
qs.dp = options.decimalPoints as number;
}
if (options.product) {
qs.product = parseInt(options.product as string, 10);
}
if (options.order) {
qs.order = options.order as string;
}
if (options.orderBy) {
qs.orderby = options.orderBy as string;
}
if (options.search) {
qs.search = options.search as string;
}
if (options.status) {
qs.status = options.status as string;
}
if (returnAll === true) {
responseData = await woocommerceApiRequestAllItems.call(this, 'GET', '/orders', {}, qs);
} else {
qs.per_page = this.getNodeParameter('limit', i) as number;
responseData = await woocommerceApiRequest.call(this, 'GET', '/orders', {}, qs);
}
}
//https://woocommerce.github.io/woocommerce-rest-api-docs/#delete-an-order
if (operation === 'delete') {
const orderId = this.getNodeParameter('orderId', i) as string;
responseData = await woocommerceApiRequest.call(
this,
'DELETE',
`/orders/${orderId}`,
{},
{ force: true },
);
2020-02-24 16:19:04 -08:00
}
}
2020-02-16 10:43:51 -08:00
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData as IDataObject[]);
} else {
returnData.push(responseData as IDataObject);
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}