UNPKG

82.2 kBSource Map (JSON)View Raw
1{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///external \"@harvestr-api/utils\"","webpack:///external \"@harvestr-api/common\"","webpack:///./src/services/intercom-api.service.ts","webpack:///external \"ts-optchain\"","webpack:///external \"base64url\"","webpack:///external \"passport\"","webpack:///external \"passport-intercom\"","webpack:///./src/services/intercom-utils.service.ts","webpack:///./src/services/intercom.service.ts","webpack:///./src/main.ts","webpack:///external \"intercom-client\"","webpack:///external \"q\"","webpack:///external \"request\"","webpack:///./src/services/intercom-converter.service.ts","webpack:///./src/services/intercom-legacy-oauth.service.ts","webpack:///./src/services/intercom-oauth.service.ts","webpack:///external \"shortid\"","webpack:///external \"graphql-tag\"","webpack:///./src/services/intercom-canvas.service.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","require","Intercom","intercomApiService","intercom_token","deferred","Q","defer","Client","token","integration_access_token","admins","list","async","error","doc","Error","resolve","body","reject","promise","admin_id","find","where","users","resp","user","type","contacts","companies","logger","debug","JSON","stringify","organization_name","options","url","method","headers","Authorization","Accept","response","parse","intercom_conversation_id","statusCode","args","webhook_response","integration_webhook_id","info","verbose","intercom_code","INTERCOM_OAUTH_CLIENT_ID","INTERCOM_OAUTH_CLIENT_SECRET","access_token","content","conversation_id","data","id","oc","integration_trigger_id","intercom_user_id","message_type","parsed_reponse","app_id","app","id_code","intercomUtilsService","note_content","user_id","intercom_app_id","regex","exec","index","lastIndex","result_app_id","result_user_id","title","componentName","state","feedbackNumber","tags","tagNames","forEach","tag","push","text","style","items","field","length","toString","split","join","label","shortid","generate","action","process","env","HARVESTR_CLIENT_URL","intercomService","integration_id","context","INTERCOM_WIDGET_MESSAGE_FRAGMENT","messageService","getMessages","orderBy","$fragment","insert","array","el","some","a","extractSubMessages","intercom_conversation","conversation_parts","filter","sub","part_type","getConversationMessages","conversation_message","convertToSubmessage","sub_message","created_persons","mongoId","submitter","connect","pers","intercom_id","author","convertToPerson","intercom_user_short","intercom_user","person","findUser","catch","err","console","log","email","personService","exists","getPersons","deleted","phone","undefined","pseudonym","avatar","image_url","findAdmin","details","upsertPerson","getUpsertWhere","createUniquePersons","sub_messages","all_persons","Promise","all","map","intercomConverterService","intercom_company","organization","integrationSyncs","integration_type","elementId","elementType","elementUrl","elementApiUrl","elementProjectId","_projectId","project_id","update","organizationService","upsertOrganization","intercom_workspace_id","created_submitter","created_requester","labels","messageLabelService","upsertManyMessageLabels","createMessage","clientId","recipient_address","subject","channel","integration_url","requester","harvestr_message","updateMessage","updated","submessageBeforeUpdateId","last_submessage_clientId","intercom_data","getConversation","item","links","conversation_web","passport","IntercomStrategy","Strategy","intercom_legacy","use","clientID","INTERCOM_LEGACY_OAUTH_CLIENT_ID","clientSecret","INTERCOM_LEGACY_OAUTH_CLIENT_SECRET","accessToken","refreshToken","profile","done","intercomLegacyOauthService","req","res","query","authenticate","decode","code","intercom_access_token","getAccessToken","domain","HARVESTR_API_URL","legacyCreateWebhookSubscription","service_type","topics","apiTokenService","upsertApiToken","source","integration_workspace_id","notify_linked","notify_state","sync_organizations","status","send","intercom","intercomOauthService","me","getMe","mainCanvas","canvas","components","align","loginCanvas","conversationReadNotif","discoveries_length","isRead","size","discovery_id","intercomCanvasService","initCanvas","workspaceId","conversationId","tokenIntercomService","getApiToken","message","getMessage","linked_cards","chunk","chunks","discovery","card","client_domain","toClientId","feedback_number","discoveries_number","linked_discoveries_title","allDiscoveries","linked_card","formatDiscoveryCanvas","parent","discoverystate","discoveriesCanvas","discoveriesMore","stored_data","message_id","discoveries","concat","abstractCanvas","read"],"mappings":"6DACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAG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ACnDsM,EAAa3K,KAAK,IACX8K,EACH9N,IAAK,GACD6D,QAAQC,IAAIkK,eAAiB,wBACX,EAAAC,WAAWH,GAAWzM,KAC5C6M,gBAAiB,EAAA5M,GAAGwM,GAAWD,OAAO,IAAIxK,QAAU,IAWpE,MAzHe,EACnB4F,EACA+D,EACAW,KAEAtH,QAAQC,IAAI,eAAgBqH,GAC5B,MAAMQ,GAAsBR,GAAgB,IAAItK,OAC1C+K,EAA2BD,EAC3B,CAKI,CACI5O,KAAM,OACN0D,KAAM,wBAAwBkL,MAC9BvB,MAAO,OACP1J,MAAO,WAGf,GACAmL,GAAkBV,GAAgB,IAAIjG,IAAK4G,GAC7C,EAAAxM,qBAAqByM,sBACjBD,EAAY9L,MACZ8L,EAAYtO,IACZsO,EAAYE,OAAOhM,MACnB8L,EAAYG,eAAerS,KAC3BkS,EAAYJ,gBACZI,EAAY1L,OAGd8L,EAAoBP,EAAqBE,EAAe,GAAK,GAG7DM,EACFR,EAAqB,EACf,CACI,CACI5O,KAAM,WAEV,CACIA,KAAM,SACN8B,GAAI,wBACJoC,MAAO,yBAVrB0K,EAAqB,EAAIA,EAAqB,EAAI,UAWpCjL,MAAO,OACPU,OAAQ,CACJrE,KAAM,YAIlB,GAqBV,MApBe,CACXmN,OAAQ,CACJxL,QAAS,CACLyL,WAAY,IACLG,EAAsB,CACrBE,SACAE,aAAcjE,EACd8D,oBAAqBY,GAAgB,IAAItK,YAE1C+K,KACAM,KACAC,IAGXC,YAAa,CACTC,WAAY5F,EACZ6F,YAAmB,GAAIC,UAAUV,OAgDrBW,CAChBvB,EAAQxE,UAAY,GACpBwE,EAAQwB,KACRtB,GAMR,OAAOlB","file":"main.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 9);\n","module.exports = require(\"@harvestr-api/utils\");","module.exports = require(\"@harvestr-api/common\");","import { logger } from \"@harvestr-api/utils\";\nconst Intercom = require(\"intercom-client\");\nimport * as Q from \"q\";\nimport request from \"request\";\nimport { oc } from \"ts-optchain\";\n\nimport {\n IntercomCompany,\n IntercomConversation,\n IntercomUserFull,\n IntercomWebhookResponse,\n IntercomGetUsersResp,\n IntercomApiMe\n} from \"../models/intercom\";\n\nexport const intercomApiService = {\n async findAdmins(intercom_token: { integration_access_token: string }) {\n const deferred = Q.defer<any>();\n const client = new Intercom.Client({\n token: intercom_token.integration_access_token\n });\n client.admins.list(async (error, doc) => {\n try {\n if (error) throw new Error(error);\n deferred.resolve(doc.body.admins);\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async findAdmin(\n admin_id: string,\n intercom_token: {\n integration_access_token: string;\n }\n ) {\n const deferred = Q.defer<any>();\n const client = new Intercom.Client({\n token: intercom_token.integration_access_token\n });\n client.admins.find(admin_id, async (error, doc) => {\n try {\n if (error) throw new Error(error);\n deferred.resolve(doc.body);\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async findUser(\n where: { id?: string; email?: string },\n intercom_token: {\n integration_access_token: string;\n }\n ) {\n const deferred = Q.defer<IntercomUserFull | null>();\n const client = new Intercom.Client({\n token: intercom_token.integration_access_token\n });\n client.users.find(where, async (error, doc) => {\n try {\n if (error) throw new Error(error);\n const resp: IntercomGetUsersResp | IntercomUserFull = doc.body;\n let user: IntercomUserFull | null = null;\n switch (resp.type) {\n case \"user.list\":\n user = ((<IntercomGetUsersResp>doc.body).users ||\n [])[0];\n break;\n case \"contact.list\":\n user = ((<any>doc.body).contacts || [])[0];\n break;\n case \"user\":\n case \"contact\":\n user = <IntercomUserFull>doc.body;\n break;\n default:\n break;\n }\n // logger.debug(\n // \"Debugging intercom findUser: \",\n // JSON.stringify(resp)\n // );\n deferred.resolve(user);\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async findCompany(\n where: { id: string },\n intercom_token: {\n integration_access_token: string;\n }\n ) {\n const deferred = Q.defer<IntercomCompany>();\n const client = new Intercom.Client({\n token: intercom_token.integration_access_token\n });\n client.companies.find(where, async (error, doc) => {\n try {\n if (error) throw new Error(error);\n logger.debug(\n \"Debugging intercom findCompany: \",\n JSON.stringify(doc.body)\n );\n deferred.resolve(doc.body);\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async findCompanyFromName(\n organization_name: string,\n intercom_token: {\n integration_access_token: string;\n }\n ) {\n const deferred = Q.defer<IntercomCompany>();\n // Set the headers\n const headers = {\n Authorization: \"Bearer \" + intercom_token.integration_access_token,\n Accept: \"application/json\"\n };\n // Configure the request\n const options = {\n url: `https://api.intercom.io/companies?name=${organization_name}`,\n method: \"GET\",\n headers: headers\n };\n // Start the request\n request(options, async (error, response, body) => {\n try {\n if (error) throw new Error(error);\n deferred.resolve(JSON.parse(body));\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async getConversation(\n intercom_conversation_id: string,\n intercom_token: {\n integration_access_token: string;\n }\n ) {\n const deferred = Q.defer<IntercomConversation>();\n // Set the headers\n const headers = {\n Authorization: \"Bearer \" + intercom_token.integration_access_token,\n Accept: \"application/json\"\n };\n // Configure the request\n const options = {\n url:\n \"https://api.intercom.io/conversations/\" +\n intercom_conversation_id,\n method: \"GET\",\n headers: headers\n };\n // Start the request\n request(options, async (error, response, body) => {\n try {\n if (error) throw new Error(error);\n if (response.statusCode !== 200) {\n throw new Error(\n \"intercom request not sending a 200 : \" +\n JSON.stringify(response)\n );\n }\n\n deferred.resolve(JSON.parse(body));\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async legacyCreateWebhookSubscription(\n args: {\n service_type: string;\n url: string;\n topics: string[];\n },\n integration_access_token: string\n ) {\n const deferred = Q.defer<IntercomWebhookResponse>();\n // Set the headers\n const headers = {\n Authorization: \"Bearer \" + integration_access_token,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\"\n };\n // Configure the request\n const options = {\n url: \"https://api.intercom.io/subscriptions\",\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(args)\n };\n\n // Start the request\n request(options, async (error, response, body) => {\n try {\n if (error) throw new Error(error);\n if (response.statusCode === 200) {\n const webhook_response: IntercomWebhookResponse = JSON.parse(\n body\n );\n /*\n console.log(\n \"webhook response newly created in intercom(): \",\n webhook_response\n );\n */\n deferred.resolve(webhook_response);\n } else {\n logger.error(\n `intercom request not sending a 200 :\n ${JSON.stringify(response)}`\n );\n throw new Error(\"Request Error\");\n }\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async legacyDeleteWebhookSubscription(intercom_token: {\n integration_webhook_id: string;\n integration_access_token: string;\n }) {\n const deferred = Q.defer();\n // Set the headers\n const headers = {\n Authorization: \"Bearer \" + intercom_token.integration_access_token,\n Accept: \"application/json\"\n };\n // Configure the request\n const options = {\n url: `https://api.intercom.io/subscriptions/${intercom_token.integration_webhook_id}`,\n method: \"DELETE\",\n headers: headers\n };\n // Start the request\n request(options, async (error, response, body) => {\n try {\n if (error) throw new Error(error);\n if (response.statusCode === 200) {\n logger.info(`webhook successfully deleted`);\n deferred.resolve();\n } else {\n logger.error(\n `intercom request not sending a 200 :\n ${JSON.stringify(response)}`\n );\n throw new Error(\"Request Error\");\n }\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async getAccessToken(args: {\n intercom_code: string;\n INTERCOM_OAUTH_CLIENT_ID: string;\n INTERCOM_OAUTH_CLIENT_SECRET: string;\n }) {\n logger.verbose(\"asking for intercom access token\");\n const deferred = Q.defer<string>();\n // Configure the request\n const options = {\n url:\n \"https://api.intercom.io/auth/eagle/token?code=\" +\n args.intercom_code +\n \"&client_id=\" +\n args.INTERCOM_OAUTH_CLIENT_ID +\n \"&client_secret=\" +\n args.INTERCOM_OAUTH_CLIENT_SECRET +\n \"\",\n method: \"POST\"\n };\n // Start the request\n request(options, async (error, response, body) => {\n try {\n if (error) throw new Error(error);\n if (response.statusCode === 200) {\n logger.info(`received intercom token ${body}`);\n deferred.resolve(JSON.parse(body).access_token);\n } else {\n logger.error(\n `intercom request not sending a 200 :\n ${JSON.stringify(response)}`\n );\n throw new Error(\"Request Error\");\n }\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n },\n async createNote(\n content: string,\n conversation_id: string | number,\n intercom_token: {\n integration_trigger_id: string;\n integration_access_token: string;\n }\n ) {\n // Set the headers\n const headers = {\n Authorization: \"Bearer \" + intercom_token.integration_access_token,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\"\n };\n\n const data = {\n id: oc(intercom_token).integration_trigger_id(\"\"),\n intercom_user_id: oc(intercom_token).integration_trigger_id(\"\"),\n type: \"admin\",\n message_type: \"note\",\n body: `[Harvestr] ${content}`\n };\n logger.info(conversation_id);\n // Configure the request\n const options = {\n url: `https://api.intercom.io/conversations/${conversation_id}/reply`,\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(data)\n };\n // Start the request\n request(options, async (error, response, body) => {\n // logger.info(\"error?:\", error)\n // logger.info(\"body?:\", body);\n // logger.info(\"response?:\", response)\n });\n },\n async getMe(intercom_token: { integration_access_token: string }) {\n const deferred = Q.defer<{ app_id: string; id: string }>();\n // Set the headers\n const headers = {\n Authorization: \"Bearer \" + intercom_token.integration_access_token,\n Accept: \"application/json\"\n };\n // Configure the request\n const options = {\n url: `https://api.intercom.io/me`,\n method: \"GET\",\n headers: headers\n };\n // Start the request\n request(options, async (error, response, body) => {\n try {\n if (error) throw new Error(error);\n const parsed_reponse: IntercomApiMe = JSON.parse(body);\n deferred.resolve({\n app_id: oc(parsed_reponse).app.id_code(\"\"),\n id: oc(parsed_reponse).id(\"\")\n });\n } catch (error) {\n deferred.reject(error);\n }\n });\n return deferred.promise;\n }\n};\n","module.exports = require(\"ts-optchain\");","module.exports = require(\"base64url\");","module.exports = require(\"passport\");","module.exports = require(\"passport-intercom\");","import { logger } from \"@harvestr-api/utils\";\nimport * as shortid from \"shortid\";\n\nexport const intercomUtilsService = {\n async findTrigger(\n note_content: string,\n user_id: string,\n intercom_app_id: string\n ) {\n // format of an Intercom Admin mention: <a class=\\\"entity_mention\\\" href=\\\"//app.intercom.io/apps/giuqxqva/admin/1376798\\\" rel=\\\"nofollow noopener noreferrer\\\" target=\\\"_blank\\\">\n const regex = /<a.*?href=\"\\/\\/app\\.intercom\\.io\\/apps\\/([^\"]*?)\\/admin\\/([^\"]*?)\".*?>/g;\n let m = regex.exec(note_content);\n logger.info(\"starting intercom note parsing\");\n while (m !== null) {\n // This is necessary to avoid infinite loops with zero-width matches\n if (m.index === regex.lastIndex) {\n regex.lastIndex++;\n }\n const result_app_id = m[1];\n const result_user_id = m[2];\n logger.info(\n `Admin mentionned in intercom note ${result_app_id} : ${result_user_id}`\n );\n // check if user match and note and admin come from the good app\n if (\n result_app_id === intercom_app_id &&\n result_user_id === user_id\n ) {\n // thats a note destinated to Harvestr\n return true;\n }\n m = regex.exec(note_content);\n }\n return false;\n },\n formatDiscoveryCanvas(\n title: string,\n url: string,\n componentName: string,\n state: string,\n feedbackNumber: number,\n tags: any\n ) {\n const tagNames: any = [];\n tags.forEach(tag => tagNames.push(tag.name));\n return [\n {\n type: \"divider\"\n },\n {\n type: \"text\",\n text: `*${title}*`,\n style: \"muted\"\n },\n {\n type: \"data-table\",\n items: [\n {\n type: \"field-value\",\n field: \"In component\",\n value: componentName\n },\n {\n type: \"field-value\",\n field: \"Current state\",\n value: state\n },\n {\n type: \"field-value\",\n field: \"Feedback volume\",\n value: feedbackNumber\n },\n {\n type: \"field-value\",\n field: \"Tags\",\n value: tags.length\n ? tagNames\n .toString()\n .split(\",\")\n .join(\", \")\n : \"N/A\"\n }\n ]\n },\n {\n type: \"button\",\n label: \"Open discovery\",\n style: \"secondary\",\n id: \"open-discovery-\" + shortid.generate(),\n action: {\n type: \"url\",\n url: `${process.env.HARVESTR_CLIENT_URL + url}`\n }\n }\n ];\n }\n};\n","import { messageService, AuthContext } from \"@harvestr-api/common\";\nimport { gqlIntercomIntMessageFragment } from \"@harvestr-api/models\";\nimport gql from \"graphql-tag\";\n\nexport const intercomService = {\n async getMessage(integration_id: string, context: AuthContext) {\n /*\n const messages = (await messageService.getMessages(\n { where: { integration_id }, orderBy: \"createdAt_DESC\" },\n context\n ));\n */\n const INTERCOM_WIDGET_MESSAGE_FRAGMENT = gql`\n fragment IntercomIntMessage on Message {\n id\n clientId\n createdAt\n updatedAt\n tags\n integration_url\n integration_id\n recipient_address\n title\n content\n channel\n read\n archived\n processed\n chunks {\n id\n clientId\n discovery {\n id\n clientId\n title\n discoverystate {\n name\n color\n id\n clientId\n }\n tags {\n name\n color\n id\n clientId\n }\n parent {\n id\n clientId\n title\n }\n chunks {\n id\n clientId\n }\n }\n }\n }\n `;\n const messages = <gqlIntercomIntMessageFragment[]>(\n await messageService\n .getMessages(\n { where: { integration_id }, orderBy: \"createdAt_DESC\" },\n context\n )\n .$fragment(INTERCOM_WIDGET_MESSAGE_FRAGMENT)\n );\n\n return messages[0];\n }\n};\n","// models\nexport * from \"./models/intercom\";\n// services\nexport * from \"./services/intercom-api.service\";\nexport * from \"./services/intercom-converter.service\";\nexport * from \"./services/intercom-legacy-oauth.service\";\nexport * from \"./services/intercom-oauth.service\";\nexport * from \"./services/intercom-utils.service\";\nexport * from \"./services/intercom.service\";\nexport * from \"./services/intercom-canvas.service\";\n","module.exports = require(\"intercom-client\");","module.exports = require(\"q\");","module.exports = require(\"request\");","import {\n AuthContext,\n messageService,\n organizationService,\n personService,\n messageLabelService\n} from \"@harvestr-api/common\";\nimport {\n gqlOrganizationCreateWithoutProjectInput,\n gqlOrganizationUpdateWithoutProjectDataInput,\n gqlOrganizationWhereInput,\n gqlPersonCreateWithoutProjectInput,\n gqlPersonWhereInput,\n gqlSubmessageCreateWithoutMessageInput\n} from \"@harvestr-api/models\";\nimport { logger } from \"@harvestr-api/utils\";\nimport { Omit } from \"lodash\";\nimport { oc } from \"ts-optchain\";\n\nimport {\n IntercomCompany,\n IntercomConversation,\n IntercomData,\n IntercomUserFull,\n IntercomUserShort\n} from \"../models/intercom\";\nimport { intercomApiService } from \"./intercom-api.service\";\n\ninterface CreatedPerson {\n id: string;\n intercom_id: string;\n}\n\nconst insert = (array, el) => {\n return array.some(a => a.id === el.id) ? array : [...array, el];\n};\n\nconst extractSubMessages = (intercom_conversation: IntercomConversation) => {\n return oc(intercom_conversation)\n .conversation_parts.conversation_parts([])\n .filter(\n sub =>\n // only store notes and comments (do not store closing or ticket assignation for instance)\n sub.part_type === \"comment\" ||\n sub.part_type === \"assignment\" ||\n sub.part_type === \"note\"\n )\n .filter(sub => sub.body);\n};\n\nconst getConversationMessages = (\n intercom_conversation: IntercomConversation\n): {\n id;\n part_type;\n body;\n author: IntercomUserShort;\n}[] => {\n return (\n [\n intercom_conversation.conversation_message,\n ...extractSubMessages(intercom_conversation)\n ]\n // remove messages with empty body\n .filter(sub => sub.body)\n );\n};\n\nconst convertToSubmessage = async (\n sub_message: {\n id;\n part_type;\n body;\n author: IntercomUserShort;\n },\n created_persons: CreatedPerson[]\n) => {\n const cc_mess: gqlSubmessageCreateWithoutMessageInput = {\n mongoId: sub_message.id.toString(),\n type: sub_message.part_type === \"note\" ? \"NOTE\" : \"MESSAGE\",\n content: sub_message.body || \"\",\n submitter: {\n connect: {\n id: (\n created_persons.find(\n pers => pers.intercom_id === sub_message.author.id\n ) || { id: \"\" }\n ).id\n }\n }\n };\n return cc_mess;\n};\n\nconst convertToPerson = async (\n intercom_user_short: IntercomUserShort,\n intercom_token: {\n integration_access_token: string;\n },\n context: AuthContext\n) => {\n let intercom_user:\n | (IntercomUserShort & {\n phone?: string;\n pseudonym?: string;\n avatar?: any;\n })\n | IntercomUserFull\n | null;\n let person: gqlPersonCreateWithoutProjectInput;\n let where: gqlPersonWhereInput;\n\n switch (intercom_user_short.type) {\n case \"user\":\n case \"contact\":\n case \"lead\":\n intercom_user = await intercomApiService\n .findUser({ id: intercom_user_short.id }, intercom_token)\n .catch(err => {\n console.log(\"could not find Intercom user\");\n return intercom_user_short;\n });\n if (!intercom_user) {\n logger.debug(\"Intercom user not found\");\n return intercom_user_short;\n }\n where = oc(intercom_user).email()\n ? { email: intercom_user.email }\n : {\n name: intercom_user.name\n };\n if (await personService.exists(where, context)) {\n const found_person = (await personService.getPersons(\n {\n where\n },\n context\n ))[0];\n return found_person;\n }\n person = {\n type: \"CUSTOMER\",\n deleted: false,\n email: intercom_user.email,\n phone: intercom_user.phone || undefined,\n name: intercom_user.name || oc(intercom_user).pseudonym(\"\"),\n avatar: oc(intercom_user).avatar.image_url()\n ? {\n create: {\n name: intercom_user.avatar.name || \"\",\n url: intercom_user.avatar.image_url\n }\n }\n : undefined\n };\n break;\n case \"admin\":\n case \"team\":\n intercom_user = await intercomApiService\n .findAdmin(intercom_user_short.id, {\n integration_access_token: oc(\n intercom_token\n ).integration_access_token(\"\")\n })\n .catch(err => {\n console.log(\"could not find Intercom admin\");\n return intercom_user_short;\n });\n if (!intercom_user) {\n logger.debug(\"Intercom admin not found\");\n return intercom_user_short;\n }\n where = oc(intercom_user).email()\n ? { email: intercom_user.email }\n : {\n name: oc(intercom_user).name(\"Unnammed user\")\n };\n if (await personService.exists(where, context)) {\n const found_person = (await personService.getPersons(\n {\n where\n },\n context\n ))[0];\n return found_person;\n }\n person = {\n deleted: false,\n email: oc(intercom_user).email(),\n type: \"CUSTOMER\",\n name:\n intercom_user.name ||\n oc(intercom_user).pseudonym(\"Unnammed user\")\n };\n break;\n default:\n if (await personService.exists({ email: \"operator\" }, context)) {\n const found_person = (await personService.getPersons(\n {\n where: { email: \"operator\" }\n },\n context\n ))[0];\n return found_person;\n }\n // its a bot, create it if it doesnt exist\n person = {\n deleted: true,\n name: \"Intercom operator\",\n type: \"CUSTOMER\", // role of this person within the scope of the comany: Collaborator, Customer\n email: \"operator\",\n details: \"Intercom operator bot which generates auto replies\"\n };\n break;\n }\n return personService.upsertPerson(\n personService.getUpsertWhere(\n {\n name: person.name,\n email: person.email || undefined\n },\n context\n ),\n person,\n { deleted: false },\n context\n );\n};\n\nconst createUniquePersons = async (\n intercom_conversation: IntercomConversation,\n submitter: IntercomUserShort | null,\n intercom_token: {\n integration_access_token: string;\n },\n context: AuthContext\n): Promise<CreatedPerson[]> => {\n const sub_messages = getConversationMessages(intercom_conversation);\n // get all unique prsons\n let all_persons: IntercomUserShort[] = [];\n all_persons = intercom_conversation.user\n ? insert(all_persons, intercom_conversation.user)\n : all_persons;\n all_persons = submitter ? insert(all_persons, submitter) : all_persons;\n for (const sub_message of sub_messages) {\n all_persons = sub_message.author\n ? insert(all_persons, sub_message.author)\n : all_persons;\n }\n all_persons = all_persons.filter(pers => pers && pers.id);\n logger.verbose(\"persons length: \", all_persons.length);\n // creating all unique persons\n return Promise.all(\n all_persons.map(async person => ({\n id: (await convertToPerson(person, intercom_token, context)).id,\n intercom_id: person.id\n }))\n );\n};\n\nexport const intercomConverterService = {\n async convertToOrganization(\n intercom_company: IntercomCompany,\n intercom_token: {\n integration_access_token: string;\n },\n context: AuthContext\n ) {\n logger.debug(\n \"converting the following intercom company: \",\n intercom_company\n );\n const organization: {\n where: gqlOrganizationWhereInput;\n create: Omit<\n gqlOrganizationCreateWithoutProjectInput,\n \"defaultPerson\"\n >;\n update: gqlOrganizationUpdateWithoutProjectDataInput;\n } = {\n where: { name: intercom_company.name },\n create: {\n name: intercom_company.name || \"\",\n integrationSyncs: {\n create: [\n {\n integration_type: \"INTERCOM\",\n elementId: intercom_company.id,\n elementType: \"company\",\n elementUrl: `https://app.intercom.io/apps/${\n intercom_company.app_id\n }/companies/${intercom_company.id}`,\n elementApiUrl: `https://api.intercom.io/companies/${\n intercom_company.id\n }`,\n elementProjectId: intercom_company.app_id,\n _projectId: context.project_id\n }\n ]\n }\n // attributes: {\n // size: intercom_company.size,\n // ser_count: intercom_company.user_count,\n // industry: intercom_company.industry,\n // website: intercom_company.website,\n // monthly_spend: intercom_company.monthly_spend,\n // session_count: intercom_company.session_count,\n // custom_attributes: intercom_company.custom_attributes\n // }\n },\n update: {\n // integrationSyncs: {\n // upsert: [{ where: {}, create: {}, update: {} }]\n // }\n // attributes: {\n // size: intercom_company.size,\n // ser_count: intercom_company.user_count,\n // industry: intercom_company.industry,\n // website: intercom_company.website,\n // monthly_spend: intercom_company.monthly_spend,\n // session_count: intercom_company.session_count,\n // custom_attributes: intercom_company.custom_attributes\n // }\n }\n };\n return organizationService.upsertOrganization(\n organization.where,\n organization.create,\n organization.update,\n context\n );\n },\n async convertToMessage(\n intercom_conversation: IntercomConversation & { clientId?: string },\n submitter: IntercomUserShort,\n intercom_token: {\n integration_access_token: string;\n },\n intercom_workspace_id: string,\n context: AuthContext\n ) {\n const sub_messages = getConversationMessages(intercom_conversation);\n const created_persons = await createUniquePersons(\n intercom_conversation,\n submitter,\n intercom_token,\n context\n );\n const created_submitter = created_persons.find(\n pers => pers.intercom_id === submitter.id\n );\n const created_requester = created_persons.find(\n pers => pers.intercom_id === intercom_conversation.user.id\n );\n if (!created_submitter)\n throw new Error(\n \"Error in intercom message creation: submitter cannot be empty\"\n );\n\n const tags =\n oc(intercom_conversation).tags.type() === \"tag.list\"\n ? oc(intercom_conversation)\n .tags.tags([])\n .map(tag => ({\n name: tag.name\n }))\n : [];\n\n const labels = await messageLabelService.upsertManyMessageLabels(\n tags,\n context\n );\n\n return messageService.createMessage(\n {\n clientId: oc(intercom_conversation).clientId() || undefined,\n recipient_address: \"Intercom\",\n title: intercom_conversation.conversation_message.subject,\n content: intercom_conversation.conversation_message.body,\n // tags:\n // oc(intercom_conversation).tags.type() === \"tag.list\" &&\n // oc(intercom_conversation).tags.tags([]).length\n // ? {\n // set: intercom_conversation.tags.tags.map(tag => ({\n // name: tag.name\n // }))\n // }\n // : undefined,\n labels: (labels || []).length\n ? {\n connect: (labels || []).map(l => ({ id: l.id }))\n }\n : undefined,\n sub_messages: {\n create: sub_messages.length\n ? await Promise.all(\n sub_messages.map(sub =>\n convertToSubmessage(sub, created_persons)\n )\n )\n : []\n },\n channel: \"INTERCOM\",\n integration_id: intercom_conversation.id.toString(),\n integration_url: `https://app.intercom.io/a/apps/${intercom_workspace_id}/inbox/all/conversations/${intercom_conversation.id.toString()}`,\n requester: {\n connect: {\n id: oc(created_requester).id(created_submitter.id)\n }\n },\n submitter: {\n connect: {\n id: created_submitter.id\n }\n }\n },\n context\n );\n },\n async updateMessage(\n intercom_conversation: IntercomConversation,\n harvestr_message: {\n id: string;\n last_submessage_clientId?: string;\n updated: boolean;\n },\n intercom_token: { integration_access_token: string },\n context: AuthContext\n ) {\n const sub_messages = extractSubMessages(intercom_conversation);\n const created_persons = await createUniquePersons(\n intercom_conversation,\n null,\n intercom_token,\n context\n );\n console.log(\"PERSONS TADATATA\", JSON.stringify(created_persons));\n console.log(\"UPDATE\", JSON.stringify(sub_messages));\n return messageService.updateMessage(\n { id: harvestr_message.id },\n {\n updated: true,\n submessageBeforeUpdateId:\n harvestr_message.last_submessage_clientId &&\n !harvestr_message.updated\n ? harvestr_message.last_submessage_clientId\n : undefined,\n sub_messages: {\n create: sub_messages.length\n ? await Promise.all(\n sub_messages.map(sub =>\n convertToSubmessage(sub, created_persons)\n )\n )\n : []\n }\n },\n context\n );\n },\n async legacyConvertToMessage(\n intercom_data: IntercomData,\n submitter: IntercomUserShort,\n intercom_token: {\n integration_access_token: string;\n },\n context: AuthContext\n ) {\n const intercom_conversation = await intercomApiService.getConversation(\n intercom_data.item.id.toString(),\n {\n integration_access_token: oc(\n intercom_token\n ).integration_access_token(\"\")\n }\n );\n const sub_messages = getConversationMessages(intercom_conversation);\n const created_persons = await createUniquePersons(\n intercom_conversation,\n submitter,\n intercom_token,\n context\n );\n const created_submitter = created_persons.find(\n pers => pers.intercom_id === submitter.id\n );\n const created_requester = created_persons.find(\n pers => pers.intercom_id === intercom_conversation.user.id\n );\n if (!created_submitter)\n throw new Error(\n \"Error in intercom message creation: submitter cannot be empty\"\n );\n\n const tags =\n oc(intercom_conversation).tags.type() === \"tag.list\"\n ? oc(intercom_conversation)\n .tags.tags([])\n .map(tag => ({\n name: tag.name\n }))\n : [];\n\n const labels = await messageLabelService.upsertManyMessageLabels(\n tags,\n context\n );\n\n return messageService.createMessage(\n {\n recipient_address: \"Intercom\",\n title: oc(intercom_conversation).conversation_message.subject()\n ? intercom_conversation.conversation_message.subject\n : \"Intercom conversation\",\n\n content: intercom_conversation.conversation_message.body,\n // tags:\n // oc(intercom_conversation).tags.type() === \"tag.list\" &&\n // oc(intercom_conversation).tags.tags([]).length\n // ? {\n // set: intercom_conversation.tags.tags.map(tag => ({\n // name: tag.name\n // }))\n // }\n // : undefined,\n labels: (labels || []).length\n ? {\n connect: (labels || []).map(l => ({ id: l.id }))\n }\n : undefined,\n sub_messages: {\n create: sub_messages.length\n ? await Promise.all(\n sub_messages.map(sub =>\n convertToSubmessage(sub, created_persons)\n )\n )\n : []\n },\n channel: \"INTERCOM\",\n integration_id: intercom_data.item.id.toString(),\n integration_url: oc(\n intercom_data\n ).item.links.conversation_web(),\n requester: {\n connect: {\n id: oc(created_requester).id(created_submitter.id)\n }\n },\n submitter: {\n connect: {\n id: created_submitter.id\n }\n }\n },\n context\n );\n }\n};\n","import { apiTokenService, AuthContext } from \"@harvestr-api/common\";\nimport { logger } from \"@harvestr-api/utils\";\nimport base64url from \"base64url\";\nimport { Request, Response } from \"express\";\nconst passport = require(\"passport\");\n\nimport { intercomApiService } from \"./intercom-api.service\";\n\nconst IntercomStrategy = require(\"passport-intercom\").Strategy;\n\nconst intercom_legacy = passport.use(\n new IntercomStrategy(\n {\n clientID: process.env.INTERCOM_LEGACY_OAUTH_CLIENT_ID,\n clientSecret: process.env.INTERCOM_LEGACY_OAUTH_CLIENT_SECRET,\n },\n (accessToken, refreshToken, profile, done) => {\n done();\n }\n )\n);\n\nexport const intercomLegacyOauthService = {\n async handleLegacyIntercomOauth(req: Request, res: Response) {\n try {\n const project_id = req.query.id;\n intercom_legacy.authenticate(\"intercom\", <any>{\n state: base64url(JSON.stringify({ id: project_id })),\n })(req, res);\n } catch (error) {\n logger.error(error);\n }\n },\n\n async handleLegacyIntercomOauthResponse(req: Request, res: Response) {\n try {\n const state = req.query.state as string;\n const response = JSON.parse(base64url.decode(state));\n const project_id = response.id;\n const intercom_code = req.query.code as string;\n const context: AuthContext = {\n type: \"INTEGRATION_INTERCOM\",\n project_id,\n };\n const INTERCOM_LEGACY_OAUTH_CLIENT_ID =\n process.env.INTERCOM_LEGACY_OAUTH_CLIENT_ID || \"\";\n const INTERCOM_LEGACY_OAUTH_CLIENT_SECRET =\n process.env.INTERCOM_LEGACY_OAUTH_CLIENT_SECRET || \"\";\n const intercom_access_token = await intercomApiService.getAccessToken(\n {\n INTERCOM_OAUTH_CLIENT_ID: INTERCOM_LEGACY_OAUTH_CLIENT_ID,\n INTERCOM_OAUTH_CLIENT_SECRET: INTERCOM_LEGACY_OAUTH_CLIENT_SECRET,\n intercom_code,\n }\n );\n logger.info(\"creating the webhook on client's intercom app\");\n // create webhook\n const domain: string = process.env.HARVESTR_API_URL || \"google.com\";\n const webhook_response = await intercomApiService.legacyCreateWebhookSubscription(\n {\n service_type: \"web\",\n url: domain + \"/intercom/note/\" + context.project_id,\n topics: [\"conversation.admin.noted\"],\n },\n intercom_access_token\n );\n if (!webhook_response) throw new Error(\"Webhook creation failed\");\n logger.info(\n `webhook created in intercom with id ${webhook_response.id}`\n );\n await apiTokenService.upsertApiToken(\n { source: \"INTERCOM_MENTION\" },\n {\n source: \"INTERCOM_MENTION\",\n integration_access_token: intercom_access_token,\n integration_webhook_id: webhook_response.id,\n integration_workspace_id: webhook_response.app_id,\n options: {\n create: {\n notify_linked: true,\n notify_state: true,\n sync_organizations: true,\n },\n },\n },\n {\n source: \"INTERCOM_MENTION\",\n integration_access_token: intercom_access_token,\n integration_webhook_id: webhook_response.id,\n integration_workspace_id: webhook_response.app_id,\n options: {\n create: {\n notify_linked: true,\n notify_state: true,\n sync_organizations: true,\n },\n },\n },\n context\n );\n res.status(200).send(\n \"<h3>Success! Redirecting...</h3><h4>You can close this window.</h4>\"\n );\n } catch (error) {\n logger.error(error);\n res.status(400).send(error);\n }\n },\n};\n","import { apiTokenService, AuthContext } from \"@harvestr-api/common\";\nimport { logger } from \"@harvestr-api/utils\";\nimport base64url from \"base64url\";\nimport { Request, Response } from \"express\";\nconst passport = require(\"passport\");\n\nimport { intercomApiService } from \"./intercom-api.service\";\n\nconst IntercomStrategy = require(\"passport-intercom\").Strategy;\n\nconst intercom = passport.use(\n new IntercomStrategy(\n {\n clientID: process.env.INTERCOM_OAUTH_CLIENT_ID,\n clientSecret: process.env.INTERCOM_OAUTH_CLIENT_SECRET,\n },\n (accessToken, refreshToken, profile, done) => {\n done();\n }\n )\n);\n\nexport const intercomOauthService = {\n async handleIntercomOauth(req: Request, res: Response) {\n try {\n const project_id = req.query.id;\n intercom.authenticate(\"intercom\", <any>{\n state: base64url(JSON.stringify({ id: project_id })),\n })(req, res);\n } catch (error) {\n logger.error(error);\n }\n },\n\n async handleIntercomOauthResponse(req: Request, res: Response) {\n try {\n const state = req.query.state as string;\n const response = JSON.parse(base64url.decode(state));\n const project_id = response.id;\n const intercom_code = req.query.code as string;\n const context: AuthContext = {\n type: \"INTEGRATION_INTERCOM\",\n project_id,\n };\n const INTERCOM_OAUTH_CLIENT_ID =\n process.env.INTERCOM_OAUTH_CLIENT_ID || \"\";\n const INTERCOM_OAUTH_CLIENT_SECRET =\n process.env.INTERCOM_OAUTH_CLIENT_SECRET || \"\";\n const intercom_access_token = await intercomApiService.getAccessToken(\n {\n INTERCOM_OAUTH_CLIENT_ID,\n INTERCOM_OAUTH_CLIENT_SECRET,\n intercom_code,\n }\n );\n const me = await intercomApiService.getMe({\n integration_access_token: intercom_access_token,\n });\n await apiTokenService\n .upsertApiToken(\n { source: \"INTERCOM_WIDGET\" },\n {\n source: \"INTERCOM_WIDGET\",\n integration_access_token: intercom_access_token,\n integration_workspace_id: me.app_id,\n integration_trigger_id: me.id,\n options: {\n create: {\n notify_linked: true,\n notify_state: true,\n sync_organizations: true,\n },\n },\n },\n {\n source: \"INTERCOM_WIDGET\",\n integration_access_token: intercom_access_token,\n integration_workspace_id: me.app_id,\n integration_trigger_id: me.id,\n options: {\n create: {\n notify_linked: true,\n notify_state: true,\n sync_organizations: true,\n },\n },\n },\n context\n )\n .catch((error) => {\n logger.error(error);\n res.status(400).send(\n \"This Intercom account is already connected to another Harvestr account, please delete it to proceed.\"\n );\n return;\n });\n res.status(200).send(\n \"<h3>Success! Redirecting...</h3><h4>You can close this window.</h4>\"\n );\n } catch (error) {\n logger.error(error);\n res.status(400).send(error);\n }\n },\n};\n","module.exports = require(\"shortid\");","module.exports = require(\"graphql-tag\");","import { intercomUtilsService } from \"./intercom-utils.service\";\nimport { tokenIntercomService, AuthContext } from \"@harvestr-api/common\";\nimport { intercomService } from \"./intercom.service\";\nimport { toClientId } from \"@harvestr-api/utils\";\nimport { oc } from \"ts-optchain\";\nimport { gqlApiToken } from \"@harvestr-api/models\";\n\nconst mainCanvas = {\n canvas: {\n content: {\n components: [\n {\n type: \"text\",\n text: \"*Create new Feedback*\",\n align: \"left\",\n style: \"header\",\n },\n {\n type: \"button\",\n label: \"Send conversation to Harvestr\",\n style: \"secondary\",\n id: \"send-harvestr\",\n action: { type: \"submit\" },\n },\n ],\n },\n },\n};\n\nconst loginCanvas = {\n canvas: {\n content: {\n components: [\n {\n type: \"text\",\n text: \"You need to add a Harvestr account\",\n align: \"left\",\n style: \"muted\",\n },\n {\n type: \"text\",\n text:\n \"Configure your accounts in your [app settings](https://app.harvestr.io/settings/integrations/intercom)\",\n align: \"left\",\n style: \"muted\",\n },\n ],\n },\n },\n};\n\nconst conversationReadNotif = (data: {\n isRead: boolean;\n discovery_id: string;\n discoveries_length?: number;\n}) =>\n data.discoveries_length\n ? [\n // {\n // type: \"divider\"\n // },\n // {\n // type: \"button\",\n // label: \"View in Harvestr\",\n // style: \"link\",\n // id: \"view-in-harvestr\",\n // action: {\n // type: \"url\",\n // url: `${process.env.HARVESTR_CLIENT_URL}/messages/inbox/${data.discovery_id}`\n // }\n // }\n ]\n : [\n {\n type: \"divider\",\n },\n {\n type: \"text\",\n text: \"*Sent conversation info*\",\n style: \"header\",\n },\n {\n type: \"data-table\",\n items: [\n {\n type: \"field-value\",\n field: \"Status\",\n value: data.discoveries_length\n ? `Linked to ${data.discoveries_length} discover${\n data.discoveries_length === 1 ? \"y\" : \"ies\"\n }`\n : data.isRead\n ? `Conversation was read`\n : `Not read`,\n },\n ],\n },\n {\n type: \"spacer\",\n size: \"xs\",\n },\n {\n type: \"button\",\n label: \"View in Harvestr\",\n style: \"link\",\n id: \"view-in-harvestr\",\n action: {\n type: \"url\",\n url: `${process.env.HARVESTR_CLIENT_URL}/messages/inbox/${data.discovery_id}`,\n },\n },\n ];\n\nconst abstractCanvas = (\n clientId: string,\n isRead: boolean,\n linked_cards?: any[]\n) => {\n console.log(\"LINK CARDS: \", linked_cards);\n const discoveries_number = (linked_cards || []).length;\n const linked_discoveries_title = discoveries_number\n ? [\n // {\n // type: \"divider\",\n // bottom_margin: \"none\"\n // },\n {\n type: \"text\",\n text: `*Linked discoveries (${discoveries_number})*`,\n align: \"left\",\n style: \"header\",\n },\n ]\n : [];\n const allDiscoveries = (linked_cards || []).map((linked_card) =>\n intercomUtilsService.formatDiscoveryCanvas(\n linked_card.title,\n linked_card.url,\n linked_card.parent.title,\n linked_card.discoverystate.name,\n linked_card.feedback_number,\n linked_card.tags\n )\n );\n const discoveriesCanvas = discoveries_number ? allDiscoveries[0] : [];\n const discoveriesLeft_number =\n discoveries_number > 1 ? discoveries_number - 1 : 0;\n const discoveriesMore =\n discoveries_number > 1\n ? [\n {\n type: \"divider\",\n },\n {\n type: \"button\",\n id: \"load-more-discoveries\",\n label: `View all discoveries (${discoveriesLeft_number} more)`,\n style: \"link\",\n action: {\n type: \"submit\",\n },\n },\n ]\n : [];\n const canvas = {\n canvas: {\n content: {\n components: [\n ...conversationReadNotif({\n isRead,\n discovery_id: clientId,\n discoveries_length: (linked_cards || []).length,\n }),\n ...linked_discoveries_title,\n ...discoveriesCanvas,\n ...discoveriesMore,\n ],\n },\n stored_data: {\n message_id: clientId,\n discoveries: (<any>[]).concat(...allDiscoveries), //? flatten array\n },\n },\n };\n return canvas;\n};\n\nconst initCanvas = async (workspaceId: string, conversationId: string) => {\n let intercom_token: gqlApiToken | null = null;\n try {\n intercom_token = workspaceId\n ? ((await tokenIntercomService.getApiToken(\n workspaceId\n )) as gqlApiToken)\n : null;\n } catch (err) {\n console.log(\"invalid or no intercom token\");\n }\n if (!intercom_token) {\n return loginCanvas;\n }\n const context: AuthContext = {\n type: \"INTEGRATION_INTERCOM\",\n project_id: intercom_token._projectId || \"\",\n };\n // const integration_id = requestBody.conversation.id.toString();\n const message = await intercomService.getMessage(conversationId, context);\n const linked_cards: {\n id: string;\n title: string;\n url: string;\n feedback_number: number;\n }[] = [];\n if (message) {\n for (const chunk of oc(message).chunks([])) {\n if (oc(chunk).discovery()) {\n const discovery = chunk.discovery;\n if (!linked_cards.some((card) => card.id === discovery.id)) {\n linked_cards.push({\n ...discovery,\n url: `${\n process.env.client_domain || \"\"\n }/components/0/list/${toClientId(discovery).id}`,\n feedback_number: oc(discovery).chunks([]).length || 0,\n });\n }\n }\n }\n const recapCanvas = abstractCanvas(\n message.clientId || \"\",\n message.read,\n linked_cards\n );\n\n return recapCanvas;\n }\n\n return mainCanvas;\n};\n\nexport const intercomCanvasService = { conversationReadNotif, initCanvas };\n"],"sourceRoot":""}
\No newline at end of file