nubot-lite 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -5
- package/lib/api.mjs +6 -2
- package/lib/cloudflare.mjs +13 -12
- package/lib/commands/init.mjs +260 -251
- package/package.json +1 -1
- package/template/.claude/skills/nubot-lite/SKILL.md +7 -1
- package/template/panel/PANEL.md +1 -1
- package/template/panel/assets/AgendarDemoPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{AgentDatasetsPage-D8vQhRWO.js → AgentDatasetsPage-wLtBtSB2.js} +2 -2
- package/template/panel/assets/AgentKnowledgeGroupsPage-BGHNFj-e.js +1 -0
- package/template/panel/assets/AgentListPage-F3ja9_o_.js +1 -0
- package/template/panel/assets/AgentQaTrainingPage-CojiU8_W.js +1 -0
- package/template/panel/assets/AiAgentWhatsappPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/BlogPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/BlogPostPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/CalculadoraTiempoRespuestaPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{CampaignDetailPage-DFMctNEj.js → CampaignDetailPage-DUNnckvn.js} +1 -1
- package/template/panel/assets/CampaignsPage-CS60yZBd.js +1 -0
- package/template/panel/assets/ChannelSelector-C7R9zqrt.js +1 -0
- package/template/panel/assets/ChatbotParaWhatsappPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/ConfirmModal-B27OBQdm.js +1 -0
- package/template/panel/assets/ContactsPage-CvoDlFUN.js +14 -0
- package/template/panel/assets/CreateAgentPage-CbhikMY1.js +19 -0
- package/template/panel/assets/CreditLimitBanner-j72L7jgK.js +1 -0
- package/template/panel/assets/CrmParaWhatsappPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/DashboardPage-BGWkXY7W.js +1 -0
- package/template/panel/assets/{EmojiPicker-BToAe-MT.js → EmojiPicker-ByTMSXTj.js} +1 -1
- package/template/panel/assets/{EventTypesSettingsPage-DCedeQzM.js → EventTypesSettingsPage-CLpO1VBL.js} +1 -1
- package/template/panel/assets/GeneradorEnlacesPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/GeneradorQrWhatsappPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{GeneralSettingsPage-B04ozcHb.js → GeneralSettingsPage-CY-5aGgL.js} +1 -1
- package/template/panel/assets/GoogleCalendarManagePage-oX7DuErV.js +1 -0
- package/template/panel/assets/{InvitationAcceptancePage-BPgtBFl5.js → InvitationAcceptancePage-BYllrAYs.js} +1 -1
- package/template/panel/assets/IrAlSitioPublico-Bn_BvTp1.js +1 -0
- package/template/panel/assets/LiteAiUsagePage-Dzm8jBL2.js +1 -0
- package/template/panel/assets/{LiteSetupPage-42rgAdnG.js → LiteSetupPage-CMSAur_e.js} +1 -1
- package/template/panel/assets/MarkdownRenderer-C3TD9KYa.js +3 -0
- package/template/panel/assets/MediaProcessingService-CG2DdSyN.js +1 -0
- package/template/panel/assets/NewCampaignPage-BfSEd075.js +1 -0
- package/template/panel/assets/OrdersConfigPage-BAKKaX0L.js +1 -0
- package/template/panel/assets/OrdersPage-CXiPOCXP.js +1 -0
- package/template/panel/assets/{PasswordStrengthIndicator-HZK_oU0W.js → PasswordStrengthIndicator-4h-Y0s2r.js} +1 -1
- package/template/panel/assets/PlantillaDetailPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/PlantillasIndexPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/PrivacyPolicy-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{ProductManagementPage-DNM7DEgt.js → ProductManagementPage-CRkNTicv.js} +4 -4
- package/template/panel/assets/PublicFormPage-BxPxJ3Pq.js +1 -0
- package/template/panel/assets/QaForm-Px-cmakA.js +5 -0
- package/template/panel/assets/SelectPlanPage-Gyo5C1Hq.js +1 -0
- package/template/panel/assets/SignatureEditor-DIhmrXow.js +1 -0
- package/template/panel/assets/{TagSelector-ChoKzvjW.js → TagSelector-o6tVpRs9.js} +1 -1
- package/template/panel/assets/TagsSettingsPage-DT8MfW1H.js +2 -0
- package/template/panel/assets/TeamsPage-BuWuGxZo.js +1 -0
- package/template/panel/assets/WhatsappBusinessApiPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/WhatsappMultiagentePage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{account-D2ltXC_U.js → account-G3WXxisG.js} +1 -1
- package/template/panel/assets/{admin-lEgqZTsa.js → admin-CSMlOMR8.js} +1 -1
- package/template/panel/assets/{agent.service-BcAkMU7j.js → agent.service-BE2rJG_o.js} +1 -1
- package/template/panel/assets/{alert-dialog-D8P69s-m.js → alert-dialog-gzZZoAiu.js} +2 -2
- package/template/panel/assets/{alert-DI3GBLi1.js → alert-seLKo73M.js} +1 -1
- package/template/panel/assets/api-keys-BF33GS2N.js +1 -0
- package/template/panel/assets/{archive-LUe5bKi5.js → archive-CxUKRJwu.js} +1 -1
- package/template/panel/assets/{arrow-left-BeDdBs_Q.js → arrow-left-CI7mH7bD.js} +1 -1
- package/template/panel/assets/{arrow-up-BiBq8Pvx.js → arrow-up-DJzXCc8_.js} +1 -1
- package/template/panel/assets/{arrow-up-down-CaG2BONN.js → arrow-up-down-DkSCsCjR.js} +1 -1
- package/template/panel/assets/audit-slljESxh.js +1 -0
- package/template/panel/assets/{authService-Cbm8LdlJ.js → authService-CtvlzCDa.js} +1 -1
- package/template/panel/assets/{avatar-CILB1zwS.js → avatar-BXhSKQGY.js} +1 -1
- package/template/panel/assets/{billing-IVLNopU2.js → billing-Cy2XUBeY.js} +1 -1
- package/template/panel/assets/{brain-B9z7jZ7A.js → brain-BmrjUpsb.js} +1 -1
- package/template/panel/assets/{calendar-CIHhMjNy.js → calendar-Bu0aDtW1.js} +1 -1
- package/template/panel/assets/{calendar-days-BwJfOz8M.js → calendar-days-CXtOZxOF.js} +1 -1
- package/template/panel/assets/{card-DcKsxjXK.js → card-DdbmSh-v.js} +1 -1
- package/template/panel/assets/{checkbox-pcbjC0d3.js → checkbox-CuJh5AMO.js} +1 -1
- package/template/panel/assets/{chevrons-up-down-DC-BWTrj.js → chevrons-up-down-DNNdNhV8.js} +1 -1
- package/template/panel/assets/{circle-check-big-DzPo5zZX.js → circle-check-big-BOZQ_2Kv.js} +1 -1
- package/template/panel/assets/{circle-x-BwMKIs8b.js → circle-x-decmm7ip.js} +1 -1
- package/template/panel/assets/cloud-B3m0_VpL.js +1 -0
- package/template/panel/assets/{code-BMAyHFJe.js → code-C-UH-ZD-.js} +1 -1
- package/template/panel/assets/{cog-M7j64wa2.js → cog-BS-_-U4F.js} +1 -1
- package/template/panel/assets/{collapsible-B22t1J-V.js → collapsible-Ce_8EeFJ.js} +1 -1
- package/template/panel/assets/{command-COdSmSIB.js → command-aHRTWaYV.js} +1 -1
- package/template/panel/assets/connectionsService-BJg4S1e9.js +1 -0
- package/template/panel/assets/contactsApi-DI5dcMLo.js +1 -0
- package/template/panel/assets/creditErrors-DSbswjsG.js +1 -0
- package/template/panel/assets/{database-C1qvt3Py.js → database-Brb7Omak.js} +1 -1
- package/template/panel/assets/{datapath-C12uI_pT.js → datapath-CHeKabeh.js} +1 -1
- package/template/panel/assets/{datetime-BuZosCVk.js → datetime-D72Uxhjs.js} +1 -1
- package/template/panel/assets/{download-CiVQHPeB.js → download-CyfdxFCW.js} +1 -1
- package/template/panel/assets/{ellipsis-CMEJnUfK.js → ellipsis-GLu0u4ze.js} +1 -1
- package/template/panel/assets/{ellipsis-vertical-DTqbEYYp.js → ellipsis-vertical-CskGwbgN.js} +1 -1
- package/template/panel/assets/email-inbox-kyJ2qML5.js +1 -0
- package/template/panel/assets/es-BDgg6unH.js +1 -0
- package/template/panel/assets/external-link-w7K66ae2.js +1 -0
- package/template/panel/assets/{eye-HfQCUjxJ.js → eye-CR5C6hVv.js} +1 -1
- package/template/panel/assets/{eye-off-v1Z_lKS0.js → eye-off-CBiJXw4j.js} +1 -1
- package/template/panel/assets/facebook-D0SQMea2.js +1 -0
- package/template/panel/assets/{file-DMzjdlTL.js → file-CTZ8-xmL.js} +1 -1
- package/template/panel/assets/file-braces-54MsOnzo.js +1 -0
- package/template/panel/assets/file-spreadsheet-DpekIaV8.js +1 -0
- package/template/panel/assets/{folder-D0GKakGp.js → folder-DxTHNhQ_.js} +1 -1
- package/template/panel/assets/{folder-open-DQFc4qTJ.js → folder-open-BM4rA96e.js} +1 -1
- package/template/panel/assets/format-BG1mN6C0.js +1 -0
- package/template/panel/assets/{grip-vertical-FN-eTC2C.js → grip-vertical-CS-dU0tJ.js} +1 -1
- package/template/panel/assets/{hash-BoTE56iw.js → hash-ByrjK6gt.js} +1 -1
- package/template/panel/assets/{help-center-B1MAIBWA.js → help-center-fmvvoAkD.js} +1 -1
- package/template/panel/assets/{history-DhHayxUg.js → history-97D1GT_9.js} +1 -1
- package/template/panel/assets/house-CXew5LB-.js +1 -0
- package/template/panel/assets/{index-DsyZ_FlA.js → index-43NA2pdZ.js} +23 -23
- package/template/panel/assets/index-BG59-Kyv.js +6 -0
- package/template/panel/assets/{index-DUnioqCT.js → index-BGvtgHY3.js} +1 -1
- package/template/panel/assets/index-BL76lyPt.js +2 -0
- package/template/panel/assets/index-BUA9lP4J.js +1 -0
- package/template/panel/assets/index-Bfvq4Q3v.js +1 -0
- package/template/panel/assets/index-CK793Wzl.css +1 -0
- package/template/panel/assets/{index-BTxe6gLJ.js → index-ChrvveQm.js} +1 -1
- package/template/panel/assets/index-CoJIvJ6y.js +1 -0
- package/template/panel/assets/{index-CMEeV9dO.js → index-CsV1u-Y7.js} +2 -2
- package/template/panel/assets/{index-BiSc3WD9.js → index-DIxON2Dm.js} +1 -1
- package/template/panel/assets/index-DtoSJTyl.js +1 -0
- package/template/panel/assets/index-FBuxpbGF.js +36 -0
- package/template/panel/assets/index-YR5X3nd4.js +1 -0
- package/template/panel/assets/{instagram-CC7iYt7V.js → instagram-Bm17x-Fs.js} +1 -1
- package/template/panel/assets/interactiveLimits-C7Sx7s9W.js +1 -0
- package/template/panel/assets/landing-CEUFhLJ9.js +1 -0
- package/template/panel/assets/{layout-grid-Cm6hfBWZ.js → layout-grid-DN-t2Wjd.js} +1 -1
- package/template/panel/assets/{list-BKc6EXnV.js → list-B0uLKf1b.js} +1 -1
- package/template/panel/assets/{map-pin-CPmcofD3.js → map-pin-COYHwobx.js} +1 -1
- package/template/panel/assets/{maximize-2-WdbM7Kdx.js → maximize-2-SbmXBBYe.js} +1 -1
- package/template/panel/assets/mediaLimits-CAYdWqeQ.js +1 -0
- package/template/panel/assets/mediaValidation-Bg0xHQrv.js +1 -0
- package/template/panel/assets/message-circle-tNSzOeOW.js +1 -0
- package/template/panel/assets/{message-square-Dfn16oHc.js → message-square-B1_OirdW.js} +1 -1
- package/template/panel/assets/{meta-templates-C7yEjSOI.js → meta-templates-hhDdxBOR.js} +1 -1
- package/template/panel/assets/metadataSchemasApi-BmJko2eC.js +1 -0
- package/template/panel/assets/{mic-CT4vyzLZ.js → mic-ClFq9hMZ.js} +1 -1
- package/template/panel/assets/minus-vh4a51Mn.js +1 -0
- package/template/panel/assets/{music-Cu8AQMFp.js → music-CgtkroYi.js} +1 -1
- package/template/panel/assets/{page-components-o2TF52HV.js → page-components-DXOKtt_M.js} +1 -1
- package/template/panel/assets/{pages-Cj5Qd1QO.js → pages-BcYbyh_-.js} +1 -1
- package/template/panel/assets/{pages-B7digtXi.js → pages-BuibyrnC.js} +1 -1
- package/template/panel/assets/{pages-Dw7dvmaS.js → pages-CGXCBdff.js} +1 -1
- package/template/panel/assets/paperclip-DVRbzE7C.js +1 -0
- package/template/panel/assets/{pen-line-DLnhkIuw.js → pen-line-Cr0YFjAs.js} +1 -1
- package/template/panel/assets/{pencil-Cx8u1N8t.js → pencil-aqjc7AWb.js} +1 -1
- package/template/panel/assets/{popover-MyuU-yAK.js → popover-cWIhNmod.js} +1 -1
- package/template/panel/assets/{power-CdR2OkIX.js → power-CVFzhVJx.js} +1 -1
- package/template/panel/assets/{product.service-CRLZOQsr.js → product.service-FClit10f.js} +1 -1
- package/template/panel/assets/products.types-nZIsk2w8.js +1 -0
- package/template/panel/assets/proxy-CvX2KM2u.js +1 -0
- package/template/panel/assets/{save-Dua2yhWl.js → save-mwkHDnDL.js} +1 -1
- package/template/panel/assets/scroll-area-CSCo4HHB.js +1 -0
- package/template/panel/assets/{select-DlB_BbfM.js → select-DCY_lg9j.js} +1 -1
- package/template/panel/assets/{send-Dxmdupsl.js → send-DBQH77K9.js} +1 -1
- package/template/panel/assets/{separator-CPT3uVRM.js → separator-DznqP68l.js} +1 -1
- package/template/panel/assets/{settings-2-C-c8ECWW.js → settings-2-PhKPMrsj.js} +1 -1
- package/template/panel/assets/shield-alert-Fv3j9Wbv.js +1 -0
- package/template/panel/assets/{skeleton-B0zh8s_y.js → skeleton-CN6xlRXP.js} +1 -1
- package/template/panel/assets/{slider-CY71MXOW.js → slider-D0QB_Lme.js} +1 -1
- package/template/panel/assets/{square-BuGqLxJB.js → square-Dm5VC71z.js} +1 -1
- package/template/panel/assets/{square-pen-CJajoyrm.js → square-pen-Dbn7xmc-.js} +1 -1
- package/template/panel/assets/{star-Cuegk1GF.js → star-BMD3HmS6.js} +1 -1
- package/template/panel/assets/stat-card-W7s_-fHW.js +1 -0
- package/template/panel/assets/storage.api-C0ZJBoSz.js +20 -0
- package/template/panel/assets/{switch-ODBa0fCT.js → switch-C7XmAU1c.js} +1 -1
- package/template/panel/assets/{table-CvSELOPi.js → table-7NGq0kRw.js} +1 -1
- package/template/panel/assets/{tabs-DqXhuAr6.js → tabs-BGCKrmVw.js} +1 -1
- package/template/panel/assets/{tags-By_tlh_r.js → tags-HU2fuPFH.js} +1 -1
- package/template/panel/assets/{target-DEuCdeUI.js → target-CG_g4_Fj.js} +1 -1
- package/template/panel/assets/{textarea-BYtcLsMD.js → textarea-B1anutjq.js} +1 -1
- package/template/panel/assets/{ticket-CWba7G1i.js → ticket-CHs1Xojr.js} +1 -1
- package/template/panel/assets/{trash-2-Du2vmQCH.js → trash-2-D_kmHMwn.js} +1 -1
- package/template/panel/assets/{trending-up-Ba4HSvuW.js → trending-up-BnHeLWFs.js} +1 -1
- package/template/panel/assets/{upload-C7TwpdyA.js → upload-CQg4_W5r.js} +1 -1
- package/template/panel/assets/{useAiAgentsQuery-Bm6aRHKj.js → useAiAgentsQuery-CXo6TmU6.js} +1 -1
- package/template/panel/assets/useFunnelStats-Bk8wTET5.js +1 -0
- package/template/panel/assets/useFunnelsQuery-vDrahaDr.js +1 -0
- package/template/panel/assets/{useInfiniteQuery-BXUM1Z9V.js → useInfiniteQuery-D0sFT2K2.js} +1 -1
- package/template/panel/assets/{useMutation-a5tIBvQY.js → useMutation-0ypmz8SO.js} +1 -1
- package/template/panel/assets/useOrgSyncedFetch-FSgwRhpR.js +1 -0
- package/template/panel/assets/usePipelineBoardQuery-BysscZXI.js +9 -0
- package/template/panel/assets/{useUploadConfig-BuiF0X-3.js → useUploadConfig-CvVmSc6S.js} +1 -1
- package/template/panel/assets/{user-DwCALzIG.js → user-l48WDfDH.js} +1 -1
- package/template/panel/assets/{user-plus-BiUjcHil.js → user-plus-CWaaUP-O.js} +1 -1
- package/template/panel/assets/{video-VfwKgB6z.js → video-CILE66CA.js} +1 -1
- package/template/panel/assets/{volume-2-C5DMdOVq.js → volume-2-DfFqN0dw.js} +1 -1
- package/template/panel/assets/wrench-Dcbk4scY.js +1 -0
- package/template/panel/index.html +2 -2
- package/template/panel/version.json +2 -2
- package/template/worker/migrations/0006_ai_usage.sql +33 -0
- package/template/worker/migrations/0007_channels.sql +18 -0
- package/template/worker/src/agent/pricing.ts +37 -0
- package/template/worker/src/agent/prompt.ts +137 -134
- package/template/worker/src/agent/run.ts +350 -243
- package/template/worker/src/agent/sandbox.ts +2 -2
- package/template/worker/src/agent/tools.ts +463 -463
- package/template/worker/src/channels/accounts.ts +177 -0
- package/template/worker/src/channels/zernio.ts +161 -148
- package/template/worker/src/inbox/contacts.ts +2 -0
- package/template/worker/src/inbox/store.ts +199 -187
- package/template/worker/src/index.ts +2 -0
- package/template/worker/src/nubot/account.ts +163 -178
- package/template/worker/src/nubot/ai-usage.ts +197 -0
- package/template/worker/src/nubot/channels.ts +159 -0
- package/template/worker/src/nubot/contacts.ts +387 -386
- package/template/worker/src/nubot/funnels.ts +672 -670
- package/template/worker/src/nubot/inbox.ts +623 -616
- package/template/worker/src/nubot/index.ts +127 -122
- package/template/worker/src/nubot/mappers.ts +12 -5
- package/template/worker/src/routes/channels.ts +13 -0
- package/template/worker/src/routes/system.ts +110 -100
- package/template/worker/src/webhooks/zernio.ts +154 -125
- package/template/panel/assets/AgendarDemoPage-DOiS40FL.js +0 -1
- package/template/panel/assets/AgentKnowledgeGroupsPage-DEPS1lsk.js +0 -1
- package/template/panel/assets/AgentListPage-DqY9rze5.js +0 -1
- package/template/panel/assets/AgentQaTrainingPage-Ecis7xoc.js +0 -1
- package/template/panel/assets/AiAgentWhatsappPage-DOiS40FL.js +0 -1
- package/template/panel/assets/AiMetricsPage-DEPS1lsk.js +0 -1
- package/template/panel/assets/BlogPage-DOiS40FL.js +0 -1
- package/template/panel/assets/BlogPostPage-DOiS40FL.js +0 -1
- package/template/panel/assets/CalculadoraTiempoRespuestaPage-DOiS40FL.js +0 -1
- package/template/panel/assets/CampaignsPage-CLRaXGlj.js +0 -1
- package/template/panel/assets/ChannelSelector-q9tTirNo.js +0 -1
- package/template/panel/assets/ChatbotParaWhatsappPage-DOiS40FL.js +0 -1
- package/template/panel/assets/ConfirmModal-W7VUI3Z_.js +0 -1
- package/template/panel/assets/ContactsPage-CsOFsOPw.js +0 -14
- package/template/panel/assets/CreateAgentPage-Ifxx6_UX.js +0 -19
- package/template/panel/assets/CreditLimitBanner-J49rSVEn.js +0 -1
- package/template/panel/assets/CrmParaWhatsappPage-DOiS40FL.js +0 -1
- package/template/panel/assets/DashboardPage-3Viy83dd.js +0 -1
- package/template/panel/assets/GeneradorEnlacesPage-DOiS40FL.js +0 -1
- package/template/panel/assets/GeneradorQrWhatsappPage-DOiS40FL.js +0 -1
- package/template/panel/assets/IrAlSitioPublico-DOiS40FL.js +0 -1
- package/template/panel/assets/MediaProcessingService-glHGiE_o.js +0 -1
- package/template/panel/assets/NewCampaignPage-Cw99m3W8.js +0 -1
- package/template/panel/assets/OrdersConfigPage-B6BfM3lf.js +0 -1
- package/template/panel/assets/OrdersPage-Du7CJjty.js +0 -1
- package/template/panel/assets/PlantillaDetailPage-DOiS40FL.js +0 -1
- package/template/panel/assets/PlantillasIndexPage-DOiS40FL.js +0 -1
- package/template/panel/assets/PrivacyPolicy-DOiS40FL.js +0 -1
- package/template/panel/assets/PublicFormPage-DDb4OXEM.js +0 -1
- package/template/panel/assets/QaForm-BDboHNKo.js +0 -5
- package/template/panel/assets/SelectPlanPage-DALaf8E5.js +0 -1
- package/template/panel/assets/TagsSettingsPage-DYCKveQq.js +0 -2
- package/template/panel/assets/TeamsPage-DPUcRdlh.js +0 -1
- package/template/panel/assets/WhatsappBusinessApiPage-DOiS40FL.js +0 -1
- package/template/panel/assets/WhatsappMultiagentePage-DOiS40FL.js +0 -1
- package/template/panel/assets/api-keys-B0UQNR5E.js +0 -1
- package/template/panel/assets/audit-BrdHcTNl.js +0 -1
- package/template/panel/assets/connections-Dqwd01UI.js +0 -1
- package/template/panel/assets/connectionsService-BsJf8pFz.js +0 -3
- package/template/panel/assets/contactsApi-B851NME_.js +0 -1
- package/template/panel/assets/creditErrors-CrpkwwUI.js +0 -1
- package/template/panel/assets/email-inbox-LbGeQCty.js +0 -1
- package/template/panel/assets/es-BG480iA5.js +0 -1
- package/template/panel/assets/facebook-RxMBweMB.js +0 -1
- package/template/panel/assets/index-B183O0S5.js +0 -1
- package/template/panel/assets/index-BJCPaymI.css +0 -1
- package/template/panel/assets/index-BtxJGfLL.js +0 -6
- package/template/panel/assets/index-Bz-ixwph.js +0 -1
- package/template/panel/assets/index-CjQSv8hF.js +0 -2
- package/template/panel/assets/index-D3vkHHjD.js +0 -9
- package/template/panel/assets/index-D4WhIkMN.js +0 -1
- package/template/panel/assets/interactiveLimits-CfLJ1O4_.js +0 -1
- package/template/panel/assets/landing-If3oVsS0.js +0 -1
- package/template/panel/assets/mediaValidation-BR-ZOj5w.js +0 -1
- package/template/panel/assets/minus-CyVEzdqL.js +0 -1
- package/template/panel/assets/products.types-46xSxBS8.js +0 -1
- package/template/panel/assets/scroll-area-CavEOIyz.js +0 -1
- package/template/panel/assets/shield-alert-04pSYngI.js +0 -1
- package/template/panel/assets/storage.api-CFU3KJNp.js +0 -20
- package/template/panel/assets/useFunnelStats-tvjpmWIC.js +0 -1
|
@@ -1,386 +1,387 @@
|
|
|
1
|
-
// Contactos, etiquetas y respuestas rápidas con las formas del panel.
|
|
2
|
-
|
|
3
|
-
import { Hono, type Context } from "hono";
|
|
4
|
-
import { notifyPanel } from "../do/inbox-hub";
|
|
5
|
-
import { deleteContact } from "../inbox/contacts";
|
|
6
|
-
import { newId } from "../inbox/store";
|
|
7
|
-
import type { NubotEnv } from "./index";
|
|
8
|
-
import { toContact, ticketStatus, type ContactRecord } from "./mappers";
|
|
9
|
-
|
|
10
|
-
type Ctx = Context<NubotEnv>;
|
|
11
|
-
|
|
12
|
-
export const contacts = new Hono<NubotEnv>();
|
|
13
|
-
|
|
14
|
-
const CONTACT_COLUMNS = "id, name, phone, metadata, created_at, updated_at";
|
|
15
|
-
const notFound = (c: Ctx) => c.json({ message: "Ese contacto no existe.", statusCode: 404 }, 404);
|
|
16
|
-
const onlyAdmin = (c: Ctx) =>
|
|
17
|
-
c.get("user").role === "admin" ? null : c.json({ message: "Solo un administrador puede hacer esto.", statusCode: 403 }, 403);
|
|
18
|
-
|
|
19
|
-
interface TagRecord {
|
|
20
|
-
id: string;
|
|
21
|
-
name: string;
|
|
22
|
-
color: string;
|
|
23
|
-
description: string | null;
|
|
24
|
-
position: number;
|
|
25
|
-
created_at: number;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const TAG_COLUMNS = "t.id, t.name, t.color, t.description, t.position, t.created_at";
|
|
29
|
-
|
|
30
|
-
const toTag = (t: TagRecord) => ({
|
|
31
|
-
id: t.id,
|
|
32
|
-
name: t.name,
|
|
33
|
-
description: t.description,
|
|
34
|
-
color: t.color,
|
|
35
|
-
folderId: null,
|
|
36
|
-
position: t.position,
|
|
37
|
-
aiMetadata: null,
|
|
38
|
-
createdAt: new Date(t.created_at).toISOString(),
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
async function tagsOf(c: Ctx, contactId: string) {
|
|
42
|
-
const { results } = await c.env.DB.prepare(
|
|
43
|
-
`SELECT ${TAG_COLUMNS} FROM contact_tags ct JOIN tags t ON t.id = ct.tag_id WHERE ct.contact_id = ? ORDER BY t.position, t.name`,
|
|
44
|
-
)
|
|
45
|
-
.bind(contactId)
|
|
46
|
-
.all<TagRecord>();
|
|
47
|
-
return results.map(toTag);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
async function loadContact(c: Ctx, id: string) {
|
|
51
|
-
return c.env.DB.prepare(`SELECT ${CONTACT_COLUMNS} FROM contacts WHERE id = ?`).bind(id).first<ContactRecord>();
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** Avisa a las conversaciones del contacto que cambió su nombre, sus datos o sus etiquetas. */
|
|
55
|
-
async function contactChanged(c: Ctx, contactId: string) {
|
|
56
|
-
const { results } = await c.env.DB.prepare("SELECT id FROM conversations WHERE contact_id = ?").bind(contactId).all<{ id: string }>();
|
|
57
|
-
c.executionCtx.waitUntil(
|
|
58
|
-
Promise.all(results.map((r) => notifyPanel(c.env, { type: "contact:update", conversationId: r.id }))),
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// ---------- Contactos ----------
|
|
63
|
-
|
|
64
|
-
contacts.get("/contacts", async (c) => {
|
|
65
|
-
const page = Math.max(1, Number(c.req.query("page")) || 1);
|
|
66
|
-
const limit = Math.min(100, Math.max(1, Number(c.req.query("limit")) || 20));
|
|
67
|
-
const where: string[] = [];
|
|
68
|
-
const binds: unknown[] = [];
|
|
69
|
-
const search = c.req.query("search")?.trim();
|
|
70
|
-
if (search) {
|
|
71
|
-
where.push("(ct.name LIKE ? OR ct.phone LIKE ? OR ct.metadata LIKE ?)");
|
|
72
|
-
binds.push(`%${search}%`, `%${search}%`, `%${search}%`);
|
|
73
|
-
}
|
|
74
|
-
const tagIds = (c.req.query("tagIds") ?? "").split(",").filter(Boolean);
|
|
75
|
-
if (tagIds.length) {
|
|
76
|
-
where.push(`ct.id IN (SELECT contact_id FROM contact_tags WHERE tag_id IN (${tagIds.map(() => "?").join(", ")}))`);
|
|
77
|
-
binds.push(...tagIds);
|
|
78
|
-
}
|
|
79
|
-
if (c.req.query("untagged") === "true") where.push("ct.id NOT IN (SELECT contact_id FROM contact_tags)");
|
|
80
|
-
if (c.req.query("withoutPhone") === "true") where.push("(ct.phone IS NULL OR ct.phone = '')");
|
|
81
|
-
if (c.req.query("hasActiveTickets") === "true") {
|
|
82
|
-
where.push("ct.id IN (SELECT contact_id FROM conversations WHERE status != 'closed')");
|
|
83
|
-
}
|
|
84
|
-
const from = Date.parse(c.req.query("startDate") ?? "");
|
|
85
|
-
if (Number.isFinite(from)) {
|
|
86
|
-
where.push("ct.created_at >= ?");
|
|
87
|
-
binds.push(from);
|
|
88
|
-
}
|
|
89
|
-
const to = Date.parse(c.req.query("endDate") ?? "");
|
|
90
|
-
if (Number.isFinite(to)) {
|
|
91
|
-
where.push("ct.created_at <= ?");
|
|
92
|
-
binds.push(to);
|
|
93
|
-
}
|
|
94
|
-
const sortColumn = { name: "ct.name", createdAt: "ct.created_at", updatedAt: "ct.updated_at", lastSeenAt: "ct.updated_at" }[
|
|
95
|
-
c.req.query("sortBy") ?? "createdAt"
|
|
96
|
-
] ?? "ct.created_at";
|
|
97
|
-
const order = c.req.query("sortOrder") === "ASC" ? "ASC" : "DESC";
|
|
98
|
-
const whereSql = where.length ? `WHERE ${where.join(" AND ")}` : "";
|
|
99
|
-
const [rows, count] = await c.env.DB.batch([
|
|
100
|
-
c.env.DB.prepare(
|
|
101
|
-
`SELECT ct.id, ct.name, ct.phone, ct.metadata, ct.created_at, ct.updated_at,
|
|
102
|
-
(SELECT id FROM conversations WHERE contact_id = ct.id ORDER BY updated_at DESC LIMIT 1) AS last_ticket_id,
|
|
103
|
-
EXISTS (SELECT 1 FROM conversations WHERE contact_id = ct.id AND status != 'closed') AS active
|
|
104
|
-
FROM contacts ct ${whereSql} ORDER BY ${sortColumn} ${order}, ct.id LIMIT ? OFFSET ?`,
|
|
105
|
-
).bind(...binds, limit, (page - 1) * limit),
|
|
106
|
-
c.env.DB.prepare(`SELECT COUNT(*) AS n FROM contacts ct ${whereSql}`).bind(...binds),
|
|
107
|
-
]);
|
|
108
|
-
const list = rows.results as (ContactRecord & { last_ticket_id: string | null; active: number })[];
|
|
109
|
-
const total = (count.results[0] as { n: number }).n;
|
|
110
|
-
const data = await Promise.all(
|
|
111
|
-
list.map(async (r) => ({
|
|
112
|
-
...toContact(r),
|
|
113
|
-
phone: r.phone ?? "",
|
|
114
|
-
tags: await tagsOf(c, r.id),
|
|
115
|
-
lastTicketId: r.last_ticket_id ?? undefined,
|
|
116
|
-
hasActiveTickets: r.active === 1,
|
|
117
|
-
})),
|
|
118
|
-
);
|
|
119
|
-
return c.json({ data, total, page, pageSize: limit, hasMore: page * limit < total });
|
|
120
|
-
});
|
|
121
|
-
|
|
122
|
-
contacts.get("/contacts/stats", async (c) => {
|
|
123
|
-
const row = await c.env.DB.prepare(
|
|
124
|
-
`SELECT COUNT(*) AS total,
|
|
125
|
-
COALESCE(SUM(CASE WHEN metadata LIKE '%"correo"%' THEN 1 ELSE 0 END), 0) AS withEmail,
|
|
126
|
-
COALESCE(SUM(CASE WHEN phone IS NOT NULL AND phone != '' THEN 1 ELSE 0 END), 0) AS withPhone,
|
|
127
|
-
(SELECT COUNT(DISTINCT contact_id) FROM contact_tags) AS labeled
|
|
128
|
-
FROM contacts`,
|
|
129
|
-
).first();
|
|
130
|
-
return c.json(row);
|
|
131
|
-
});
|
|
132
|
-
|
|
133
|
-
/** Cada contacto de WhatsApp es único por su número: en Lite no hay duplicados que unir. */
|
|
134
|
-
contacts.get("/contacts/duplicates", (c) => c.json({ hasResults: false, byPhone: [], byEmail: [], byFuzzy: [], meta: null }));
|
|
135
|
-
|
|
136
|
-
contacts.post("/contacts", async (c) => {
|
|
137
|
-
const body = await c.req.json<{ name?: string; phone?: string; email?: string }>();
|
|
138
|
-
const name = body.name?.trim();
|
|
139
|
-
const phone = body.phone?.replace(/[^\d+]/g, "") || null;
|
|
140
|
-
if (!name) return c.json({ message: "Escribe el nombre del contacto.", statusCode: 400 }, 400);
|
|
141
|
-
if (!phone) return c.json({ message: "Escribe el número de WhatsApp del contacto.", statusCode: 400 }, 400);
|
|
142
|
-
const digits = phone.replace(/\D/g, "");
|
|
143
|
-
const exists = await c.env.DB.prepare("SELECT 1 FROM contacts WHERE external_id = ? OR REPLACE(phone, '+', '') = ?")
|
|
144
|
-
.bind(digits, digits)
|
|
145
|
-
.first();
|
|
146
|
-
if (exists) return c.json({ message: "Ya hay un contacto con ese número.", statusCode: 409 }, 409);
|
|
147
|
-
const now = Date.now();
|
|
148
|
-
const metadata = body.email?.trim() ? { correo: body.email.trim() } : {};
|
|
149
|
-
const contact: ContactRecord = { id: newId(), name, phone: phone.startsWith("+") ? phone : `+${phone}`, metadata: JSON.stringify(metadata), created_at: now, updated_at: now };
|
|
150
|
-
await c.env.DB.prepare("INSERT INTO contacts (id, external_id, phone, name, metadata, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
151
|
-
.bind(contact.id, digits, contact.phone, name, contact.metadata, now, now)
|
|
152
|
-
.run();
|
|
153
|
-
return c.json({ ...toContact(contact), tags: [] }, 201);
|
|
154
|
-
});
|
|
155
|
-
|
|
156
|
-
contacts.post("/contacts/bulk/delete", async (c) => {
|
|
157
|
-
const denied = onlyAdmin(c);
|
|
158
|
-
if (denied) return denied;
|
|
159
|
-
const { ids } = await c.req.json<{ ids?: string[] }>();
|
|
160
|
-
for (const id of ids ?? []) await deleteContact(c.env, id);
|
|
161
|
-
c.executionCtx.waitUntil(notifyPanel(c.env, { type: "contact:delete" }));
|
|
162
|
-
return c.json({ count: ids?.length ?? 0 });
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
contacts.post("/contacts/bulk/tags", async (c) => {
|
|
166
|
-
const { ids, tagIds } = await c.req.json<{ ids?: string[]; tagIds?: string[] }>();
|
|
167
|
-
const now = Date.now();
|
|
168
|
-
const pairs = (ids ?? []).flatMap((id) => (tagIds ?? []).map((tagId) => [id, tagId]));
|
|
169
|
-
if (pairs.length) {
|
|
170
|
-
await c.env.DB.batch(
|
|
171
|
-
pairs.map(([id, tagId]) =>
|
|
172
|
-
c.env.DB.prepare(
|
|
173
|
-
"INSERT OR IGNORE INTO contact_tags (contact_id, tag_id, created_at) SELECT ?, ?, ? WHERE EXISTS (SELECT 1 FROM tags WHERE id = ?)",
|
|
174
|
-
).bind(id, tagId, now, tagId),
|
|
175
|
-
),
|
|
176
|
-
);
|
|
177
|
-
}
|
|
178
|
-
return c.json({ count: ids?.length ?? 0 });
|
|
179
|
-
});
|
|
180
|
-
|
|
181
|
-
contacts.get("/contacts/:id", async (c) => {
|
|
182
|
-
const row = await loadContact(c, c.req.param("id"));
|
|
183
|
-
return row ? c.json({ ...toContact(row), tags: await tagsOf(c, row.id) }) : notFound(c);
|
|
184
|
-
});
|
|
185
|
-
|
|
186
|
-
contacts.get("/contacts/:id/full", async (c) => {
|
|
187
|
-
const row = await loadContact(c, c.req.param("id"));
|
|
188
|
-
if (!row) return notFound(c);
|
|
189
|
-
return c.json({
|
|
190
|
-
...toContact(row),
|
|
191
|
-
tags: await tagsOf(c, row.id),
|
|
192
|
-
isBlacklisted: false,
|
|
193
|
-
identities: row.phone ? [{ id: `${row.id}:phone`, type: "PHONE", identifierValue: row.phone, isBlacklisted: false }] : [],
|
|
194
|
-
});
|
|
195
|
-
});
|
|
196
|
-
|
|
197
|
-
contacts.patch("/contacts/:id", async (c) => {
|
|
198
|
-
const row = await loadContact(c, c.req.param("id"));
|
|
199
|
-
if (!row) return notFound(c);
|
|
200
|
-
const body = await c.req.json<{ name?: string; email?: string | null; metadata?: Record<string, unknown> }>();
|
|
201
|
-
const metadata = { ...(JSON.parse(row.metadata || "{}") as Record<string, unknown>), ...(body.metadata ?? {}) };
|
|
202
|
-
if (body.email !== undefined) {
|
|
203
|
-
if (body.email) metadata.correo = body.email.trim();
|
|
204
|
-
else delete metadata.correo;
|
|
205
|
-
}
|
|
206
|
-
const name = body.name?.trim() || row.name;
|
|
207
|
-
await c.env.DB.prepare("UPDATE contacts SET name = ?, metadata = ?, updated_at = ? WHERE id = ?")
|
|
208
|
-
.bind(name, JSON.stringify(metadata), Date.now(), row.id)
|
|
209
|
-
.run();
|
|
210
|
-
await contactChanged(c, row.id);
|
|
211
|
-
const saved = await loadContact(c, row.id);
|
|
212
|
-
return c.json({ ...toContact(saved!), tags: await tagsOf(c, row.id) });
|
|
213
|
-
});
|
|
214
|
-
|
|
215
|
-
/** Borra al contacto con todo su historial: lo que pide la ley de protección de datos cuando el cliente lo solicita. */
|
|
216
|
-
contacts.delete("/contacts/:id", async (c) => {
|
|
217
|
-
const denied = onlyAdmin(c);
|
|
218
|
-
if (denied) return denied;
|
|
219
|
-
const id = c.req.param("id");
|
|
220
|
-
if (!(await loadContact(c, id))) return notFound(c);
|
|
221
|
-
const { filesDeleted } = await deleteContact(c.env, id);
|
|
222
|
-
c.executionCtx.waitUntil(notifyPanel(c.env, { type: "contact:delete" }));
|
|
223
|
-
return c.json({ success: true, filesDeleted });
|
|
224
|
-
});
|
|
225
|
-
|
|
226
|
-
contacts.get("/contacts/:id/tags", async (c) => c.json(await tagsOf(c, c.req.param("id"))));
|
|
227
|
-
|
|
228
|
-
contacts.post("/contacts/:id/tags/:tagId", async (c) => {
|
|
229
|
-
const { id, tagId } = c.req.param();
|
|
230
|
-
const tag = await c.env.DB.prepare("SELECT 1 FROM tags WHERE id = ?").bind(tagId).first();
|
|
231
|
-
if (!tag || !(await loadContact(c, id))) return c.json({ message: "No encontramos el contacto o la etiqueta.", statusCode: 404 }, 404);
|
|
232
|
-
await c.env.DB.prepare("INSERT OR IGNORE INTO contact_tags (contact_id, tag_id, created_at) VALUES (?, ?, ?)")
|
|
233
|
-
.bind(id, tagId, Date.now())
|
|
234
|
-
.run();
|
|
235
|
-
await contactChanged(c, id);
|
|
236
|
-
return c.json({ success: true }, 201);
|
|
237
|
-
});
|
|
238
|
-
|
|
239
|
-
contacts.delete("/contacts/:id/tags/:tagId", async (c) => {
|
|
240
|
-
const { id, tagId } = c.req.param();
|
|
241
|
-
await c.env.DB.prepare("DELETE FROM contact_tags WHERE contact_id = ? AND tag_id = ?").bind(id, tagId).run();
|
|
242
|
-
await contactChanged(c, id);
|
|
243
|
-
return c.json({ success: true });
|
|
244
|
-
});
|
|
245
|
-
|
|
246
|
-
contacts.get("/contacts/:id/blacklist-status", async (c) => {
|
|
247
|
-
const row = await loadContact(c, c.req.param("id"));
|
|
248
|
-
return c.json({ isBlacklisted: false, phone: row?.phone ?? null });
|
|
249
|
-
});
|
|
250
|
-
|
|
251
|
-
contacts.get("/contacts/:id/metadata-history", (c) => c.json([]));
|
|
252
|
-
|
|
253
|
-
contacts.get("/contacts/:id/tickets", async (c) => {
|
|
254
|
-
const { results } = await c.env.DB.prepare(
|
|
255
|
-
`SELECT cv.id, cv.status, cv.assigned_user_id, cv.created_at, cv.updated_at,
|
|
256
|
-
(SELECT COUNT(*) FROM messages m WHERE m.conversation_id = cv.id) AS message_count
|
|
257
|
-
FROM conversations cv WHERE cv.contact_id = ? ORDER BY cv.updated_at DESC`,
|
|
258
|
-
)
|
|
259
|
-
.bind(c.req.param("id"))
|
|
260
|
-
.all<{ id: string; status: "ai" | "human" | "closed"; assigned_user_id: string | null; created_at: number; updated_at: number; message_count: number }>();
|
|
261
|
-
return c.json(
|
|
262
|
-
results.map((r) => ({
|
|
263
|
-
id: r.id,
|
|
264
|
-
status: ticketStatus(r),
|
|
265
|
-
channelType:
|
|
266
|
-
channelName:
|
|
267
|
-
createdAt: new Date(r.created_at).toISOString(),
|
|
268
|
-
updatedAt: new Date(r.updated_at).toISOString(),
|
|
269
|
-
messageCount: r.message_count,
|
|
270
|
-
})),
|
|
271
|
-
);
|
|
272
|
-
});
|
|
273
|
-
|
|
274
|
-
contacts.get("/contacts/:id/open-ticket", async (c) => {
|
|
275
|
-
const row = await c.env.DB.prepare(
|
|
276
|
-
"SELECT id, status, assigned_user_id FROM conversations WHERE contact_id = ? AND status != 'closed' ORDER BY updated_at DESC LIMIT 1",
|
|
277
|
-
)
|
|
278
|
-
.bind(c.req.param("id"))
|
|
279
|
-
.first<{ id: string; status: "ai" | "human" | "closed"; assigned_user_id: string | null }>();
|
|
280
|
-
if (!row) return c.json(null);
|
|
281
|
-
|
|
282
|
-
});
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
const
|
|
302
|
-
const
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
.
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
});
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
const
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
.
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
c.env.DB.prepare(`DELETE FROM
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
});
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
});
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
c.env.DB.prepare("DELETE FROM
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
});
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
const
|
|
368
|
-
|
|
369
|
-
.
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
});
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
contacts.
|
|
1
|
+
// Contactos, etiquetas y respuestas rápidas con las formas del panel.
|
|
2
|
+
|
|
3
|
+
import { Hono, type Context } from "hono";
|
|
4
|
+
import { notifyPanel } from "../do/inbox-hub";
|
|
5
|
+
import { deleteContact } from "../inbox/contacts";
|
|
6
|
+
import { newId } from "../inbox/store";
|
|
7
|
+
import type { NubotEnv } from "./index";
|
|
8
|
+
import { channel, toContact, ticketStatus, type ContactRecord } from "./mappers";
|
|
9
|
+
|
|
10
|
+
type Ctx = Context<NubotEnv>;
|
|
11
|
+
|
|
12
|
+
export const contacts = new Hono<NubotEnv>();
|
|
13
|
+
|
|
14
|
+
const CONTACT_COLUMNS = "id, name, phone, metadata, created_at, updated_at";
|
|
15
|
+
const notFound = (c: Ctx) => c.json({ message: "Ese contacto no existe.", statusCode: 404 }, 404);
|
|
16
|
+
const onlyAdmin = (c: Ctx) =>
|
|
17
|
+
c.get("user").role === "admin" ? null : c.json({ message: "Solo un administrador puede hacer esto.", statusCode: 403 }, 403);
|
|
18
|
+
|
|
19
|
+
interface TagRecord {
|
|
20
|
+
id: string;
|
|
21
|
+
name: string;
|
|
22
|
+
color: string;
|
|
23
|
+
description: string | null;
|
|
24
|
+
position: number;
|
|
25
|
+
created_at: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const TAG_COLUMNS = "t.id, t.name, t.color, t.description, t.position, t.created_at";
|
|
29
|
+
|
|
30
|
+
const toTag = (t: TagRecord) => ({
|
|
31
|
+
id: t.id,
|
|
32
|
+
name: t.name,
|
|
33
|
+
description: t.description,
|
|
34
|
+
color: t.color,
|
|
35
|
+
folderId: null,
|
|
36
|
+
position: t.position,
|
|
37
|
+
aiMetadata: null,
|
|
38
|
+
createdAt: new Date(t.created_at).toISOString(),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
async function tagsOf(c: Ctx, contactId: string) {
|
|
42
|
+
const { results } = await c.env.DB.prepare(
|
|
43
|
+
`SELECT ${TAG_COLUMNS} FROM contact_tags ct JOIN tags t ON t.id = ct.tag_id WHERE ct.contact_id = ? ORDER BY t.position, t.name`,
|
|
44
|
+
)
|
|
45
|
+
.bind(contactId)
|
|
46
|
+
.all<TagRecord>();
|
|
47
|
+
return results.map(toTag);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function loadContact(c: Ctx, id: string) {
|
|
51
|
+
return c.env.DB.prepare(`SELECT ${CONTACT_COLUMNS} FROM contacts WHERE id = ?`).bind(id).first<ContactRecord>();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Avisa a las conversaciones del contacto que cambió su nombre, sus datos o sus etiquetas. */
|
|
55
|
+
async function contactChanged(c: Ctx, contactId: string) {
|
|
56
|
+
const { results } = await c.env.DB.prepare("SELECT id FROM conversations WHERE contact_id = ?").bind(contactId).all<{ id: string }>();
|
|
57
|
+
c.executionCtx.waitUntil(
|
|
58
|
+
Promise.all(results.map((r) => notifyPanel(c.env, { type: "contact:update", conversationId: r.id }))),
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ---------- Contactos ----------
|
|
63
|
+
|
|
64
|
+
contacts.get("/contacts", async (c) => {
|
|
65
|
+
const page = Math.max(1, Number(c.req.query("page")) || 1);
|
|
66
|
+
const limit = Math.min(100, Math.max(1, Number(c.req.query("limit")) || 20));
|
|
67
|
+
const where: string[] = [];
|
|
68
|
+
const binds: unknown[] = [];
|
|
69
|
+
const search = c.req.query("search")?.trim();
|
|
70
|
+
if (search) {
|
|
71
|
+
where.push("(ct.name LIKE ? OR ct.phone LIKE ? OR ct.metadata LIKE ?)");
|
|
72
|
+
binds.push(`%${search}%`, `%${search}%`, `%${search}%`);
|
|
73
|
+
}
|
|
74
|
+
const tagIds = (c.req.query("tagIds") ?? "").split(",").filter(Boolean);
|
|
75
|
+
if (tagIds.length) {
|
|
76
|
+
where.push(`ct.id IN (SELECT contact_id FROM contact_tags WHERE tag_id IN (${tagIds.map(() => "?").join(", ")}))`);
|
|
77
|
+
binds.push(...tagIds);
|
|
78
|
+
}
|
|
79
|
+
if (c.req.query("untagged") === "true") where.push("ct.id NOT IN (SELECT contact_id FROM contact_tags)");
|
|
80
|
+
if (c.req.query("withoutPhone") === "true") where.push("(ct.phone IS NULL OR ct.phone = '')");
|
|
81
|
+
if (c.req.query("hasActiveTickets") === "true") {
|
|
82
|
+
where.push("ct.id IN (SELECT contact_id FROM conversations WHERE status != 'closed')");
|
|
83
|
+
}
|
|
84
|
+
const from = Date.parse(c.req.query("startDate") ?? "");
|
|
85
|
+
if (Number.isFinite(from)) {
|
|
86
|
+
where.push("ct.created_at >= ?");
|
|
87
|
+
binds.push(from);
|
|
88
|
+
}
|
|
89
|
+
const to = Date.parse(c.req.query("endDate") ?? "");
|
|
90
|
+
if (Number.isFinite(to)) {
|
|
91
|
+
where.push("ct.created_at <= ?");
|
|
92
|
+
binds.push(to);
|
|
93
|
+
}
|
|
94
|
+
const sortColumn = { name: "ct.name", createdAt: "ct.created_at", updatedAt: "ct.updated_at", lastSeenAt: "ct.updated_at" }[
|
|
95
|
+
c.req.query("sortBy") ?? "createdAt"
|
|
96
|
+
] ?? "ct.created_at";
|
|
97
|
+
const order = c.req.query("sortOrder") === "ASC" ? "ASC" : "DESC";
|
|
98
|
+
const whereSql = where.length ? `WHERE ${where.join(" AND ")}` : "";
|
|
99
|
+
const [rows, count] = await c.env.DB.batch([
|
|
100
|
+
c.env.DB.prepare(
|
|
101
|
+
`SELECT ct.id, ct.name, ct.phone, ct.metadata, ct.created_at, ct.updated_at,
|
|
102
|
+
(SELECT id FROM conversations WHERE contact_id = ct.id ORDER BY updated_at DESC LIMIT 1) AS last_ticket_id,
|
|
103
|
+
EXISTS (SELECT 1 FROM conversations WHERE contact_id = ct.id AND status != 'closed') AS active
|
|
104
|
+
FROM contacts ct ${whereSql} ORDER BY ${sortColumn} ${order}, ct.id LIMIT ? OFFSET ?`,
|
|
105
|
+
).bind(...binds, limit, (page - 1) * limit),
|
|
106
|
+
c.env.DB.prepare(`SELECT COUNT(*) AS n FROM contacts ct ${whereSql}`).bind(...binds),
|
|
107
|
+
]);
|
|
108
|
+
const list = rows.results as (ContactRecord & { last_ticket_id: string | null; active: number })[];
|
|
109
|
+
const total = (count.results[0] as { n: number }).n;
|
|
110
|
+
const data = await Promise.all(
|
|
111
|
+
list.map(async (r) => ({
|
|
112
|
+
...toContact(r),
|
|
113
|
+
phone: r.phone ?? "",
|
|
114
|
+
tags: await tagsOf(c, r.id),
|
|
115
|
+
lastTicketId: r.last_ticket_id ?? undefined,
|
|
116
|
+
hasActiveTickets: r.active === 1,
|
|
117
|
+
})),
|
|
118
|
+
);
|
|
119
|
+
return c.json({ data, total, page, pageSize: limit, hasMore: page * limit < total });
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
contacts.get("/contacts/stats", async (c) => {
|
|
123
|
+
const row = await c.env.DB.prepare(
|
|
124
|
+
`SELECT COUNT(*) AS total,
|
|
125
|
+
COALESCE(SUM(CASE WHEN metadata LIKE '%"correo"%' THEN 1 ELSE 0 END), 0) AS withEmail,
|
|
126
|
+
COALESCE(SUM(CASE WHEN phone IS NOT NULL AND phone != '' THEN 1 ELSE 0 END), 0) AS withPhone,
|
|
127
|
+
(SELECT COUNT(DISTINCT contact_id) FROM contact_tags) AS labeled
|
|
128
|
+
FROM contacts`,
|
|
129
|
+
).first();
|
|
130
|
+
return c.json(row);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
/** Cada contacto de WhatsApp es único por su número: en Lite no hay duplicados que unir. */
|
|
134
|
+
contacts.get("/contacts/duplicates", (c) => c.json({ hasResults: false, byPhone: [], byEmail: [], byFuzzy: [], meta: null }));
|
|
135
|
+
|
|
136
|
+
contacts.post("/contacts", async (c) => {
|
|
137
|
+
const body = await c.req.json<{ name?: string; phone?: string; email?: string }>();
|
|
138
|
+
const name = body.name?.trim();
|
|
139
|
+
const phone = body.phone?.replace(/[^\d+]/g, "") || null;
|
|
140
|
+
if (!name) return c.json({ message: "Escribe el nombre del contacto.", statusCode: 400 }, 400);
|
|
141
|
+
if (!phone) return c.json({ message: "Escribe el número de WhatsApp del contacto.", statusCode: 400 }, 400);
|
|
142
|
+
const digits = phone.replace(/\D/g, "");
|
|
143
|
+
const exists = await c.env.DB.prepare("SELECT 1 FROM contacts WHERE external_id = ? OR REPLACE(phone, '+', '') = ?")
|
|
144
|
+
.bind(digits, digits)
|
|
145
|
+
.first();
|
|
146
|
+
if (exists) return c.json({ message: "Ya hay un contacto con ese número.", statusCode: 409 }, 409);
|
|
147
|
+
const now = Date.now();
|
|
148
|
+
const metadata = body.email?.trim() ? { correo: body.email.trim() } : {};
|
|
149
|
+
const contact: ContactRecord = { id: newId(), name, phone: phone.startsWith("+") ? phone : `+${phone}`, metadata: JSON.stringify(metadata), created_at: now, updated_at: now };
|
|
150
|
+
await c.env.DB.prepare("INSERT INTO contacts (id, external_id, phone, name, metadata, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
151
|
+
.bind(contact.id, digits, contact.phone, name, contact.metadata, now, now)
|
|
152
|
+
.run();
|
|
153
|
+
return c.json({ ...toContact(contact), tags: [] }, 201);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
contacts.post("/contacts/bulk/delete", async (c) => {
|
|
157
|
+
const denied = onlyAdmin(c);
|
|
158
|
+
if (denied) return denied;
|
|
159
|
+
const { ids } = await c.req.json<{ ids?: string[] }>();
|
|
160
|
+
for (const id of ids ?? []) await deleteContact(c.env, id);
|
|
161
|
+
c.executionCtx.waitUntil(notifyPanel(c.env, { type: "contact:delete" }));
|
|
162
|
+
return c.json({ count: ids?.length ?? 0 });
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
contacts.post("/contacts/bulk/tags", async (c) => {
|
|
166
|
+
const { ids, tagIds } = await c.req.json<{ ids?: string[]; tagIds?: string[] }>();
|
|
167
|
+
const now = Date.now();
|
|
168
|
+
const pairs = (ids ?? []).flatMap((id) => (tagIds ?? []).map((tagId) => [id, tagId]));
|
|
169
|
+
if (pairs.length) {
|
|
170
|
+
await c.env.DB.batch(
|
|
171
|
+
pairs.map(([id, tagId]) =>
|
|
172
|
+
c.env.DB.prepare(
|
|
173
|
+
"INSERT OR IGNORE INTO contact_tags (contact_id, tag_id, created_at) SELECT ?, ?, ? WHERE EXISTS (SELECT 1 FROM tags WHERE id = ?)",
|
|
174
|
+
).bind(id, tagId, now, tagId),
|
|
175
|
+
),
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
return c.json({ count: ids?.length ?? 0 });
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
contacts.get("/contacts/:id", async (c) => {
|
|
182
|
+
const row = await loadContact(c, c.req.param("id"));
|
|
183
|
+
return row ? c.json({ ...toContact(row), tags: await tagsOf(c, row.id) }) : notFound(c);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
contacts.get("/contacts/:id/full", async (c) => {
|
|
187
|
+
const row = await loadContact(c, c.req.param("id"));
|
|
188
|
+
if (!row) return notFound(c);
|
|
189
|
+
return c.json({
|
|
190
|
+
...toContact(row),
|
|
191
|
+
tags: await tagsOf(c, row.id),
|
|
192
|
+
isBlacklisted: false,
|
|
193
|
+
identities: row.phone ? [{ id: `${row.id}:phone`, type: "PHONE", identifierValue: row.phone, isBlacklisted: false }] : [],
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
contacts.patch("/contacts/:id", async (c) => {
|
|
198
|
+
const row = await loadContact(c, c.req.param("id"));
|
|
199
|
+
if (!row) return notFound(c);
|
|
200
|
+
const body = await c.req.json<{ name?: string; email?: string | null; metadata?: Record<string, unknown> }>();
|
|
201
|
+
const metadata = { ...(JSON.parse(row.metadata || "{}") as Record<string, unknown>), ...(body.metadata ?? {}) };
|
|
202
|
+
if (body.email !== undefined) {
|
|
203
|
+
if (body.email) metadata.correo = body.email.trim();
|
|
204
|
+
else delete metadata.correo;
|
|
205
|
+
}
|
|
206
|
+
const name = body.name?.trim() || row.name;
|
|
207
|
+
await c.env.DB.prepare("UPDATE contacts SET name = ?, metadata = ?, updated_at = ? WHERE id = ?")
|
|
208
|
+
.bind(name, JSON.stringify(metadata), Date.now(), row.id)
|
|
209
|
+
.run();
|
|
210
|
+
await contactChanged(c, row.id);
|
|
211
|
+
const saved = await loadContact(c, row.id);
|
|
212
|
+
return c.json({ ...toContact(saved!), tags: await tagsOf(c, row.id) });
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
/** Borra al contacto con todo su historial: lo que pide la ley de protección de datos cuando el cliente lo solicita. */
|
|
216
|
+
contacts.delete("/contacts/:id", async (c) => {
|
|
217
|
+
const denied = onlyAdmin(c);
|
|
218
|
+
if (denied) return denied;
|
|
219
|
+
const id = c.req.param("id");
|
|
220
|
+
if (!(await loadContact(c, id))) return notFound(c);
|
|
221
|
+
const { filesDeleted } = await deleteContact(c.env, id);
|
|
222
|
+
c.executionCtx.waitUntil(notifyPanel(c.env, { type: "contact:delete" }));
|
|
223
|
+
return c.json({ success: true, filesDeleted });
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
contacts.get("/contacts/:id/tags", async (c) => c.json(await tagsOf(c, c.req.param("id"))));
|
|
227
|
+
|
|
228
|
+
contacts.post("/contacts/:id/tags/:tagId", async (c) => {
|
|
229
|
+
const { id, tagId } = c.req.param();
|
|
230
|
+
const tag = await c.env.DB.prepare("SELECT 1 FROM tags WHERE id = ?").bind(tagId).first();
|
|
231
|
+
if (!tag || !(await loadContact(c, id))) return c.json({ message: "No encontramos el contacto o la etiqueta.", statusCode: 404 }, 404);
|
|
232
|
+
await c.env.DB.prepare("INSERT OR IGNORE INTO contact_tags (contact_id, tag_id, created_at) VALUES (?, ?, ?)")
|
|
233
|
+
.bind(id, tagId, Date.now())
|
|
234
|
+
.run();
|
|
235
|
+
await contactChanged(c, id);
|
|
236
|
+
return c.json({ success: true }, 201);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
contacts.delete("/contacts/:id/tags/:tagId", async (c) => {
|
|
240
|
+
const { id, tagId } = c.req.param();
|
|
241
|
+
await c.env.DB.prepare("DELETE FROM contact_tags WHERE contact_id = ? AND tag_id = ?").bind(id, tagId).run();
|
|
242
|
+
await contactChanged(c, id);
|
|
243
|
+
return c.json({ success: true });
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
contacts.get("/contacts/:id/blacklist-status", async (c) => {
|
|
247
|
+
const row = await loadContact(c, c.req.param("id"));
|
|
248
|
+
return c.json({ isBlacklisted: false, phone: row?.phone ?? null });
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
contacts.get("/contacts/:id/metadata-history", (c) => c.json([]));
|
|
252
|
+
|
|
253
|
+
contacts.get("/contacts/:id/tickets", async (c) => {
|
|
254
|
+
const { results } = await c.env.DB.prepare(
|
|
255
|
+
`SELECT cv.id, cv.channel, cv.status, cv.assigned_user_id, cv.created_at, cv.updated_at,
|
|
256
|
+
(SELECT COUNT(*) FROM messages m WHERE m.conversation_id = cv.id) AS message_count
|
|
257
|
+
FROM conversations cv WHERE cv.contact_id = ? ORDER BY cv.updated_at DESC`,
|
|
258
|
+
)
|
|
259
|
+
.bind(c.req.param("id"))
|
|
260
|
+
.all<{ id: string; channel: string; status: "ai" | "human" | "closed"; assigned_user_id: string | null; created_at: number; updated_at: number; message_count: number }>();
|
|
261
|
+
return c.json(
|
|
262
|
+
results.map((r) => ({
|
|
263
|
+
id: r.id,
|
|
264
|
+
status: ticketStatus(r),
|
|
265
|
+
channelType: channel(r.channel).type,
|
|
266
|
+
channelName: channel(r.channel).name,
|
|
267
|
+
createdAt: new Date(r.created_at).toISOString(),
|
|
268
|
+
updatedAt: new Date(r.updated_at).toISOString(),
|
|
269
|
+
messageCount: r.message_count,
|
|
270
|
+
})),
|
|
271
|
+
);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
contacts.get("/contacts/:id/open-ticket", async (c) => {
|
|
275
|
+
const row = await c.env.DB.prepare(
|
|
276
|
+
"SELECT id, channel, zernio_account_id, status, assigned_user_id FROM conversations WHERE contact_id = ? AND status != 'closed' ORDER BY updated_at DESC LIMIT 1",
|
|
277
|
+
)
|
|
278
|
+
.bind(c.req.param("id"))
|
|
279
|
+
.first<{ id: string; channel: string; zernio_account_id: string; status: "ai" | "human" | "closed"; assigned_user_id: string | null }>();
|
|
280
|
+
if (!row) return c.json(null);
|
|
281
|
+
const ch = channel(row.channel, row.zernio_account_id);
|
|
282
|
+
return c.json({ ticketId: row.id, status: ticketStatus(row), channelId: ch.id, channelName: ch.name, channelType: ch.type });
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// ---------- Etiquetas ----------
|
|
286
|
+
|
|
287
|
+
contacts.get("/tags", async (c) => {
|
|
288
|
+
const { results } = await c.env.DB.prepare(`SELECT ${TAG_COLUMNS} FROM tags t ORDER BY t.position, t.name`).all<TagRecord>();
|
|
289
|
+
return c.json(results.map(toTag));
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
/** En Lite las etiquetas no van en carpetas. */
|
|
293
|
+
contacts.get("/tags/folders", (c) => c.json([]));
|
|
294
|
+
|
|
295
|
+
contacts.post("/tags", async (c) => {
|
|
296
|
+
const body = await c.req.json<{ name?: string; color?: string; description?: string }>();
|
|
297
|
+
const name = body.name?.trim();
|
|
298
|
+
if (!name) return c.json({ message: "Escribe el nombre de la etiqueta.", statusCode: 400 }, 400);
|
|
299
|
+
const exists = await c.env.DB.prepare("SELECT 1 FROM tags WHERE name = ? COLLATE NOCASE").bind(name).first();
|
|
300
|
+
if (exists) return c.json({ message: "Esa etiqueta ya existe.", statusCode: 409 }, 409);
|
|
301
|
+
const color = /^#[0-9a-f]{6}$/i.test(body.color ?? "") ? body.color! : "#135bec";
|
|
302
|
+
const next = await c.env.DB.prepare("SELECT COALESCE(MAX(position), 0) + 1 AS p FROM tags").first<{ p: number }>();
|
|
303
|
+
const tag: TagRecord = { id: newId(), name, color, description: body.description?.trim() || null, position: next?.p ?? 1, created_at: Date.now() };
|
|
304
|
+
await c.env.DB.prepare("INSERT INTO tags (id, name, color, description, position, created_at) VALUES (?, ?, ?, ?, ?, ?)")
|
|
305
|
+
.bind(tag.id, tag.name, tag.color, tag.description, tag.position, tag.created_at)
|
|
306
|
+
.run();
|
|
307
|
+
return c.json(toTag(tag), 201);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
contacts.patch("/tags/reorder", async (c) => {
|
|
311
|
+
const { orders } = await c.req.json<{ orders?: { id: string; position: number }[] }>();
|
|
312
|
+
if (orders?.length) {
|
|
313
|
+
await c.env.DB.batch(orders.map((o) => c.env.DB.prepare("UPDATE tags SET position = ? WHERE id = ?").bind(o.position, o.id)));
|
|
314
|
+
}
|
|
315
|
+
return c.json({ success: true });
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
contacts.patch("/tags/:id", async (c) => {
|
|
319
|
+
const body = await c.req.json<{ name?: string; color?: string; description?: string | null }>();
|
|
320
|
+
const row = await c.env.DB.prepare(`SELECT ${TAG_COLUMNS} FROM tags t WHERE t.id = ?`).bind(c.req.param("id")).first<TagRecord>();
|
|
321
|
+
if (!row) return c.json({ message: "Esa etiqueta no existe.", statusCode: 404 }, 404);
|
|
322
|
+
const tag: TagRecord = {
|
|
323
|
+
...row,
|
|
324
|
+
name: body.name?.trim() || row.name,
|
|
325
|
+
color: /^#[0-9a-f]{6}$/i.test(body.color ?? "") ? body.color! : row.color,
|
|
326
|
+
description: body.description === undefined ? row.description : body.description?.trim() || null,
|
|
327
|
+
};
|
|
328
|
+
await c.env.DB.prepare("UPDATE tags SET name = ?, color = ?, description = ? WHERE id = ?")
|
|
329
|
+
.bind(tag.name, tag.color, tag.description, tag.id)
|
|
330
|
+
.run();
|
|
331
|
+
return c.json(toTag(tag));
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
async function deleteTags(c: Ctx, ids: string[]) {
|
|
335
|
+
if (!ids.length) return 0;
|
|
336
|
+
const marks = ids.map(() => "?").join(", ");
|
|
337
|
+
const [, deleted] = await c.env.DB.batch([
|
|
338
|
+
c.env.DB.prepare(`DELETE FROM contact_tags WHERE tag_id IN (${marks})`).bind(...ids),
|
|
339
|
+
c.env.DB.prepare(`DELETE FROM tags WHERE id IN (${marks})`).bind(...ids),
|
|
340
|
+
]);
|
|
341
|
+
return deleted.meta.changes ?? 0;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
contacts.delete("/tags/bulk/delete", async (c) => {
|
|
345
|
+
const { tagIds } = await c.req.json<{ tagIds?: string[] }>();
|
|
346
|
+
return c.json({ deleted: await deleteTags(c, tagIds ?? []) });
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
contacts.delete("/tags/:id", async (c) => {
|
|
350
|
+
await deleteTags(c, [c.req.param("id")]);
|
|
351
|
+
return c.json({ success: true });
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
contacts.post("/tags/merge", async (c) => {
|
|
355
|
+
const { sourceTagId, targetTagId } = await c.req.json<{ sourceTagId: string; targetTagId: string }>();
|
|
356
|
+
const [moved] = await c.env.DB.batch([
|
|
357
|
+
c.env.DB.prepare(
|
|
358
|
+
"INSERT OR IGNORE INTO contact_tags (contact_id, tag_id, created_at) SELECT contact_id, ?, created_at FROM contact_tags WHERE tag_id = ?",
|
|
359
|
+
).bind(targetTagId, sourceTagId),
|
|
360
|
+
c.env.DB.prepare("DELETE FROM contact_tags WHERE tag_id = ?").bind(sourceTagId),
|
|
361
|
+
c.env.DB.prepare("DELETE FROM tags WHERE id = ?").bind(sourceTagId),
|
|
362
|
+
]);
|
|
363
|
+
return c.json({ transferred: moved.meta.changes ?? 0, deleted: true });
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
async function usageCounts(c: Ctx, ids?: string[]) {
|
|
367
|
+
const filter = ids?.length ? `WHERE tag_id IN (${ids.map(() => "?").join(", ")})` : "";
|
|
368
|
+
const { results } = await c.env.DB.prepare(`SELECT tag_id, COUNT(*) AS n FROM contact_tags ${filter} GROUP BY tag_id`)
|
|
369
|
+
.bind(...(ids ?? []))
|
|
370
|
+
.all<{ tag_id: string; n: number }>();
|
|
371
|
+
return Object.fromEntries(results.map((r) => [r.tag_id, r.n]));
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
contacts.get("/tags/stats/usage-counts", async (c) => c.json(await usageCounts(c)));
|
|
375
|
+
|
|
376
|
+
contacts.post("/tags/bulk/usage", async (c) => {
|
|
377
|
+
const { tagIds } = await c.req.json<{ tagIds?: string[] }>();
|
|
378
|
+
return c.json(await usageCounts(c, tagIds ?? []));
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
contacts.get("/tags/:id/usage", async (c) => {
|
|
382
|
+
const id = c.req.param("id");
|
|
383
|
+
return c.json({ tagId: id, count: (await usageCounts(c, [id]))[id] ?? 0 });
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
contacts.get("/metadata-schemas", (c) => c.json([]));
|
|
387
|
+
contacts.post("/tags/folders", (c) => c.json({ message: "Las carpetas de etiquetas son parte de Nubot.", statusCode: 409 }, 409));
|