n8n/packages/nodes-base/nodes/QuickBooks/GenericFunctions.ts

427 lines
10 KiB
TypeScript
Raw Normal View History

:sparkles: Add QuickBooks node (#1365) * Add OAuth2 credentials * Adjust credentials params * Add node to listing * Add initial node scaffolding * Remove unused credentials params * Add customer search with select statement * Add pagination to customer search * Add customer creation functionality * Add customer update functionality * Small formatting fix * Adjust property name casing for consistency * Adjust customer operations for consistency * Handle large QuickBooks listings * Add initial estimate resource description * Add estimate resource retrieval operations * Refactor customer billing address * Simplify customer billing address * Fix casing for customer additional fields * Adjust types to accommodate loadOptions functions * Add loadOptions for customers to estimate * Sort customer update fields alphabetically * Refactor estimate line into standalone file * Add stub for PDF retrieval operation * Add invoice resource description and execute branches * Implement estimate PDF download functionality * Place descriptions in their own dir * Add get and getAll for invoices * Add send functionality to invoices * Refactor handling of binary data * Add invoice voiding functionality * Add invoice deletion functionality * Refactor resources into subdirs and add interfaces * Add get and getAll for bill * Add payment description * Add get and getAll for payment * Make variables in endpoints consistent * Refactor interfaces for consistency * Add interface for item resource * Fill in fields for all resources * Minor fixes in defaults and descriptions * Refactor loader * Add all resources to execute function * Fix line property duplication * Add get and getAll for vendor * Optimize description imports * Add creation for customer and bill * Add update operation for bill * Refactor create and update for customer * Implement employee create and update * Implement create and update for estimate * Make address params more consistent * Add create and update to payment * Add item operations * Add create and delete operations for invoice * Refactor binary data handler * Refactor generic functions * Add create and update operations for vendor * Fix build * Fix total amount in bill:update * Fix balance in bill:update * Remove currency from bill:update * Implement reference retrieval in bill:update * Fix failing params in customer:update * Fix param in employee:update * Implement reference retrieval in estimate:update * Fix failing params in estimate:update * Fix failing params in invoice:update * Fix failing param in vendor:update * Implement reference retrieval in payment:update * Remove unused interfaces * Rename line property function * Remove hared directory * Refactor reference and sync token retrieval * Fix line structure in bill:create * Fix line structure in estimate:create * Flatten responses * Refactor line processing * Remove unused interfaces * Add endpoint documentation * Fix payment:void content type * Fix default for bill line item * Hide auth URI query parameters * Hide auth header parameter * Add switch for credentials environment * Adjust OAuth2 callback to accommodate realmId * Retrieve realmId from OAuth2 flow * :zap: Improvements * Reposition dividers * Add IDs to display names of reference fields * Add estimate:delete and bill:delete * Load items in lines for bill, estimate and invoice * Add filename for binary property in PDF download * :zap: Improvements * Adjust field description * Implement estimate:send * Adjust field description * Adjust custom field descriptions * Add missing period to description * :zap: Minor improvements on QuickBooks-Node * Add descriptions for bill * Add descriptions for customer * Add descriptions for employee * Add descriptions for estimate * Add descriptions for invoice * Add descriptions for payment * Add descriptions for vendor Co-authored-by: ricardo <ricardoespinoza105@gmail.com> Co-authored-by: Jan Oberhauser <jan.oberhauser@gmail.com>
2021-02-13 08:27:08 -08:00
import {
IExecuteFunctions,
IHookFunctions,
} from 'n8n-core';
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
:sparkles: Improve node error handling (#1309) * Add path mapping and response error interfaces * Add error handling and throwing functionality * Refactor error handling into a single function * Re-implement error handling in Hacker News node * Fix linting details * Re-implement error handling in Spotify node * Re-implement error handling in G Suite Admin node * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: Fix error handling for non-standard nodes Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
2021-04-16 09:33:36 -07:00
NodeApiError,
:sparkles: Add QuickBooks node (#1365) * Add OAuth2 credentials * Adjust credentials params * Add node to listing * Add initial node scaffolding * Remove unused credentials params * Add customer search with select statement * Add pagination to customer search * Add customer creation functionality * Add customer update functionality * Small formatting fix * Adjust property name casing for consistency * Adjust customer operations for consistency * Handle large QuickBooks listings * Add initial estimate resource description * Add estimate resource retrieval operations * Refactor customer billing address * Simplify customer billing address * Fix casing for customer additional fields * Adjust types to accommodate loadOptions functions * Add loadOptions for customers to estimate * Sort customer update fields alphabetically * Refactor estimate line into standalone file * Add stub for PDF retrieval operation * Add invoice resource description and execute branches * Implement estimate PDF download functionality * Place descriptions in their own dir * Add get and getAll for invoices * Add send functionality to invoices * Refactor handling of binary data * Add invoice voiding functionality * Add invoice deletion functionality * Refactor resources into subdirs and add interfaces * Add get and getAll for bill * Add payment description * Add get and getAll for payment * Make variables in endpoints consistent * Refactor interfaces for consistency * Add interface for item resource * Fill in fields for all resources * Minor fixes in defaults and descriptions * Refactor loader * Add all resources to execute function * Fix line property duplication * Add get and getAll for vendor * Optimize description imports * Add creation for customer and bill * Add update operation for bill * Refactor create and update for customer * Implement employee create and update * Implement create and update for estimate * Make address params more consistent * Add create and update to payment * Add item operations * Add create and delete operations for invoice * Refactor binary data handler * Refactor generic functions * Add create and update operations for vendor * Fix build * Fix total amount in bill:update * Fix balance in bill:update * Remove currency from bill:update * Implement reference retrieval in bill:update * Fix failing params in customer:update * Fix param in employee:update * Implement reference retrieval in estimate:update * Fix failing params in estimate:update * Fix failing params in invoice:update * Fix failing param in vendor:update * Implement reference retrieval in payment:update * Remove unused interfaces * Rename line property function * Remove hared directory * Refactor reference and sync token retrieval * Fix line structure in bill:create * Fix line structure in estimate:create * Flatten responses * Refactor line processing * Remove unused interfaces * Add endpoint documentation * Fix payment:void content type * Fix default for bill line item * Hide auth URI query parameters * Hide auth header parameter * Add switch for credentials environment * Adjust OAuth2 callback to accommodate realmId * Retrieve realmId from OAuth2 flow * :zap: Improvements * Reposition dividers * Add IDs to display names of reference fields * Add estimate:delete and bill:delete * Load items in lines for bill, estimate and invoice * Add filename for binary property in PDF download * :zap: Improvements * Adjust field description * Implement estimate:send * Adjust field description * Adjust custom field descriptions * Add missing period to description * :zap: Minor improvements on QuickBooks-Node * Add descriptions for bill * Add descriptions for customer * Add descriptions for employee * Add descriptions for estimate * Add descriptions for invoice * Add descriptions for payment * Add descriptions for vendor Co-authored-by: ricardo <ricardoespinoza105@gmail.com> Co-authored-by: Jan Oberhauser <jan.oberhauser@gmail.com>
2021-02-13 08:27:08 -08:00
} from 'n8n-workflow';
import {
CustomField,
GeneralAddress,
Ref,
} from './descriptions/Shared.interface';
import {
capitalCase,
} from 'change-case';
import {
pickBy,
} from 'lodash';
import {
OptionsWithUri,
} from 'request';
/**
* Make an authenticated API request to QuickBooks.
*/
export async function quickBooksApiRequest(
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
method: string,
endpoint: string,
qs: IDataObject,
body: IDataObject,
option: IDataObject = {},
): Promise<any> { // tslint:disable-line:no-any
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
let isDownload = false;
if (['estimate', 'invoice', 'payment'].includes(resource) && operation === 'get') {
isDownload = this.getNodeParameter('download', 0) as boolean;
}
const productionUrl = 'https://quickbooks.api.intuit.com';
const sandboxUrl = 'https://sandbox-quickbooks.api.intuit.com';
const credentials = this.getCredentials('quickBooksOAuth2Api') as IDataObject;
const options: OptionsWithUri = {
headers: {
'user-agent': 'n8n',
},
method,
uri: `${credentials.environment === 'sandbox' ? sandboxUrl : productionUrl}${endpoint}`,
qs,
body,
json: !isDownload,
};
if (!Object.keys(body).length) {
delete options.body;
}
if (!Object.keys(qs).length) {
delete options.qs;
}
if (Object.keys(option)) {
Object.assign(options, option);
}
if (isDownload) {
options.headers!['Accept'] = 'application/pdf';
}
if (resource === 'invoice' && operation === 'send') {
options.headers!['Content-Type'] = 'application/octet-stream';
}
if (
(resource === 'invoice' && (operation === 'void' || operation === 'delete')) ||
(resource === 'payment' && (operation === 'void' || operation === 'delete'))
) {
options.headers!['Content-Type'] = 'application/json';
}
try {
return await this.helpers.requestOAuth2!.call(this, 'quickBooksOAuth2Api', options);
} catch (error) {
:sparkles: Improve node error handling (#1309) * Add path mapping and response error interfaces * Add error handling and throwing functionality * Refactor error handling into a single function * Re-implement error handling in Hacker News node * Fix linting details * Re-implement error handling in Spotify node * Re-implement error handling in G Suite Admin node * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: Fix error handling for non-standard nodes Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
2021-04-16 09:33:36 -07:00
throw new NodeApiError(this.getNode(), error);
:sparkles: Add QuickBooks node (#1365) * Add OAuth2 credentials * Adjust credentials params * Add node to listing * Add initial node scaffolding * Remove unused credentials params * Add customer search with select statement * Add pagination to customer search * Add customer creation functionality * Add customer update functionality * Small formatting fix * Adjust property name casing for consistency * Adjust customer operations for consistency * Handle large QuickBooks listings * Add initial estimate resource description * Add estimate resource retrieval operations * Refactor customer billing address * Simplify customer billing address * Fix casing for customer additional fields * Adjust types to accommodate loadOptions functions * Add loadOptions for customers to estimate * Sort customer update fields alphabetically * Refactor estimate line into standalone file * Add stub for PDF retrieval operation * Add invoice resource description and execute branches * Implement estimate PDF download functionality * Place descriptions in their own dir * Add get and getAll for invoices * Add send functionality to invoices * Refactor handling of binary data * Add invoice voiding functionality * Add invoice deletion functionality * Refactor resources into subdirs and add interfaces * Add get and getAll for bill * Add payment description * Add get and getAll for payment * Make variables in endpoints consistent * Refactor interfaces for consistency * Add interface for item resource * Fill in fields for all resources * Minor fixes in defaults and descriptions * Refactor loader * Add all resources to execute function * Fix line property duplication * Add get and getAll for vendor * Optimize description imports * Add creation for customer and bill * Add update operation for bill * Refactor create and update for customer * Implement employee create and update * Implement create and update for estimate * Make address params more consistent * Add create and update to payment * Add item operations * Add create and delete operations for invoice * Refactor binary data handler * Refactor generic functions * Add create and update operations for vendor * Fix build * Fix total amount in bill:update * Fix balance in bill:update * Remove currency from bill:update * Implement reference retrieval in bill:update * Fix failing params in customer:update * Fix param in employee:update * Implement reference retrieval in estimate:update * Fix failing params in estimate:update * Fix failing params in invoice:update * Fix failing param in vendor:update * Implement reference retrieval in payment:update * Remove unused interfaces * Rename line property function * Remove hared directory * Refactor reference and sync token retrieval * Fix line structure in bill:create * Fix line structure in estimate:create * Flatten responses * Refactor line processing * Remove unused interfaces * Add endpoint documentation * Fix payment:void content type * Fix default for bill line item * Hide auth URI query parameters * Hide auth header parameter * Add switch for credentials environment * Adjust OAuth2 callback to accommodate realmId * Retrieve realmId from OAuth2 flow * :zap: Improvements * Reposition dividers * Add IDs to display names of reference fields * Add estimate:delete and bill:delete * Load items in lines for bill, estimate and invoice * Add filename for binary property in PDF download * :zap: Improvements * Adjust field description * Implement estimate:send * Adjust field description * Adjust custom field descriptions * Add missing period to description * :zap: Minor improvements on QuickBooks-Node * Add descriptions for bill * Add descriptions for customer * Add descriptions for employee * Add descriptions for estimate * Add descriptions for invoice * Add descriptions for payment * Add descriptions for vendor Co-authored-by: ricardo <ricardoespinoza105@gmail.com> Co-authored-by: Jan Oberhauser <jan.oberhauser@gmail.com>
2021-02-13 08:27:08 -08:00
}
}
/**
* Make an authenticated API request to QuickBooks and return all results.
*/
export async function quickBooksApiRequestAllItems(
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
method: string,
endpoint: string,
qs: IDataObject,
body: IDataObject,
resource: string,
): Promise<any> { // tslint:disable-line:no-any
let responseData;
let startPosition = 1;
const maxResults = 1000;
const returnData: IDataObject[] = [];
const maxCount = await getCount.call(this, method, endpoint, qs);
const originalQuery = qs.query;
do {
qs.query = `${originalQuery} MAXRESULTS ${maxResults} STARTPOSITION ${startPosition}`;
responseData = await quickBooksApiRequest.call(this, method, endpoint, qs, body);
returnData.push(...responseData.QueryResponse[capitalCase(resource)]);
startPosition += maxResults;
} while (maxCount > returnData.length);
return returnData;
}
async function getCount(
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
method: string,
endpoint: string,
qs: IDataObject,
): Promise<any> { // tslint:disable-line:no-any
const responseData = await quickBooksApiRequest.call(this, method, endpoint, qs, {});
return responseData.QueryResponse.totalCount;
}
/**
* Handles a QuickBooks listing by returning all items or up to a limit.
*/
export async function handleListing(
this: IExecuteFunctions,
i: number,
endpoint: string,
resource: string,
): Promise<any> { // tslint:disable-line:no-any
let responseData;
const qs = {
query: `SELECT * FROM ${resource}`,
} as IDataObject;
const returnAll = this.getNodeParameter('returnAll', i);
const filters = this.getNodeParameter('filters', i) as IDataObject;
if (filters.query) {
qs.query += ` ${filters.query}`;
}
if (returnAll) {
return await quickBooksApiRequestAllItems.call(this, 'GET', endpoint, qs, {}, resource);
} else {
const limit = this.getNodeParameter('limit', i) as number;
qs.query += ` MAXRESULTS ${limit}`;
responseData = await quickBooksApiRequest.call(this, 'GET', endpoint, qs, {});
responseData = responseData.QueryResponse[capitalCase(resource)];
return responseData;
}
}
/**
* Get the SyncToken required for delete and void operations in QuickBooks.
*/
export async function getSyncToken(
this: IExecuteFunctions,
i: number,
companyId: string,
resource: string,
) {
const resourceId = this.getNodeParameter(`${resource}Id`, i);
const getEndpoint = `/v3/company/${companyId}/${resource}/${resourceId}`;
const propertyName = capitalCase(resource);
const { [propertyName]: { SyncToken } } = await quickBooksApiRequest.call(this, 'GET', getEndpoint, {}, {});
return SyncToken;
}
/**
* Get the reference and SyncToken required for update operations in QuickBooks.
*/
export async function getRefAndSyncToken(
this: IExecuteFunctions,
i: number,
companyId: string,
resource: string,
ref: string,
) {
const resourceId = this.getNodeParameter(`${resource}Id`, i);
const endpoint = `/v3/company/${companyId}/${resource}/${resourceId}`;
const responseData = await quickBooksApiRequest.call(this, 'GET', endpoint, {}, {});
return {
ref: responseData[capitalCase(resource)][ref],
syncToken: responseData[capitalCase(resource)].SyncToken,
};
}
/**
* Populate node items with binary data.
*/
export async function handleBinaryData(
this: IExecuteFunctions,
items: INodeExecutionData[],
i: number,
companyId: string,
resource: string,
resourceId: string,
) {
const binaryProperty = this.getNodeParameter('binaryProperty', i) as string;
const fileName = this.getNodeParameter('fileName', i) as string;
const endpoint = `/v3/company/${companyId}/${resource}/${resourceId}/pdf`;
const data = await quickBooksApiRequest.call(this, 'GET', endpoint, {}, {}, { encoding: null });
items[i].binary = items[i].binary ?? {};
items[i].binary![binaryProperty] = await this.helpers.prepareBinaryData(data);
items[i].binary![binaryProperty].fileName = fileName;
items[i].binary![binaryProperty].fileExtension = 'pdf';
return items;
}
export async function loadResource(
this: ILoadOptionsFunctions,
resource: string,
) {
const returnData: INodePropertyOptions[] = [];
const qs = {
query: `SELECT * FROM ${resource}`,
} as IDataObject;
const { oauthTokenData: { callbackQueryString: { realmId } } } = this.getCredentials('quickBooksOAuth2Api') as { oauthTokenData: { callbackQueryString: { realmId: string } } };
const endpoint = `/v3/company/${realmId}/query`;
const resourceItems = await quickBooksApiRequestAllItems.call(this, 'GET', endpoint, qs, {}, resource);
if (resource === 'preferences') {
const { SalesFormsPrefs: { CustomField } } = resourceItems[0];
const customFields = CustomField[1].CustomField;
for (const customField of customFields) {
const length = customField.Name.length;
returnData.push({
name: customField.StringValue,
value: customField.Name.charAt(length - 1),
});
}
return returnData;
}
resourceItems.forEach((resourceItem: { DisplayName: string, Name: string, Id: string }) => {
returnData.push({
name: resourceItem.DisplayName || resourceItem.Name,
value: resourceItem.Id,
});
});
return returnData;
}
/**
* Populate the `Line` property in a request body.
*/
export function processLines(
this: IExecuteFunctions,
body: IDataObject,
lines: IDataObject[],
resource: string,
) {
lines.forEach((line) => {
if (resource === 'bill') {
if (line.DetailType === 'AccountBasedExpenseLineDetail') {
line.AccountBasedExpenseLineDetail = {
AccountRef: {
value: line.accountId,
},
};
delete line.accountId;
} else if (line.DetailType === 'ItemBasedExpenseLineDetail') {
line.ItemBasedExpenseLineDetail = {
ItemRef: {
value: line.itemId,
},
};
delete line.itemId;
}
} else if (resource === 'estimate') {
if (line.DetailType === 'SalesItemLineDetail') {
line.SalesItemLineDetail = {
ItemRef: {
value: line.itemId,
},
};
delete line.itemId;
}
} else if (resource === 'invoice') {
if (line.DetailType === 'SalesItemLineDetail') {
line.SalesItemLineDetail = {
ItemRef: {
value: line.itemId,
},
};
delete line.itemId;
}
}
});
return lines;
}
/**
* Populate update fields or additional fields into a request body.
*/
export function populateFields(
this: IExecuteFunctions,
body: IDataObject,
fields: IDataObject,
resource: string,
) {
Object.entries(fields).forEach(([key, value]) => {
if (resource === 'bill') {
if (key.endsWith('Ref')) {
const { details } = value as { details: Ref };
body[key] = {
name: details.name,
value: details.value,
};
} else {
body[key] = value;
}
} else if (['customer', 'employee', 'vendor'].includes(resource)) {
if (key === 'BillAddr') {
const { details } = value as { details: GeneralAddress };
body.BillAddr = pickBy(details, detail => detail !== '');
} else if (key === 'PrimaryEmailAddr') {
body.PrimaryEmailAddr = {
Address: value,
};
} else if (key === 'PrimaryPhone') {
body.PrimaryPhone = {
FreeFormNumber: value,
};
} else {
body[key] = value;
}
} else if (resource === 'estimate' || resource === 'invoice') {
if (key === 'BillAddr' || key === 'ShipAddr') {
const { details } = value as { details: GeneralAddress };
body[key] = pickBy(details, detail => detail !== '');
} else if (key === 'BillEmail') {
body.BillEmail = {
Address: value,
};
} else if (key === 'CustomFields') {
const { Field } = value as { Field: CustomField[] };
body.CustomField = Field;
const length = (body.CustomField as CustomField[]).length;
for (let i = 0; i < length; i++) {
//@ts-ignore
body.CustomField[i]['Type'] = 'StringType';
}
} else if (key === 'CustomerMemo') {
body.CustomerMemo = {
value,
};
} else if (key.endsWith('Ref')) {
const { details } = value as { details: Ref };
body[key] = {
name: details.name,
value: details.value,
};
} else if (key === 'TotalTax') {
body.TxnTaxDetail = {
TotalTax: value,
};
} else {
body[key] = value;
}
} else if (resource === 'payment') {
body[key] = value;
}
});
return body;
}