@zohocrm/typescript-sdk-6.0
Version:
TypeScript SDK for Zoho CRM
785 lines • 62.1 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MasterModel = exports.Utility = void 0;
const path = __importStar(require("path"));
const converter_js_1 = require("./converter.js");
const initializer_js_1 = require("../../routes/initializer.js");
const constants_js_1 = require("./constants.js");
const minified_module_js_1 = require("../../core/com/zoho/crm/api/modules/minified_module.js");
const winston_1 = __importDefault(require("winston"));
const fs = __importStar(require("fs"));
const sdk_exception_js_1 = require("../../core/com/zoho/crm/api/exception/sdk_exception.js");
const zohocrmsdk_js_1 = require("../../zohocrmsdk.js");
const choice_js_1 = require("./choice.js");
/**
* This class handles module field details.
*/
class Utility {
static async assertNotNull(value, errorCode, errorMessage) {
if (value == null) {
throw new sdk_exception_js_1.SDKException(errorCode, errorMessage);
}
}
static async fileExistsFlow(moduleAPIName, recordFieldDetailsPath, lastModifiedTime) {
let recordFieldDetailsJson = initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
let initializer = await initializer_js_1.Initializer.getInitializer().catch((err) => { throw err; });
if (initializer == null || initializer == undefined) {
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.SDK_UNINITIALIZATION_ERROR, constants_js_1.Constants.SDK_UNINITIALIZATION_MESSAGE);
}
if (initializer.getSDKConfig() != null && initializer.getSDKConfig().getAutoRefreshFields() == true && !this.newFile && !this.getModifiedModules && (!recordFieldDetailsJson.hasOwnProperty(constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME) || this.forceRefresh || new Date().getTime() - recordFieldDetailsJson[constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME] > 3600000)) {
this.getModifiedModules = true;
lastModifiedTime = !this.forceRefresh && recordFieldDetailsJson.hasOwnProperty(constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME) ? recordFieldDetailsJson[constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME] : null;
await Utility.modifyFields(recordFieldDetailsPath, lastModifiedTime).catch((err) => { throw err; });
this.getModifiedModules = false;
}
else if (initializer.getSDKConfig() != null && initializer.getSDKConfig().getAutoRefreshFields() == false && this.forceRefresh && !this.getModifiedModules) {
this.getModifiedModules = true;
await Utility.modifyFields(recordFieldDetailsPath, lastModifiedTime).catch((err) => { throw err; });
this.getModifiedModules = false;
}
recordFieldDetailsJson = initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
if (moduleAPIName == null || (recordFieldDetailsJson.hasOwnProperty(moduleAPIName.toLowerCase()) && recordFieldDetailsJson[moduleAPIName.toLowerCase()] != null)) {
return;
}
else {
await Utility.fillDataType().catch((err) => { throw err; });
recordFieldDetailsJson[moduleAPIName.toLowerCase()] = {};
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
let fieldsDetails = await Utility.getFieldsDetails(moduleAPIName).catch(err => { throw err; });
recordFieldDetailsJson = await initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
recordFieldDetailsJson[moduleAPIName.toLowerCase()] = fieldsDetails;
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
}
}
static async verifyModuleAPIName(moduleName) {
if (moduleName != null && constants_js_1.Constants.DEFAULT_MODULENAME_VS_APINAME.has(moduleName.toLowerCase()) && constants_js_1.Constants.DEFAULT_MODULENAME_VS_APINAME.get(moduleName.toLowerCase()) != null) {
return constants_js_1.Constants.DEFAULT_MODULENAME_VS_APINAME.get(moduleName.toLowerCase());
}
var recordFieldDetailsPath = await this.getFileName().catch((err) => { throw err; });
if (fs.existsSync(recordFieldDetailsPath)) {
let fieldsJSON = initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
if (fieldsJSON.hasOwnProperty(constants_js_1.Constants.SDK_MODULE_METADATA) && fieldsJSON[constants_js_1.Constants.SDK_MODULE_METADATA].hasOwnProperty(moduleName.toLowerCase())) {
let moduleMeta = fieldsJSON[constants_js_1.Constants.SDK_MODULE_METADATA];
return moduleMeta[moduleName.toLowerCase()][constants_js_1.Constants.API_NAME];
}
}
return moduleName;
}
static async setHandlerAPIPath(moduleAPIName, handlerInstance) {
if (handlerInstance == null) {
return;
}
let apiPath = handlerInstance.getAPIPath();
if (moduleAPIName != null && apiPath.toLowerCase().includes(moduleAPIName.toLowerCase())) {
let apiPathSplit = apiPath.split("/");
for (var i = 0; i < apiPathSplit.length; i++) {
if (apiPathSplit[i] != null && apiPathSplit[i].toLowerCase() == moduleAPIName.toLowerCase()) {
apiPathSplit[i] = moduleAPIName;
}
else if (apiPathSplit[i] != null && constants_js_1.Constants.DEFAULT_MODULENAME_VS_APINAME.has(apiPathSplit[i].toLowerCase()) && constants_js_1.Constants.DEFAULT_MODULENAME_VS_APINAME.get(apiPathSplit[i].toLowerCase()) != null) {
apiPathSplit[i] = constants_js_1.Constants.DEFAULT_MODULENAME_VS_APINAME.get(apiPathSplit[i].toLowerCase());
}
}
apiPath = apiPathSplit.join("/");
handlerInstance.setAPIPath(apiPath);
}
}
/**
* This method to fetch field details of the current module for the current user and store the result in a JSON file.
* @param {string} moduleAPIName - A String containing the CRM module API name.
* @param {string} handlerInstance - A String containing CommonAPIHandler Instance.
*/
static async getFields(moduleAPIName, handlerInstance = null) {
if (this.moduleAPIName != null && this.moduleAPIName.includes(",")) {
let moduleAPINames = this.moduleAPIName.split(",");
for (var i = 0; i < moduleAPINames.length; i++) {
this.moduleAPIName = moduleAPINames[i];
await this.getFieldsInfo(this.moduleAPIName, handlerInstance).catch((err) => { throw err; });
}
}
else {
this.moduleAPIName = moduleAPIName;
await this.getFieldsInfo(this.moduleAPIName, handlerInstance).catch((err) => { throw err; });
}
}
/**
* This method to fetch field details of the current module for the current user and store the result in a JSON file.
* @param {string} moduleAPIName - A String containing the CRM module API name.
* @param {string} handlerInstance - A String containing CommonAPIHandler Instance.
*/
static async getFieldsInfo(moduleAPIName, handlerInstance = null) {
let lastModifiedTime = null;
var recordFieldDetailsPath = null;
try {
let initializer = await initializer_js_1.Initializer.getInitializer().catch((err) => { throw err; });
if (initializer == null || initializer == undefined) {
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.SDK_UNINITIALIZATION_ERROR, constants_js_1.Constants.SDK_UNINITIALIZATION_MESSAGE);
}
var resourcesPath = path.join(initializer.getResourcePath(), constants_js_1.Constants.FIELD_DETAILS_DIRECTORY);
if (!fs.existsSync(resourcesPath)) {
fs.mkdirSync(resourcesPath, { recursive: true });
}
if (moduleAPIName != null) {
moduleAPIName = await Utility.verifyModuleAPIName(moduleAPIName).catch((err) => { throw err; });
await Utility.setHandlerAPIPath(moduleAPIName, handlerInstance).catch((err) => { throw err; });
if (handlerInstance != null && handlerInstance.getModuleAPIName() == null && (moduleAPIName != null && !constants_js_1.Constants.SKIP_MODULES.includes(moduleAPIName.toLowerCase()))) {
return;
}
}
recordFieldDetailsPath = resourcesPath + "/" + await this.getFileName().catch((err) => { throw err; });
if (fs.existsSync(recordFieldDetailsPath)) {
await Utility.fileExistsFlow(moduleAPIName, recordFieldDetailsPath, lastModifiedTime).catch((err) => { throw err; });
}
else if (initializer.getSDKConfig() !== null && initializer.getSDKConfig().getAutoRefreshFields() == true) {
this.newFile = true;
await Utility.fillDataType().catch((err) => { throw err; });
this.apiSupportedModule = Object.keys(this.apiSupportedModule).length > 0 ? this.apiSupportedModule : await Utility.getModules(null).catch((err) => { throw err; });
let recordFieldDetailsJson = fs.existsSync(recordFieldDetailsPath) ? initializer_js_1.Initializer.getJSON(recordFieldDetailsPath) : {};
recordFieldDetailsJson[constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME] = new Date().getTime();
if (Object.keys(this.apiSupportedModule).length > 0) {
for (let module in this.apiSupportedModule) {
if (!recordFieldDetailsJson.hasOwnProperty(module)) {
let moduleData = this.apiSupportedModule[module];
recordFieldDetailsJson[module] = {};
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
let fieldsDetails = await Utility.getFieldsDetails(moduleData[constants_js_1.Constants.API_NAME]).catch(err => { throw err; });
recordFieldDetailsJson = await initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
recordFieldDetailsJson[module] = fieldsDetails;
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
}
}
}
this.newFile = false;
}
else if (this.forceRefresh && !this.getModifiedModules) {
//New file - and force refresh by Users
this.getModifiedModules = true;
let recordFieldDetailsJson = {};
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
await Utility.modifyFields(recordFieldDetailsPath, lastModifiedTime).catch((err) => { throw err; });
this.getModifiedModules = false;
}
else {
await Utility.fillDataType().catch((err) => { throw err; });
let recordFieldDetailsJson = {};
if (moduleAPIName != null) {
recordFieldDetailsJson[moduleAPIName.toLowerCase()] = {};
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
let fieldsDetails = await Utility.getFieldsDetails(moduleAPIName).catch(err => { throw err; });
recordFieldDetailsJson = await initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
recordFieldDetailsJson[moduleAPIName.toLowerCase()] = fieldsDetails;
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
}
}
}
catch (error) {
if (recordFieldDetailsPath != null && fs.existsSync(recordFieldDetailsPath)) {
try {
let recordFieldDetailsJson = await initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
if (moduleAPIName != null) {
if (recordFieldDetailsJson.hasOwnProperty(moduleAPIName.toLowerCase())) {
delete recordFieldDetailsJson[moduleAPIName.toLowerCase()];
}
}
if (this.newFile) {
if (recordFieldDetailsJson.hasOwnProperty(constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME)) {
delete recordFieldDetailsJson[constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME];
}
this.newFile = false;
}
if (this.getModifiedModules || this.forceRefresh) {
this.getModifiedModules = false;
this.forceRefresh = false;
if (lastModifiedTime != null) {
recordFieldDetailsJson[constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME] = lastModifiedTime;
}
}
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
}
catch (error) {
error = new sdk_exception_js_1.SDKException(null, null, null, error);
winston_1.default.error(constants_js_1.Constants.EXCEPTION, error);
throw error;
}
}
if (!(error instanceof sdk_exception_js_1.SDKException)) {
error = new sdk_exception_js_1.SDKException(null, null, null, error);
}
winston_1.default.error(constants_js_1.Constants.EXCEPTION, error);
throw error;
}
}
static async modifyFields(recordFieldDetailsPath, modifiedTime) {
let modifiedModules = await this.getModules(modifiedTime).catch((err) => { throw err; });
let recordFieldDetailsJson = await initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
recordFieldDetailsJson[constants_js_1.Constants.FIELDS_LAST_MODIFIED_TIME] = new Date().getTime();
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
if (Object.keys(modifiedModules).length > 0) {
for (let module in modifiedModules) {
if (recordFieldDetailsJson.hasOwnProperty(module)) {
delete recordFieldDetailsJson[module];
}
}
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJson));
for (let module in modifiedModules) {
let moduleData = modifiedModules[module];
await Utility.getFieldsInfo(moduleData[constants_js_1.Constants.API_NAME], null).catch((err) => { throw err; });
}
}
}
static async deleteFields(recordFieldDetailsJson, module) {
let subformModules = [];
let fieldsJSON = recordFieldDetailsJson[module.toLowerCase()];
for (let keyName of Object.keys(fieldsJSON)) {
if (fieldsJSON[keyName].hasOwnProperty(constants_js_1.Constants.SUBFORM) && fieldsJSON[keyName][constants_js_1.Constants.SUBFORM] == true && recordFieldDetailsJson.hasOwnProperty(fieldsJSON[keyName][constants_js_1.Constants.MODULE].toLowerCase())) {
let subformModuleName = fieldsJSON[keyName][constants_js_1.Constants.MODULE];
if (!subformModules.includes(subformModuleName)) {
subformModules.push(subformModuleName);
}
}
}
delete recordFieldDetailsJson[module.toLowerCase()];
if (subformModules.length > 0) {
for (let subformModule of subformModules) {
await this.deleteFields(recordFieldDetailsJson, subformModule).catch((err) => { throw err; });
}
}
}
static async getFileName() {
let initializer = await initializer_js_1.Initializer.getInitializer().catch((err) => { throw err; });
if (initializer == null || initializer == undefined) {
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.SDK_UNINITIALIZATION_ERROR, constants_js_1.Constants.SDK_UNINITIALIZATION_MESSAGE);
}
let token = initializer.getToken();
let tokenKey = "";
if (token instanceof zohocrmsdk_js_1.OAuthToken) {
let oauthToken = token;
let user = oauthToken.getUserSignature();
if (user != null) {
tokenKey = user.getName();
}
else {
let refreshToken = oauthToken.getRefreshToken();
if (refreshToken != null && refreshToken.length > 0) {
tokenKey = refreshToken.substring(refreshToken.length - 32);
}
else {
let accessToken = oauthToken.getAccessToken();
if (accessToken != null && accessToken.length > 0) {
tokenKey = accessToken.substring(accessToken.length - 32);
}
}
}
}
let fileName = initializer.getEnvironment().getUrl();
if (tokenKey != null && tokenKey.length > 0) {
fileName = fileName + tokenKey;
}
var input = converter_js_1.Converter.toUTF8Array(fileName);
var str = Buffer.from(input).toString('base64');
return str + ".json";
}
static async getRelatedLists(relatedModuleName, moduleAPIName, commonAPIHandler) {
try {
let isnewData = false;
let key = (moduleAPIName + constants_js_1.Constants.UNDERSCORE + constants_js_1.Constants.RELATED_LISTS).toLowerCase();
let initializer = await initializer_js_1.Initializer.getInitializer().catch((err) => { throw err; });
if (initializer == null || initializer == undefined) {
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.SDK_UNINITIALIZATION_ERROR, constants_js_1.Constants.SDK_UNINITIALIZATION_MESSAGE);
}
let resourcesPath = path.join(initializer.getResourcePath(), constants_js_1.Constants.FIELD_DETAILS_DIRECTORY);
if (!fs.existsSync(resourcesPath)) {
fs.mkdirSync(resourcesPath, { recursive: true });
}
var recordFieldDetailsPath = initializer.getResourcePath() + "resources/" + await this.getFileName().catch((err) => { throw err; });
let recordFieldDetailsJSON = null;
if (!fs.existsSync(recordFieldDetailsPath) || (fs.existsSync(recordFieldDetailsPath) && (!initializer_js_1.Initializer.getJSON(recordFieldDetailsPath).hasOwnProperty(key) || initializer_js_1.Initializer.getJSON(recordFieldDetailsPath)[key] == null || initializer_js_1.Initializer.getJSON(recordFieldDetailsPath)[key].length <= 0))) {
isnewData = true;
moduleAPIName = await Utility.verifyModuleAPIName(moduleAPIName).catch((err) => { throw err; });
let relatedListValues = await this.getRelatedListDetails(moduleAPIName).catch((err) => { throw err; });
recordFieldDetailsJSON = fs.existsSync(recordFieldDetailsPath) ? await initializer_js_1.Initializer.getJSON(recordFieldDetailsPath) : {};
recordFieldDetailsJSON[key] = relatedListValues;
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJSON));
}
recordFieldDetailsJSON = await initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
let moduleRelatedList = recordFieldDetailsJSON.hasOwnProperty(key) ? recordFieldDetailsJSON[key] : {};
if (!(await this.checkRelatedListExists(relatedModuleName, moduleRelatedList, commonAPIHandler).catch((err) => { throw err; })) && !isnewData) {
delete recordFieldDetailsJSON[key];
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(recordFieldDetailsJSON));
await Utility.getRelatedLists(relatedModuleName, moduleAPIName, commonAPIHandler).catch((err) => { throw err; });
}
}
catch (error) {
if (!(error instanceof sdk_exception_js_1.SDKException)) {
error = new sdk_exception_js_1.SDKException(null, null, null, error);
}
winston_1.default.error(constants_js_1.Constants.EXCEPTION, error);
throw error;
}
}
static async checkRelatedListExists(relatedModuleName, modulerelatedListArray, commonAPIHandler) {
for (let index = 0; index < modulerelatedListArray.length; index++) {
const relatedListObject = modulerelatedListArray[index];
if (relatedListObject[constants_js_1.Constants.API_NAME] != null && relatedListObject[constants_js_1.Constants.API_NAME].toLowerCase() == relatedModuleName.toLowerCase()) {
if (relatedListObject[constants_js_1.Constants.HREF].toLowerCase() == constants_js_1.Constants.NULL_VALUE) {
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.UNSUPPORTED_IN_API, commonAPIHandler.getHttpMethod() + " " + commonAPIHandler.getAPIPath() + constants_js_1.Constants.UNSUPPORTED_IN_API_MESSAGE);
}
if (relatedListObject[constants_js_1.Constants.MODULE].toLowerCase() != constants_js_1.Constants.NULL_VALUE) {
commonAPIHandler.setModuleAPIName(relatedListObject[constants_js_1.Constants.MODULE]);
await Utility.getFieldsInfo(relatedListObject[constants_js_1.Constants.MODULE], commonAPIHandler).catch((err) => { throw err; });
}
return true;
}
}
return false;
}
static async getRelatedListDetails(moduleAPIName) {
let RelatedListsOperations = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/related_lists/related_lists_operations.js")))).RelatedListsOperations;
let ResponseWrapper = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/related_lists/response_wrapper.js")))).ResponseWrapper;
let APIException = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/related_lists/api_exception.js")))).APIException;
let GetRelatedListsParam = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/related_lists/related_lists_operations.js")))).GetRelatedListsParam;
let ParameterMap = (await Promise.resolve().then(() => __importStar(require("../../routes/parameter_map.js")))).ParameterMap;
let relatedListArray = [];
let paramInstance = new ParameterMap();
await paramInstance.add(GetRelatedListsParam.MODULE, moduleAPIName);
let response = await new RelatedListsOperations().getRelatedLists(paramInstance).catch((err) => { throw err; });
if (response != null) {
if (response.getStatusCode() == constants_js_1.Constants.NO_CONTENT_STATUS_CODE) {
return relatedListArray;
}
let responseObject = response.getObject();
if (responseObject != null) {
if (responseObject instanceof ResponseWrapper) {
let relatedLists = responseObject.getRelatedLists();
relatedLists.forEach((relatedList) => {
let relatedListDetail = {};
relatedListDetail[constants_js_1.Constants.API_NAME] = relatedList.getAPIName();
relatedListDetail[constants_js_1.Constants.MODULE] = relatedList.getModule() != null ? relatedList.getModule().getAPIName() : constants_js_1.Constants.NULL_VALUE;
relatedListDetail[constants_js_1.Constants.NAME] = relatedList.getName();
relatedListDetail[constants_js_1.Constants.HREF] = relatedList.getHref() != null ? relatedList.getHref() : constants_js_1.Constants.NULL_VALUE;
relatedListArray.push(relatedListDetail);
});
}
else if (responseObject instanceof APIException) {
let errorResponse = {};
errorResponse[constants_js_1.Constants.CODE] = responseObject.getCode().getValue();
errorResponse[constants_js_1.Constants.STATUS] = responseObject.getStatus().getValue();
errorResponse[constants_js_1.Constants.MESSAGE] = responseObject.getMessage();
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.API_EXCEPTION, null, errorResponse, null);
}
else {
let errorResponse = {};
errorResponse[constants_js_1.Constants.CODE] = response.getStatusCode();
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.API_EXCEPTION, null, errorResponse, null);
}
}
}
return relatedListArray;
}
/**
* This method is to get module field data from Zoho CRM.
* @param {string} moduleAPIName - A String containing the CRM module API name.
* @returns {object} An Object representing the Zoho CRM module field details.
*/
static async getFieldsDetails(moduleAPIName) {
let FieldOperations = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/fields/fields_operations.js")))).FieldsOperations;
let FieldsResponseWrapper = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/fields/response_wrapper.js")))).ResponseWrapper;
let APIException = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/fields/api_exception.js")))).APIException;
let ParameterMap = (await Promise.resolve().then(() => __importStar(require("../../routes/parameter_map.js")))).ParameterMap;
let GetFieldsParam = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/fields/fields_operations.js")))).GetFieldsParam;
let paramInstance = new ParameterMap();
await paramInstance.add(GetFieldsParam.MODULE, moduleAPIName);
let response = await new FieldOperations().getFields(paramInstance).catch((err) => { throw err; });
let fieldsDetails = {};
if (response != null) {
if (response.getStatusCode() == constants_js_1.Constants.NO_CONTENT_STATUS_CODE) {
return fieldsDetails;
}
let responseHandler = response.getObject();
if (responseHandler != null) {
if (responseHandler instanceof FieldsResponseWrapper) {
let fields = await responseHandler.getFields();
for (let field in fields) {
let keyName = fields[field].getAPIName();
if (constants_js_1.Constants.KEYS_TO_SKIP.includes(keyName)) {
continue;
}
let fieldDetail = {};
await Utility.setDataType(fieldDetail, fields[field], moduleAPIName).catch((err) => { throw err; });
fieldsDetails[fields[field].getAPIName()] = fieldDetail;
}
if ((constants_js_1.Constants.INVENTORY_MODULES.includes(moduleAPIName.toLowerCase()))) {
let fieldDetail = {};
fieldDetail[constants_js_1.Constants.NAME] = constants_js_1.Constants.LINE_TAX;
fieldDetail[constants_js_1.Constants.TYPE] = constants_js_1.Constants.LIST_NAMESPACE;
fieldDetail[constants_js_1.Constants.STRUCTURE_NAME] = constants_js_1.Constants.LINE_TAX_NAMESPACE;
fieldDetail[constants_js_1.Constants.LOOKUP] = true;
fieldsDetails[constants_js_1.Constants.LINE_TAX] = fieldDetail;
}
if (moduleAPIName.toLowerCase() == constants_js_1.Constants.NOTES) {
let fieldDetail = {};
fieldDetail[constants_js_1.Constants.NAME] = constants_js_1.Constants.ATTACHMENTS;
fieldDetail[constants_js_1.Constants.TYPE] = constants_js_1.Constants.LIST_NAMESPACE;
fieldDetail[constants_js_1.Constants.STRUCTURE_NAME] = constants_js_1.Constants.ATTACHMENTS_NAMESPACE;
fieldsDetails[constants_js_1.Constants.ATTACHMENTS] = fieldDetail;
}
}
else if (responseHandler instanceof APIException) {
let errorResponse = {};
errorResponse[constants_js_1.Constants.CODE] = responseHandler.getCode().getValue();
errorResponse[constants_js_1.Constants.STATUS] = responseHandler.getStatus().getValue();
errorResponse[constants_js_1.Constants.MESSAGE] = responseHandler.getMessage();
let exception = new sdk_exception_js_1.SDKException(constants_js_1.Constants.API_EXCEPTION, null, errorResponse, null);
if (this.moduleAPIName != null && this.moduleAPIName.toLowerCase() == moduleAPIName.toLowerCase()) {
throw exception;
}
winston_1.default.error(constants_js_1.Constants.API_EXCEPTION, exception);
}
}
else {
let errorResponse = {};
errorResponse[constants_js_1.Constants.CODE] = response.getStatusCode();
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.API_EXCEPTION, null, errorResponse, null);
}
}
return fieldsDetails;
}
static async verifyPhotoSupport(moduleAPIName) {
try {
moduleAPIName = await Utility.verifyModuleAPIName(moduleAPIName).catch((err) => { throw err; });
if (constants_js_1.Constants.PHOTO_SUPPORTED_MODULES.includes(moduleAPIName.toLowerCase())) {
return true;
}
let modules = await Utility.getModuleNames().catch((err) => {
throw err;
});
if (modules.hasOwnProperty(moduleAPIName.toLowerCase()) && modules[moduleAPIName.toLowerCase()] != null) {
let moduleMetaData = modules[moduleAPIName.toLowerCase()];
if (moduleMetaData.hasOwnProperty(constants_js_1.Constants.GENERATED_TYPE) && moduleMetaData[constants_js_1.Constants.GENERATED_TYPE] != constants_js_1.Constants.GENERATED_TYPE_CUSTOM) {
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.UPLOAD_PHOTO_UNSUPPORTED_ERROR, constants_js_1.Constants.UPLOAD_PHOTO_UNSUPPORTED_MESSAGE + moduleAPIName);
}
}
}
catch (error) {
if (!(error instanceof sdk_exception_js_1.SDKException)) {
error = new sdk_exception_js_1.SDKException(null, null, null, error);
}
winston_1.default.error(constants_js_1.Constants.EXCEPTION, error);
throw error;
}
return true;
}
static async getModuleNames() {
let moduleData = {};
let initializer = await initializer_js_1.Initializer.getInitializer().catch((err) => { throw err; });
if (initializer == null || initializer == undefined) {
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.SDK_UNINITIALIZATION_ERROR, constants_js_1.Constants.SDK_UNINITIALIZATION_MESSAGE);
}
var resourcesPath = path.join(initializer.getResourcePath(), constants_js_1.Constants.FIELD_DETAILS_DIRECTORY);
if (!fs.existsSync(resourcesPath)) {
fs.mkdirSync(resourcesPath, { recursive: true });
}
let recordFieldDetailsPath = await this.getFileName().catch((err) => { throw err; });
let fieldMetaJSON = initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
if (!fs.existsSync(recordFieldDetailsPath) || (fs.existsSync(recordFieldDetailsPath) && (!fieldMetaJSON.hasOwnProperty(constants_js_1.Constants.SDK_MODULE_METADATA) || fieldMetaJSON[constants_js_1.Constants.SDK_MODULE_METADATA] == null || fieldMetaJSON[constants_js_1.Constants.SDK_MODULE_METADATA].length <= 0))) {
moduleData = await Utility.getModules(null).catch((err) => { throw err; });
await Utility.writeModuleMetaData(recordFieldDetailsPath, moduleData).catch((err) => { throw err; });
return moduleData;
}
let recordFieldDetailsJson = initializer_js_1.Initializer.getJSON(recordFieldDetailsPath);
return recordFieldDetailsJson[constants_js_1.Constants.SDK_MODULE_METADATA];
}
static async writeModuleMetaData(recordFieldDetailsPath, moduleData) {
let fieldDetailsJSON = fs.existsSync(recordFieldDetailsPath) ? initializer_js_1.Initializer.getJSON(recordFieldDetailsPath) : {};
fieldDetailsJSON[constants_js_1.Constants.SDK_MODULE_METADATA] = moduleData;
fs.writeFileSync(recordFieldDetailsPath, JSON.stringify(fieldDetailsJSON));
}
static async getModules(header) {
const HeaderMap = (await Promise.resolve().then(() => __importStar(require("../../routes/header_map.js")))).HeaderMap;
let ResponseWrapper = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/modules/response_wrapper.js")))).ResponseWrapper;
let APIException = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/modules/api_exception.js")))).APIException;
const ModuleOperations = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/modules/modules_operations.js")))).ModulesOperations;
const GetModulesHeader = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/modules/modules_operations.js")))).GetModulesHeader;
let apiNames = {};
let headerMap = new HeaderMap();
if (header != null) {
await headerMap.add(GetModulesHeader.IF_MODIFIED_SINCE, new Date(header));
}
let response = await new ModuleOperations().getModules(headerMap).catch((err) => { throw err; });
if (response != null) {
if ([constants_js_1.Constants.NO_CONTENT_STATUS_CODE, constants_js_1.Constants.NOT_MODIFIED_STATUS_CODE].includes(response.getStatusCode())) {
return apiNames;
}
let responseObject = response.getObject();
if (responseObject != null) {
if (responseObject instanceof ResponseWrapper) {
let modules = responseObject.getModules();
modules.forEach((module) => {
if (module.getAPISupported() == true) {
let moduleDetails = {};
moduleDetails[constants_js_1.Constants.API_NAME] = module.getAPIName();
moduleDetails[constants_js_1.Constants.GENERATED_TYPE] = module.getGeneratedType().getValue();
apiNames[module.getAPIName().toLowerCase()] = moduleDetails;
}
});
}
else if (responseObject instanceof APIException) {
let errorResponse = {};
errorResponse[constants_js_1.Constants.CODE] = responseObject.getCode().getValue();
errorResponse[constants_js_1.Constants.STATUS] = responseObject.getStatus().getValue();
errorResponse[constants_js_1.Constants.MESSAGE] = responseObject.getMessage();
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.API_EXCEPTION, null, errorResponse, null);
}
}
}
if (header == null) {
try {
let initializer = await initializer_js_1.Initializer.getInitializer().catch((err) => { throw err; });
if (initializer == null || initializer == undefined) {
throw new sdk_exception_js_1.SDKException(constants_js_1.Constants.SDK_UNINITIALIZATION_ERROR, constants_js_1.Constants.SDK_UNINITIALIZATION_MESSAGE);
}
var resourcesPath = path.join(initializer.getResourcePath(), constants_js_1.Constants.FIELD_DETAILS_DIRECTORY);
if (!fs.existsSync(resourcesPath)) {
fs.mkdirSync(resourcesPath, { recursive: true });
}
var recordFieldDetailsPath = resourcesPath + "/" + await this.getFileName().catch((err) => { throw err; });
await Utility.writeModuleMetaData(recordFieldDetailsPath, apiNames).catch((err) => { throw err; });
}
catch (error) {
if (!(error instanceof sdk_exception_js_1.SDKException)) {
error = new sdk_exception_js_1.SDKException(null, null, null, error);
}
winston_1.default.error(constants_js_1.Constants.EXCEPTION, error);
throw error;
}
}
return apiNames;
}
static async refreshModules() {
this.forceRefresh = true;
await Utility.getFieldsInfo(null).catch((err) => { throw err; });
this.forceRefresh = false;
}
static async getJSONObject(json, key) {
let keyArray = Array.from(Object.keys(json));
for (let keyInJSON of keyArray) {
if (key.toLowerCase() == keyInJSON.toLowerCase()) {
return json[keyInJSON];
}
}
return null;
}
static async setDataType(fieldDetail, field, moduleAPIName) {
var apiType = field.getDataType();
var keyName = field.getAPIName();
var module = new minified_module_js_1.MinifiedModule();
if (field.getSystemMandatory() != null && field.getSystemMandatory() == true && !(moduleAPIName.toLowerCase() == constants_js_1.Constants.CALLS && keyName.toLowerCase() == constants_js_1.Constants.CALL_DURATION)) {
fieldDetail.required = true;
}
if (keyName.toLowerCase() == constants_js_1.Constants.PRICING_DETAILS_API_NAME.toLowerCase() && moduleAPIName.toLowerCase() == constants_js_1.Constants.PRICE_BOOKS) {
fieldDetail.name = keyName;
fieldDetail.type = constants_js_1.Constants.LIST_NAMESPACE;
fieldDetail.structure_name = constants_js_1.Constants.PRICING_DETAILS;
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
return;
}
else if (keyName.toLowerCase() == constants_js_1.Constants.PARTICIPANT_API_NAME.toLowerCase() && (moduleAPIName.toLowerCase() == constants_js_1.Constants.EVENTS || moduleAPIName.toLowerCase() == constants_js_1.Constants.ACTIVITIES)) {
fieldDetail.name = keyName;
fieldDetail.type = constants_js_1.Constants.LIST_NAMESPACE;
fieldDetail.structure_name = constants_js_1.Constants.PARTICIPANTS;
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
return;
}
else if (keyName.toLowerCase() == constants_js_1.Constants.COMMENTS.toLowerCase() && (moduleAPIName.toLowerCase() == constants_js_1.Constants.SOLUTIONS || moduleAPIName.toLowerCase() == constants_js_1.Constants.CASES)) {
fieldDetail.name = keyName;
fieldDetail.type = constants_js_1.Constants.LIST_NAMESPACE;
fieldDetail.structure_name = constants_js_1.Constants.COMMENT_NAMESPACE;
fieldDetail.lookup = true;
return;
}
else if (keyName.toLowerCase() == constants_js_1.Constants.LAYOUT.toLowerCase()) {
fieldDetail.name = keyName;
fieldDetail.type = constants_js_1.Constants.LAYOUT_NAMESPACE;
fieldDetail.structure_name = constants_js_1.Constants.LAYOUT_NAMESPACE;
fieldDetail.lookup = true;
return;
}
else if ((keyName.toLowerCase() == constants_js_1.Constants.TERRITORIES.toLowerCase() || keyName.toLowerCase() == constants_js_1.Constants.TERRITORY.toLowerCase()) && field.getCustomField() !== null && field.getCustomField() == false) {
fieldDetail.name = keyName;
fieldDetail.type = constants_js_1.Constants.LIST_NAMESPACE;
fieldDetail.structure_name = constants_js_1.Constants.TERRITORY_NAMESPACE;
fieldDetail.lookup = true;
return;
}
else if (keyName.toLowerCase() == constants_js_1.Constants.PRODUCT_NAME.toLowerCase() && constants_js_1.Constants.INVENTORY_MODULES_ITEMS.includes(moduleAPIName.toLowerCase())) {
fieldDetail.name = keyName;
fieldDetail.type = constants_js_1.Constants.LINEITEM_PRODUCT;
fieldDetail.structure_name = constants_js_1.Constants.LINEITEM_PRODUCT;
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
return;
}
else if (keyName.toLowerCase() == constants_js_1.Constants.DISCOUNT.toLowerCase() && constants_js_1.Constants.INVENTORY_MODULES_ITEMS.includes(moduleAPIName.toLowerCase())) {
fieldDetail.name = keyName;
fieldDetail.type = constants_js_1.Constants.STRING_NAMESPACE;
return;
}
else if (keyName.toLowerCase() == constants_js_1.Constants.TAX.toLowerCase() && constants_js_1.Constants.PRODUCTS.toLowerCase() == moduleAPIName.toLowerCase()) {
fieldDetail.name = keyName;
fieldDetail.type = constants_js_1.Constants.LIST_NAMESPACE;
fieldDetail.structure_name = constants_js_1.Constants.TAX_NAMESPACE;
return;
}
else if (Utility.apiTypeVsDataType.has(apiType)) {
fieldDetail.type = Utility.apiTypeVsDataType.get(apiType);
}
else if (apiType.toLowerCase() == constants_js_1.Constants.FORMULA.toLowerCase()) {
if (field.getFormula() != null) {
let returnType = field.getFormula().getReturnType();
if (returnType != null && Utility.apiTypeVsDataType.has(returnType) && Utility.apiTypeVsDataType.get(returnType) != null) {
fieldDetail.type = Utility.apiTypeVsDataType.get(returnType);
}
}
fieldDetail[constants_js_1.Constants.READ_ONLY] = true;
}
else if (apiType.toLowerCase() == constants_js_1.Constants.ROLLUP_SUMMARY.toLowerCase()) {
if (field.getRollupSummary() != null) {
const returnType = field.getRollupSummary().getReturnType();
if (Utility.apiTypeVsDataType.get(returnType) != null) {
fieldDetail.type = Utility.apiTypeVsDataType.get(returnType);
}
else if (Utility.apiTypeVsDataType.get(field.getJsonType()) != null) {
fieldDetail.type = Utility.apiTypeVsDataType.get(field.getJsonType());
}
}
}
else {
return;
}
if (apiType.toLowerCase().includes(constants_js_1.Constants.LOOKUP.toLowerCase())) {
fieldDetail.lookup = true;
}
if (apiType.toLowerCase() == constants_js_1.Constants.CONSENT_LOOKUP || apiType.toLowerCase() == constants_js_1.Constants.OWNER_LOOKUP) {
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
}
if (apiType.toLowerCase() == constants_js_1.Constants.MULTI_SELECT_LOOKUP) {
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
if (field.getMultiselectlookup() != null && field.getMultiselectlookup().getLinkingModule() != null) {
let linkingModule = field.getMultiselectlookup().getLinkingModule();
fieldDetail[constants_js_1.Constants.MODULE] = linkingModule.getAPIName();
module = linkingModule;
}
fieldDetail[constants_js_1.Constants.SUBFORM] = true;
}
if (apiType.toLowerCase() == constants_js_1.Constants.MULTI_USER_LOOKUP) {
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
if (field.getMultiuserlookup() != null && field.getMultiuserlookup().getLinkingModule() != null) {
let linkingModule = field.getMultiuserlookup().getLinkingModule();
fieldDetail[constants_js_1.Constants.MODULE] = linkingModule.getAPIName();
module = linkingModule;
}
fieldDetail[constants_js_1.Constants.SUBFORM] = true;
}
if (apiType.toLowerCase() == constants_js_1.Constants.MULTI_MODULE_LOOKUP) {
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
fieldDetail[constants_js_1.Constants.SUBFORM] = true;
}
if (Utility.apiTypeVsStructureName.has(apiType)) {
fieldDetail.structure_name = Utility.apiTypeVsStructureName.get(apiType);
}
if (apiType.toLowerCase() == constants_js_1.Constants.PICKLIST && field.getPickListValues() != null && field.getPickListValues().length > 0) {
let values = [];
fieldDetail.picklist = true;
field.getPickListValues().every((x) => values.push(x.getDisplayValue()));
fieldDetail.values = values;
}
if (apiType == constants_js_1.Constants.SUBFORM && field.getAssociatedModule() != null) {
module.setAPIName(field.getAssociatedModule().getModule());
fieldDetail.module = module.getAPIName();
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
fieldDetail.subform = true;
}
if (apiType == constants_js_1.Constants.LOOKUP && field.getLookup() != null) {
let module1 = field.getLookup().getModule();
if (module1 != null && module1.getAPIName().toLowerCase() != constants_js_1.Constants.SE_MODULE) {
module.setAPIName(module1.getAPIName());
module.setId(module1.getId());
fieldDetail.module = module.getAPIName();
if (module1.getAPIName().toLowerCase() == constants_js_1.Constants.ACCOUNTS && field.getCustomField() != null && !field.getCustomField()) {
fieldDetail[constants_js_1.Constants.SKIP_MANDATORY] = true;
}
}
else {
const MinifiedModule = (await Promise.resolve().then(() => __importStar(require("../../core/com/zoho/crm/api/modules/minified_module.js")))).MinifiedModule;
module = new MinifiedModule();
}
fieldDetail.lookup = true;
}
if (module != null && module.getAPIName() != null && module.getAPIName().length > 0) {
await Utility.getFieldsInfo(module.getAPIName()).catch((err) => { throw err; });
}
fieldDetail.name = keyName;
}
static async fillDataType() {
if (this.apiTypeVsDataType.size > 0) {
return;
}
let fieldAPINamesString = [
"textarea",
"text",
"website",
"email",
"phone",
"mediumtext",
"profileimage",
"autonumber",
];
let fieldAPINamesInteger = ["integer"];
let fieldAPINamesBoolean = ["boolean"];
let fieldAPINamesLong = ["long", "bigint"];
let fieldAPINamesDouble = ["double", "percent", "lookup", "currency"];
let fieldAPINamesFieldFile = ["fileupload"];
let fieldAPINamesDateTime = ["datetime", "event_reminder"];
let fieldAPINamesDate = ["date"];
let fieldAPINamesLookup = ["lookup"];
let fieldAPINamesPickList = ["picklist"];
let fieldAPINamesMultiSelectPickList = ["multiselectpicklist"];
let fieldAPINamesSubForm = ["subform"];
let fieldAPINamesOwnerLookUp = ["ownerlookup", "userlookup"];
let fieldAPINamesMultiUserLookUp = ["multiuserlookup"];
let fieldAPINameTaskRemindAt = ["ALARM"];
let fieldAPINameRecurringActivity = ["RRULE"];
let fieldAPINameReminder = ["multireminder"];
let fieldAPINameConsentLookUp = ["consent_lookup"];
let fieldAPINameImageUpload = ["imageupload"];
let fieldAPInameMultiSelectLookUp = ["multiselectlookup"];
let fieldAPINameLineTax = ["linetax"];
let fieldAPINamesModule = ["module"];
let fieldAPINamesLayout = ["layout"];
let fieldAPINamesMultiModuleLookUp = ["multi_module_lookup"];
let fieldAPINamesTimeRange = ["time_range