server.js 204 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654
  1. require('dotenv').config();
  2. const { createLogger } = require('./utils/logger');
  3. const log = createLogger('gateway');
  4. const app = require('fastify')({ logger: log });
  5. const multipart = require('@fastify/multipart');
  6. const axios = require('axios');
  7. const fs = require('fs');
  8. const path = require('path');
  9. const crypto = require('crypto');
  10. const { pipeline } = require('stream/promises');
  11. const { ObjectId } = require('mongodb');
  12. const { getDb } = require('./utils/MongoDBConnector');
  13. const { encryptToken, decryptToken, warnIfNoKey } = require('./utils/crypto');
  14. const RabbitMQProducer = require('./utils/RabbitMQProducer');
  15. const UPLOAD_DIR = process.env.UPLOAD_DIR || '/uploads';
  16. const ALLOWED_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.mp4', '.mov', '.avi']);
  17. const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
  18. // In-memory job state for async competitor scrapes.
  19. // Max 2 competitors, scrapes complete in seconds — no persistence needed.
  20. const activeScrapeJobs = new Map();
  21. // ─── Platform-native writing rules ────────────────────────────────────────────
  22. // Injected into the AI system prompt when destinations are known.
  23. const PLATFORM_WRITING_RULES = {
  24. twitter: [
  25. 'Keep the post under 200 characters for maximum retweetability.',
  26. 'Use zero to one hashtag — more than one significantly hurts reach.',
  27. 'End with a question or provocation to drive replies.',
  28. 'No slow intros — the hook must land in the opening clause.',
  29. ],
  30. linkedin: [
  31. 'Only the first 2–3 lines are visible before "see more" — the hook must grab immediately.',
  32. 'Put external links in the first comment, not the post body — links in copy reduce reach.',
  33. 'Use 2–3 hashtags maximum, placed at the very end of the post.',
  34. 'Write for practitioners and decision-makers using clear, direct language.',
  35. ],
  36. instagram: [
  37. 'Only the first ~125 characters show before "more" — front-load the hook.',
  38. 'For Reels: hook text must appear on-screen within the first 1 second; assume silent viewing, so text overlays are essential.',
  39. 'Carousels get the highest saves — use them for educational or step-by-step content.',
  40. 'End with a clear call-to-action.',
  41. ],
  42. facebook: [
  43. 'First 3 lines visible before "See more" — lead with the most engaging line.',
  44. 'Conversational tone outperforms corporate language.',
  45. 'Questions and polls significantly boost comments and reach.',
  46. 'External links reduce reach — consider placing the link in the first comment.',
  47. ],
  48. tiktok: [
  49. 'The very first spoken word or on-screen text must hook the viewer at second 0 — no slow intros.',
  50. 'Creator-native feel performs far better than polished corporate openers.',
  51. 'End every script with a comment-bait line (a question or debate prompt).',
  52. 'Optimal caption length: short and punchy; the hook lives in the video, not the caption.',
  53. ],
  54. youtube: [
  55. 'Title must be written for search — include the primary keyword near the front.',
  56. 'Open the script with a 15-second hook that states the value proposition immediately.',
  57. 'First 2 lines of the description appear in search results — write them for click-through.',
  58. 'Always include timestamps/chapters in longer-form descriptions.',
  59. ],
  60. pinterest: [
  61. 'Pinterest is a search engine — descriptions must be keyword-rich prose, not hashtag fragments.',
  62. 'Every pin should link somewhere relevant; linkless pins underperform.',
  63. 'Vertical 2:3 format is optimal for feed visibility.',
  64. 'Use natural-language keyword phrases (e.g. "easy weeknight dinner ideas") not isolated keywords.',
  65. ],
  66. reddit: [
  67. 'Reddit is a community channel, not a publishing channel — never pitch directly.',
  68. 'Write like a practitioner who works at the brand, not a marketer who works for it.',
  69. 'Lead with value: useful data, a genuine question, or an interesting observation.',
  70. 'Match the subreddit tone exactly — formal communities reject casual posts and vice versa.',
  71. ],
  72. mastodon: [
  73. 'Mastodon users value authenticity — corporate marketing tone is poorly received.',
  74. 'Use 3–5 relevant hashtags; they are the primary discovery mechanism on Mastodon.',
  75. 'Longer posts should use a CW (content warning) as a brief summary — this is a community norm.',
  76. 'Engagement comes from genuine conversation, not broadcast-style posting.',
  77. ],
  78. bluesky: [
  79. 'Bluesky rewards original perspectives — repurposed content from other platforms underperforms.',
  80. 'Threads work well for longer ideas; each post in the thread should stand alone.',
  81. 'Use 1–2 hashtags if any — hashtag culture is still developing on Bluesky.',
  82. 'Substance drives sharing here more than engagement-bait does.',
  83. ],
  84. };
  85. function buildPlatformRulesBlock(destinations) {
  86. if (!destinations?.length) return '';
  87. const platforms = [...new Set(destinations.map((d) => d.platform).filter(Boolean))];
  88. const blocks = platforms
  89. .map((p) => {
  90. const rules = PLATFORM_WRITING_RULES[p];
  91. if (!rules?.length) return null;
  92. const name = p.charAt(0).toUpperCase() + p.slice(1);
  93. return `${name} rules:\n${rules.map((r) => `- ${r}`).join('\n')}`;
  94. })
  95. .filter(Boolean);
  96. if (!blocks.length) return '';
  97. return '\n\nPLATFORM-SPECIFIC WRITING RULES (follow these for every post on this platform):\n' + blocks.join('\n\n');
  98. }
  99. fs.mkdirSync(UPLOAD_DIR, { recursive: true });
  100. app.register(multipart, { limits: { fileSize: MAX_FILE_SIZE } });
  101. const GRAPH_API = 'https://graph.facebook.com/v22.0';
  102. // The public base URL of this app (used for OAuth redirect_uri)
  103. const APP_BASE_URL = process.env.APP_BASE_URL || 'http://localhost:8081';
  104. // ─── CORS ────────────────────────────────────────────────────────────────────
  105. app.addHook('onSend', async (request, reply) => {
  106. reply.header('Access-Control-Allow-Origin', '*');
  107. reply.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,PATCH,OPTIONS');
  108. reply.header('Access-Control-Allow-Headers', 'Content-Type, X-Workspace-Id');
  109. });
  110. // Inject workspace context into every request
  111. app.addHook('preHandler', async (request) => {
  112. request.workspaceId = request.headers['x-workspace-id'] || 'default';
  113. });
  114. app.options('*', async (request, reply) => {
  115. reply.code(204).send();
  116. });
  117. // ─── Helpers ─────────────────────────────────────────────────────────────────
  118. // Compound credential key: workspaceId + credential type
  119. function credId(ws, type) { return `${ws}:${type}`; }
  120. // Global credential types are not workspace-scoped (AI config, app credentials)
  121. const GLOBAL_CREDENTIAL_TYPES = new Set([
  122. 'ai_config', 'openai_config', 'groq_config', 'gemini_config',
  123. 'meta_app', 'pinterest_app', 'tiktok_app', 'google_places',
  124. ]);
  125. async function getCredentials(ws, type) {
  126. const db = await getDb();
  127. const id = GLOBAL_CREDENTIAL_TYPES.has(type) ? type : credId(ws, type);
  128. return db.collection('platform_credentials').findOne({ _id: id });
  129. }
  130. async function setCredentials(ws, type, data) {
  131. const isGlobal = GLOBAL_CREDENTIAL_TYPES.has(type);
  132. const id = isGlobal ? type : credId(ws, type);
  133. const db = await getDb();
  134. const meta = isGlobal ? {} : { workspaceId: ws };
  135. await db.collection('platform_credentials').updateOne(
  136. { _id: id },
  137. { $set: { _id: id, type, ...meta, ...data, updatedAt: new Date() } },
  138. { upsert: true }
  139. );
  140. }
  141. async function deleteCredentials(ws, type) {
  142. const db = await getDb();
  143. const id = GLOBAL_CREDENTIAL_TYPES.has(type) ? type : credId(ws, type);
  144. await db.collection('platform_credentials').deleteOne({ _id: id });
  145. }
  146. // ─── Workspaces ───────────────────────────────────────────────────────────────
  147. app.get('/workspaces', async () => {
  148. const db = await getDb();
  149. const list = await db.collection('workspaces').find({}).sort({ createdAt: 1 }).toArray();
  150. return { workspaces: list };
  151. });
  152. app.post('/workspaces', async (request, reply) => {
  153. const { name, color } = request.body || {};
  154. if (!name?.trim()) return reply.code(400).send({ error: 'Workspace name is required' });
  155. const db = await getDb();
  156. const id = `ws_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
  157. const doc = { _id: id, name: name.trim(), color: color || '#3B82F6', createdAt: new Date(), updatedAt: new Date() };
  158. await db.collection('workspaces').insertOne(doc);
  159. log.info({ action: 'workspace_create', workspaceId: id, name: doc.name, outcome: 'success' });
  160. return reply.code(201).send(doc);
  161. });
  162. app.put('/workspaces/:id', async (request, reply) => {
  163. const { id } = request.params;
  164. const { name, color } = request.body || {};
  165. if (!name?.trim()) return reply.code(400).send({ error: 'Workspace name is required' });
  166. const db = await getDb();
  167. const result = await db.collection('workspaces').updateOne(
  168. { _id: id },
  169. { $set: { name: name.trim(), color: color || '#3B82F6', updatedAt: new Date() } }
  170. );
  171. if (!result.matchedCount) return reply.code(404).send({ error: 'Workspace not found' });
  172. return { success: true };
  173. });
  174. app.delete('/workspaces/:id', async (request, reply) => {
  175. const { id } = request.params;
  176. if (id === 'default') return reply.code(400).send({ error: 'Cannot delete the default workspace' });
  177. const db = await getDb();
  178. const result = await db.collection('workspaces').deleteOne({ _id: id });
  179. if (!result.deletedCount) return reply.code(404).send({ error: 'Workspace not found' });
  180. // Cascade-delete all workspace-scoped data
  181. const deleteAll = (col, filter) => db.collection(col).deleteMany(filter);
  182. await Promise.all([
  183. db.collection('platform_credentials').deleteMany({ workspaceId: id }),
  184. deleteAll('competitors', { workspaceId: id }),
  185. deleteAll('hashtag_groups', { workspaceId: id }),
  186. deleteAll('hashtag_stats', { workspaceId: id }),
  187. deleteAll('account_profiles', { workspaceId: id }),
  188. deleteAll('content_calendars', { workspaceId: id }),
  189. deleteAll('bulk_draft_batches', { workspaceId: id }),
  190. deleteAll('drafts', { workspaceId: id }),
  191. deleteAll('posts', { workspaceId: id }),
  192. deleteAll('post_metrics', { workspaceId: id }),
  193. deleteAll('media_files', { workspaceId: id }),
  194. ]);
  195. log.info({ action: 'workspace_delete', workspaceId: id, outcome: 'success' });
  196. return { success: true };
  197. });
  198. // ─── Startup Migration ────────────────────────────────────────────────────────
  199. // Stamps existing documents (created before workspaces) with workspaceId: 'default'
  200. // and migrates platform_credentials _id keys to the 'default:type' format.
  201. async function runWorkspaceMigration() {
  202. try {
  203. const db = await getDb();
  204. // Ensure the default workspace exists
  205. await db.collection('workspaces').updateOne(
  206. { _id: 'default' },
  207. { $setOnInsert: { _id: 'default', name: 'Default', color: '#3B82F6', createdAt: new Date(), updatedAt: new Date() } },
  208. { upsert: true }
  209. );
  210. // Migrate platform_credentials: re-key any doc whose _id doesn't contain ':'
  211. const oldCreds = await db.collection('platform_credentials').find({ _id: { $not: /\:/ } }).toArray();
  212. for (const cred of oldCreds) {
  213. const newId = credId('default', cred._id);
  214. const exists = await db.collection('platform_credentials').findOne({ _id: newId });
  215. if (!exists) {
  216. await db.collection('platform_credentials').insertOne({ ...cred, _id: newId, workspaceId: 'default', type: cred._id });
  217. }
  218. await db.collection('platform_credentials').deleteOne({ _id: cred._id });
  219. }
  220. // Stamp workspaceId on all other collections
  221. const cols = ['competitors','hashtag_groups','hashtag_stats','account_profiles','content_calendars','bulk_draft_batches','drafts','posts','post_metrics','media_files','feeds','scheduled_jobs'];
  222. for (const col of cols) {
  223. await db.collection(col).updateMany({ workspaceId: { $exists: false } }, { $set: { workspaceId: 'default' } });
  224. }
  225. if (oldCreds.length > 0) log.info({ action: 'workspace_migration', migrated: oldCreds.length, outcome: 'success' });
  226. } catch (err) {
  227. log.error({ action: 'workspace_migration', outcome: 'failure', err: err.message });
  228. }
  229. }
  230. getDb().then(() => runWorkspaceMigration());
  231. // ─── Media Upload & Library ───────────────────────────────────────────────────
  232. app.post('/upload', async (request, reply) => {
  233. const folder = request.query.folder || null;
  234. const data = await request.file();
  235. if (!data) return reply.code(400).send({ error: 'No file provided' });
  236. const ext = path.extname(data.filename).toLowerCase();
  237. if (!ALLOWED_EXTENSIONS.has(ext)) {
  238. data.file.resume();
  239. return reply.code(400).send({ error: `File type "${ext}" is not allowed. Allowed: jpg, jpeg, png, gif, webp, mp4, mov, avi` });
  240. }
  241. const filename = `${crypto.randomUUID()}${ext}`;
  242. const filepath = path.join(UPLOAD_DIR, filename);
  243. try {
  244. await pipeline(data.file, fs.createWriteStream(filepath));
  245. } catch (err) {
  246. app.log.error({ action: 'media_upload', outcome: 'failure', err: err.message });
  247. return reply.code(500).send({ error: 'Failed to save file' });
  248. }
  249. const stat = fs.statSync(filepath);
  250. const record = {
  251. filename,
  252. originalName: data.filename,
  253. url: `/media/${filename}`,
  254. mimetype: data.mimetype,
  255. size: stat.size,
  256. folder: folder || null,
  257. workspaceId: request.workspaceId,
  258. uploadedAt: new Date(),
  259. };
  260. try {
  261. const db = await getDb();
  262. await db.collection('media_files').insertOne(record);
  263. } catch (err) {
  264. app.log.error({ action: 'media_metadata_save', outcome: 'failure', err: err.message });
  265. }
  266. return { url: record.url, filename, originalName: data.filename, mimetype: data.mimetype, size: stat.size, folder: record.folder };
  267. });
  268. // List uploaded media files, newest first; optionally filter by folder
  269. // folder=__none__ → unorganized (null/missing); folder=<name> → that folder; omit → all
  270. app.get('/media-library', async (request) => {
  271. const ws = request.workspaceId;
  272. const db = await getDb();
  273. const { folder } = request.query;
  274. const query = { workspaceId: ws };
  275. if (folder === '__none__') {
  276. query.$or = [{ folder: { $exists: false } }, { folder: null }, { folder: '' }];
  277. } else if (folder) {
  278. query.folder = folder;
  279. }
  280. const files = await db.collection('media_files').find(query).sort({ uploadedAt: -1 }).toArray();
  281. return { files };
  282. });
  283. // List custom folders with per-folder file counts
  284. app.get('/media-folders', async () => {
  285. const db = await getDb();
  286. const [folders, counts] = await Promise.all([
  287. db.collection('media_folders').find({}).sort({ createdAt: 1 }).toArray(),
  288. db.collection('media_files').aggregate([
  289. { $group: { _id: { $ifNull: ['$folder', '__none__'] }, count: { $sum: 1 } } },
  290. ]).toArray(),
  291. ]);
  292. const countMap = Object.fromEntries(counts.map((c) => [c._id, c.count]));
  293. const total = counts.reduce((s, c) => s + c.count, 0);
  294. return {
  295. folders: folders.map((f) => ({ name: f.name, count: countMap[f.name] || 0 })),
  296. totalCount: total,
  297. unorganizedCount: countMap['__none__'] || 0,
  298. folderCounts: countMap,
  299. };
  300. });
  301. // Create a custom folder
  302. app.post('/media-folders', async (request, reply) => {
  303. const { name } = request.body || {};
  304. if (!name?.trim()) return reply.code(400).send({ error: 'Folder name is required' });
  305. const trimmed = name.trim();
  306. const db = await getDb();
  307. if (await db.collection('media_folders').findOne({ name: trimmed })) {
  308. return reply.code(409).send({ error: 'Folder already exists' });
  309. }
  310. await db.collection('media_folders').insertOne({ name: trimmed, createdAt: new Date() });
  311. return { name: trimmed };
  312. });
  313. // Delete a custom folder; files in it become unorganized
  314. app.delete('/media-folders/:name', async (request, reply) => {
  315. const name = decodeURIComponent(request.params.name);
  316. const db = await getDb();
  317. await db.collection('media_folders').deleteOne({ name });
  318. await db.collection('media_files').updateMany({ folder: name }, { $set: { folder: null } });
  319. return { success: true };
  320. });
  321. // Update a file's folder assignment
  322. app.patch('/media/:filename', async (request, reply) => {
  323. const ws = request.workspaceId;
  324. const { filename } = request.params;
  325. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  326. return reply.code(400).send({ error: 'Invalid filename' });
  327. }
  328. const { folder } = request.body || {};
  329. const db = await getDb();
  330. const result = await db.collection('media_files').updateOne(
  331. { filename, workspaceId: ws },
  332. { $set: { folder: folder || null } },
  333. );
  334. if (!result.matchedCount) return reply.code(404).send({ error: 'File not found' });
  335. return { success: true };
  336. });
  337. // Delete a media file from disk and database
  338. app.delete('/media/:filename', async (request, reply) => {
  339. const ws = request.workspaceId;
  340. const { filename } = request.params;
  341. // Prevent path traversal
  342. if (!filename || filename.includes('/') || filename.includes('..') || filename.includes('\0')) {
  343. return reply.code(400).send({ error: 'Invalid filename' });
  344. }
  345. const filepath = path.join(UPLOAD_DIR, filename);
  346. try {
  347. fs.unlinkSync(filepath);
  348. } catch (err) {
  349. if (err.code !== 'ENOENT') {
  350. app.log.error({ action: 'media_delete', outcome: 'failure', err: err.message });
  351. return reply.code(500).send({ error: 'Failed to delete file' });
  352. }
  353. // Already gone from disk — still clean up DB record
  354. }
  355. const db = await getDb();
  356. await db.collection('media_files').deleteOne({ filename, workspaceId: ws });
  357. return { success: true };
  358. });
  359. // ─── Drafts ──────────────────────────────────────────────────────────────────
  360. app.post('/drafts', async (request, reply) => {
  361. const ws = request.workspaceId;
  362. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  363. const db = await getDb();
  364. const now = new Date();
  365. const result = await db.collection('drafts').insertOne({
  366. content, mediaUrl, scheduledAt, destinations, workspaceId: ws, createdAt: now, updatedAt: now,
  367. });
  368. const draft = await db.collection('drafts').findOne({ _id: result.insertedId });
  369. return reply.code(201).send(draft);
  370. });
  371. app.get('/drafts', async (request) => {
  372. const ws = request.workspaceId;
  373. const db = await getDb();
  374. const drafts = await db.collection('drafts').find({ workspaceId: ws }).sort({ updatedAt: -1 }).toArray();
  375. return { drafts };
  376. });
  377. app.get('/drafts/:id', async (request, reply) => {
  378. const ws = request.workspaceId;
  379. const { id } = request.params;
  380. let oid;
  381. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  382. const db = await getDb();
  383. const draft = await db.collection('drafts').findOne({ _id: oid, workspaceId: ws });
  384. if (!draft) return reply.code(404).send({ error: 'Draft not found' });
  385. return draft;
  386. });
  387. app.put('/drafts/:id', async (request, reply) => {
  388. const ws = request.workspaceId;
  389. const { id } = request.params;
  390. let oid;
  391. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  392. const { content = '', mediaUrl = '', scheduledAt = '', destinations = [] } = request.body || {};
  393. const db = await getDb();
  394. const result = await db.collection('drafts').updateOne(
  395. { _id: oid, workspaceId: ws },
  396. { $set: { content, mediaUrl, scheduledAt, destinations, updatedAt: new Date() } }
  397. );
  398. if (!result.matchedCount) return reply.code(404).send({ error: 'Draft not found' });
  399. return { success: true };
  400. });
  401. app.delete('/drafts/:id', async (request, reply) => {
  402. const ws = request.workspaceId;
  403. const { id } = request.params;
  404. let oid;
  405. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid draft ID' }); }
  406. const db = await getDb();
  407. await db.collection('drafts').deleteOne({ _id: oid, workspaceId: ws });
  408. return { success: true };
  409. });
  410. // ─── Meta Token Expiry & Auto-Refresh ────────────────────────────────────────
  411. let _tokenExpiryCache = null;
  412. let _tokenExpiryCacheAt = 0;
  413. const TOKEN_EXPIRY_TTL = 60 * 60 * 1000; // 1 hour
  414. const TOKEN_REFRESH_THRESHOLD_DAYS = 7; // refresh when ≤ this many days remain
  415. app.get('/meta/token-expiry', async (request, reply) => {
  416. if (_tokenExpiryCache && Date.now() - _tokenExpiryCacheAt < TOKEN_EXPIRY_TTL) {
  417. return _tokenExpiryCache;
  418. }
  419. const ws = request.workspaceId;
  420. const appCred = await getCredentials(ws, 'meta_app');
  421. if (!appCred?.appId || !appCred?.appSecret) return { accounts: [] };
  422. const plainAppSecret = decryptToken(appCred.appSecret);
  423. if (!plainAppSecret) return { accounts: [] };
  424. const ig = await getCredentials(ws, 'instagram');
  425. const selectedAccounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  426. if (!selectedAccounts.length) return { accounts: [] };
  427. const appToken = `${appCred.appId}|${plainAppSecret}`;
  428. const accounts = [];
  429. for (const account of selectedAccounts) {
  430. const plainToken = decryptToken(account.accessToken);
  431. if (!plainToken) continue;
  432. try {
  433. const res = await axios.get(`${GRAPH_API}/debug_token`, {
  434. params: { input_token: plainToken, access_token: appToken },
  435. timeout: 10000,
  436. });
  437. const data = res.data.data;
  438. const expiresAt = data.expires_at ? new Date(data.expires_at * 1000).toISOString() : null;
  439. const daysLeft = expiresAt
  440. ? Math.ceil((new Date(expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24))
  441. : null;
  442. accounts.push({ id: account.id, username: account.username, expiresAt, daysLeft, isValid: !!data.is_valid });
  443. } catch (err) {
  444. app.log.warn({ action: 'token_expiry_check', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  445. }
  446. }
  447. _tokenExpiryCache = { accounts, checkedAt: new Date().toISOString() };
  448. _tokenExpiryCacheAt = Date.now();
  449. return _tokenExpiryCache;
  450. });
  451. // Refresh Instagram long-lived tokens that are within TOKEN_REFRESH_THRESHOLD_DAYS of expiry.
  452. // Called by the scheduler's daily BullMQ job; can also be triggered manually from Settings.
  453. app.post('/meta/token-refresh', async (request, reply) => {
  454. const ws = request.workspaceId;
  455. const appCred = await getCredentials(ws, 'meta_app');
  456. if (!appCred?.appId || !appCred?.appSecret) {
  457. return reply.code(400).send({ success: false, error: 'Meta app credentials not configured' });
  458. }
  459. const plainAppSecret = decryptToken(appCred.appSecret);
  460. if (!plainAppSecret) {
  461. return reply.code(500).send({ success: false, error: 'Failed to decrypt app secret' });
  462. }
  463. const ig = await getCredentials(ws, 'instagram');
  464. const allAccounts = ig?.accounts || [];
  465. const selectedAccounts = allAccounts.filter((a) => a.selected && a.accessToken);
  466. if (!selectedAccounts.length) {
  467. return { success: true, refreshed: 0, skipped: 0, errors: 0 };
  468. }
  469. const appToken = `${appCred.appId}|${plainAppSecret}`;
  470. const refreshed = [];
  471. const skipped = [];
  472. const errors = [];
  473. for (const account of selectedAccounts) {
  474. const plainToken = decryptToken(account.accessToken);
  475. if (!plainToken) {
  476. errors.push({ username: account.username, error: 'decrypt_failed' });
  477. continue;
  478. }
  479. // Check current token expiry via debug_token
  480. let daysLeft = null;
  481. try {
  482. const debugRes = await axios.get(`${GRAPH_API}/debug_token`, {
  483. params: { input_token: plainToken, access_token: appToken },
  484. timeout: 10000,
  485. });
  486. const data = debugRes.data.data;
  487. if (!data.is_valid) {
  488. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'skip', reason: 'invalid_token' });
  489. errors.push({ username: account.username, error: 'token_invalid' });
  490. continue;
  491. }
  492. // expires_at is a Unix timestamp; null means never-expiring (page token etc.)
  493. daysLeft = data.expires_at
  494. ? Math.ceil((data.expires_at * 1000 - Date.now()) / (1000 * 60 * 60 * 24))
  495. : null;
  496. } catch (err) {
  497. app.log.warn({ action: 'token_refresh', platform: 'instagram', username: account.username, step: 'debug_token', outcome: 'failure', err: err.message });
  498. errors.push({ username: account.username, error: err.message });
  499. continue;
  500. }
  501. // Token never expires or has plenty of time — skip
  502. if (daysLeft !== null && daysLeft > TOKEN_REFRESH_THRESHOLD_DAYS) {
  503. skipped.push({ username: account.username, daysLeft });
  504. continue;
  505. }
  506. // Refresh: exchange current long-lived token for a new one
  507. try {
  508. const refreshRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  509. params: {
  510. grant_type: 'fb_exchange_token',
  511. client_id: appCred.appId,
  512. client_secret: plainAppSecret,
  513. fb_exchange_token: plainToken,
  514. },
  515. timeout: 15000,
  516. });
  517. // Mutates the element inside allAccounts (same object reference)
  518. account.accessToken = encryptToken(refreshRes.data.access_token);
  519. refreshed.push({ username: account.username, previousDaysLeft: daysLeft });
  520. app.log.info({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'success', previousDaysLeft: daysLeft });
  521. } catch (err) {
  522. app.log.error({ action: 'token_refresh', platform: 'instagram', username: account.username, outcome: 'failure', err: err.message });
  523. errors.push({ username: account.username, error: err.message });
  524. }
  525. }
  526. if (refreshed.length > 0) {
  527. await setCredentials(ws, 'instagram', { accounts: allAccounts });
  528. _tokenExpiryCache = null; // force fresh expiry check on next poll
  529. }
  530. app.log.info({ action: 'token_refresh', platform: 'meta', outcome: 'complete', refreshed: refreshed.length, skipped: skipped.length, errors: errors.length });
  531. return { success: true, refreshed: refreshed.length, skipped: skipped.length, errors: errors.length };
  532. });
  533. // ─── Account Profiles ────────────────────────────────────────────────────────
  534. app.get('/profiles', async (request) => {
  535. const ws = request.workspaceId;
  536. const db = await getDb();
  537. const profiles = await db.collection('account_profiles').find({ workspaceId: ws }).toArray();
  538. return { profiles };
  539. });
  540. app.get('/profiles/:accountKey', async (request, reply) => {
  541. const ws = request.workspaceId;
  542. const { accountKey } = request.params;
  543. const db = await getDb();
  544. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  545. return profile ?? { _id: accountKey };
  546. });
  547. app.put('/profiles/:accountKey', async (request, reply) => {
  548. const ws = request.workspaceId;
  549. const { accountKey } = request.params;
  550. const {
  551. businessName = '', description = '', websiteUrl = '', industry = '',
  552. targetAudience = '', toneOfVoice = '', keywords = '', hashtags = '',
  553. postingGuidelines = '',
  554. } = request.body || {};
  555. const db = await getDb();
  556. await db.collection('account_profiles').updateOne(
  557. { _id: accountKey },
  558. { $set: { businessName, description, websiteUrl, industry, targetAudience, toneOfVoice, keywords, hashtags, postingGuidelines, workspaceId: ws, updatedAt: new Date() } },
  559. { upsert: true }
  560. );
  561. return { success: true };
  562. });
  563. // Strategy consistency audit — check if a profile's fields are internally coherent
  564. app.post('/profiles/:accountKey/audit', async (request, reply) => {
  565. const ws = request.workspaceId;
  566. const { accountKey } = request.params;
  567. const db = await getDb();
  568. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  569. if (!profile) return reply.code(404).send({ error: 'Profile not found' });
  570. const filled = [
  571. profile.businessName, profile.description, profile.industry,
  572. profile.toneOfVoice, profile.targetAudience, profile.keywords,
  573. profile.hashtags, profile.postingGuidelines,
  574. ].filter(Boolean);
  575. if (filled.length < 3) {
  576. return reply.code(400).send({ error: 'Fill in at least 3 profile fields before running an audit' });
  577. }
  578. const profileBlock = [
  579. profile.businessName && `Business: ${profile.businessName}`,
  580. profile.description && `Description: ${profile.description}`,
  581. profile.industry && `Industry: ${profile.industry}`,
  582. profile.toneOfVoice && `Tone of voice: ${profile.toneOfVoice}`,
  583. profile.targetAudience && `Target audience: ${profile.targetAudience}`,
  584. profile.keywords && `Keywords: ${profile.keywords}`,
  585. profile.hashtags && `Preferred hashtags: ${profile.hashtags}`,
  586. profile.postingGuidelines && `Posting guidelines: ${profile.postingGuidelines}`,
  587. ].filter(Boolean).join('\n');
  588. const system = 'You are a brand strategy consultant. Return only valid JSON with no explanation, no markdown code blocks.';
  589. const prompt = `Audit the internal consistency of this social media account profile and identify any conflicts or misalignments.
  590. PROFILE:
  591. ${profileBlock}
  592. Check for these issues:
  593. 1. Audience-tone mismatch (e.g. B2B business using casual/Gen-Z tone)
  594. 2. Industry-keyword misalignment (keywords don't reflect stated industry)
  595. 3. Hashtag-audience misalignment (hashtags target a different audience than described)
  596. 4. Tone-guideline conflicts (tone of voice contradicts posting guidelines)
  597. 5. Missing critical context (fields that are vague and would hurt AI content quality)
  598. Return a JSON object:
  599. {
  600. "score": <consistency score 0-100>,
  601. "summary": "<2-3 sentence overall assessment>",
  602. "issues": [
  603. { "severity": "<high|medium|low>", "field": "<which field(s)>", "issue": "<what the conflict is>", "fix": "<specific recommendation>" }
  604. ],
  605. "strengths": ["<1-3 things the profile does well>"]
  606. }
  607. Return [] for issues if no problems found. Return ONLY the JSON object.`;
  608. try {
  609. const pconf = await getActiveProviderConfig(request.workspaceId);
  610. const model = pconf.model;
  611. let text = '';
  612. if (pconf.provider === 'ollama') {
  613. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  614. text = res.data.response;
  615. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  616. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  617. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  618. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  619. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  620. text = res.data.choices[0]?.message?.content || '';
  621. } else if (pconf.provider === 'gemini') {
  622. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  623. const res = await axios.post(
  624. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  625. { contents: buildGeminiContents(prompt, system) },
  626. { timeout: 90000 },
  627. );
  628. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  629. } else {
  630. return reply.code(400).send({ error: 'AI not configured' });
  631. }
  632. let result = null;
  633. try {
  634. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  635. result = JSON.parse(jsonStr);
  636. if (typeof result.score !== 'number') throw new Error();
  637. if (!Array.isArray(result.issues)) result.issues = [];
  638. if (!Array.isArray(result.strengths)) result.strengths = [];
  639. } catch {
  640. return reply.code(503).send({ error: 'AI returned invalid audit format — try again' });
  641. }
  642. log.info({ action: 'profile_audit', accountKey, score: result.score, issues: result.issues.length, outcome: 'success' });
  643. return { success: true, ...result };
  644. } catch (err) {
  645. return reply.code(503).send({ error: 'Profile audit failed', detail: err.message });
  646. }
  647. });
  648. // ─── AI / Multi-provider ─────────────────────────────────────────────────────
  649. const DEFAULT_OLLAMA_ENDPOINT = process.env.OLLAMA_ENDPOINT || 'http://ollama:11434';
  650. const DEFAULT_OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'llama3.2';
  651. const PROVIDER_MODELS = {
  652. openai: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-3.5-turbo'],
  653. groq: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768', 'gemma2-9b-it'],
  654. gemini: ['gemini-2.0-flash', 'gemini-1.5-flash', 'gemini-1.5-pro'],
  655. };
  656. const PROVIDER_BASE_URLS = {
  657. openai: 'https://api.openai.com/v1',
  658. groq: 'https://api.groq.com/openai/v1',
  659. };
  660. // Returns decrypted runtime config for the currently active provider
  661. async function getActiveProviderConfig(ws = 'default') {
  662. const aiConfig = await getCredentials(ws, 'ai_config');
  663. const provider = aiConfig?.provider || 'ollama';
  664. if (provider === 'openai' || provider === 'groq') {
  665. const doc = await getCredentials(ws, `${provider}_config`);
  666. return {
  667. provider,
  668. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  669. model: doc?.model || PROVIDER_MODELS[provider][0],
  670. baseUrl: PROVIDER_BASE_URLS[provider],
  671. };
  672. }
  673. if (provider === 'gemini') {
  674. const doc = await getCredentials(ws, 'gemini_config');
  675. return {
  676. provider,
  677. apiKey: doc?.apiKey ? decryptToken(doc.apiKey) : null,
  678. model: doc?.model || PROVIDER_MODELS.gemini[0],
  679. };
  680. }
  681. return {
  682. provider: 'ollama',
  683. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  684. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  685. visionModel: aiConfig?.visionModel || 'llava',
  686. };
  687. }
  688. function buildOpenAIMessages(prompt, system) {
  689. const messages = [];
  690. if (system) messages.push({ role: 'system', content: system });
  691. messages.push({ role: 'user', content: prompt });
  692. return messages;
  693. }
  694. // Gemini encodes system as a leading user/model conversation pair
  695. function buildGeminiContents(prompt, system) {
  696. const contents = [];
  697. if (system) {
  698. contents.push({ role: 'user', parts: [{ text: system }] });
  699. contents.push({ role: 'model', parts: [{ text: 'Understood.' }] });
  700. }
  701. contents.push({ role: 'user', parts: [{ text: prompt }] });
  702. return contents;
  703. }
  704. app.get('/ai/config', async (request) => {
  705. const ws = request.workspaceId;
  706. const config = await getCredentials(ws, 'ai_config');
  707. return {
  708. provider: config?.provider || 'ollama',
  709. endpoint: config?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  710. model: config?.model || DEFAULT_OLLAMA_MODEL,
  711. visionModel: config?.visionModel || 'llava',
  712. enabled: config?.enabled ?? true,
  713. };
  714. });
  715. app.put('/ai/config', async (request, reply) => {
  716. const ws = request.workspaceId;
  717. const { provider = 'ollama', endpoint, model, visionModel = 'llava', enabled = true } = request.body || {};
  718. if (provider === 'ollama' && !endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  719. await setCredentials(ws, 'ai_config', { provider, endpoint, model, visionModel, enabled });
  720. return { success: true };
  721. });
  722. // ─── Provider management routes ───────────────────────────────────────────────
  723. app.get('/ai/providers', async (request) => {
  724. const ws = request.workspaceId;
  725. const aiConfig = await getCredentials(ws, 'ai_config');
  726. const active = aiConfig?.provider || 'ollama';
  727. const [openaiDoc, groqDoc, geminiDoc] = await Promise.all([
  728. getCredentials(ws, 'openai_config'),
  729. getCredentials(ws, 'groq_config'),
  730. getCredentials(ws, 'gemini_config'),
  731. ]);
  732. return {
  733. active,
  734. providers: [
  735. {
  736. name: 'ollama',
  737. configured: true,
  738. active: active === 'ollama',
  739. endpoint: aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT,
  740. model: aiConfig?.model || DEFAULT_OLLAMA_MODEL,
  741. visionModel: aiConfig?.visionModel || 'llava',
  742. },
  743. {
  744. name: 'openai',
  745. configured: !!openaiDoc?.apiKey,
  746. active: active === 'openai',
  747. model: openaiDoc?.model || PROVIDER_MODELS.openai[0],
  748. apiKeyHint: openaiDoc?.apiKey ? `sk-...${decryptToken(openaiDoc.apiKey).slice(-4)}` : null,
  749. },
  750. {
  751. name: 'groq',
  752. configured: !!groqDoc?.apiKey,
  753. active: active === 'groq',
  754. model: groqDoc?.model || PROVIDER_MODELS.groq[0],
  755. apiKeyHint: groqDoc?.apiKey ? `gsk_...${decryptToken(groqDoc.apiKey).slice(-4)}` : null,
  756. },
  757. {
  758. name: 'gemini',
  759. configured: !!geminiDoc?.apiKey,
  760. active: active === 'gemini',
  761. model: geminiDoc?.model || PROVIDER_MODELS.gemini[0],
  762. apiKeyHint: geminiDoc?.apiKey ? `AIza...${decryptToken(geminiDoc.apiKey).slice(-4)}` : null,
  763. },
  764. ],
  765. };
  766. });
  767. // PUT /ai/provider/:name — save credentials and optionally set as active
  768. // ollama body: { endpoint, model, visionModel, setActive? }
  769. // others body: { apiKey, model, setActive? }
  770. app.put('/ai/provider/:name', async (request, reply) => {
  771. const ws = request.workspaceId;
  772. const { name } = request.params;
  773. const { apiKey, model, endpoint, visionModel, setActive = false } = request.body || {};
  774. if (name === 'ollama') {
  775. if (!endpoint) return reply.code(400).send({ error: 'endpoint is required for Ollama' });
  776. const existing = await getCredentials(ws, 'ai_config') || {};
  777. await setCredentials(ws, 'ai_config', {
  778. ...existing,
  779. provider: setActive ? 'ollama' : (existing.provider || 'ollama'),
  780. endpoint,
  781. model: model || DEFAULT_OLLAMA_MODEL,
  782. visionModel: visionModel || 'llava',
  783. });
  784. } else if (['openai', 'groq', 'gemini'].includes(name)) {
  785. if (!apiKey) return reply.code(400).send({ error: 'apiKey is required' });
  786. await setCredentials(ws, `${name}_config`, {
  787. apiKey: encryptToken(apiKey),
  788. model: model || PROVIDER_MODELS[name][0],
  789. });
  790. if (setActive) {
  791. const existing = await getCredentials(ws, 'ai_config') || {};
  792. await setCredentials(ws, 'ai_config', { ...existing, provider: name });
  793. }
  794. } else {
  795. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  796. }
  797. return { success: true };
  798. });
  799. // DELETE /ai/provider/:name — remove provider credentials; falls back to ollama if it was active
  800. app.delete('/ai/provider/:name', async (request, reply) => {
  801. const ws = request.workspaceId;
  802. const { name } = request.params;
  803. if (name === 'ollama') return reply.code(400).send({ error: 'Cannot remove Ollama provider' });
  804. if (!['openai', 'groq', 'gemini'].includes(name)) return reply.code(404).send({ error: `Unknown provider: ${name}` });
  805. await deleteCredentials(ws, `${name}_config`);
  806. const aiConfig = await getCredentials(ws, 'ai_config') || {};
  807. if (aiConfig.provider === name) {
  808. await setCredentials(ws, 'ai_config', { ...aiConfig, provider: 'ollama' });
  809. }
  810. return { success: true };
  811. });
  812. // POST /ai/provider/:name/models — list models for a provider (test without saving key)
  813. app.post('/ai/provider/:name/models', async (request, reply) => {
  814. const ws = request.workspaceId;
  815. const { name } = request.params;
  816. const { apiKey: bodyApiKey, endpoint: bodyEndpoint } = request.body || {};
  817. if (name === 'ollama') {
  818. const aiConfig = await getCredentials(ws, 'ai_config');
  819. const ep = bodyEndpoint || aiConfig?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  820. try {
  821. const res = await axios.get(`${ep}/api/tags`, { timeout: 5000 });
  822. return { models: (res.data.models || []).map((m) => m.name) };
  823. } catch (err) {
  824. return reply.code(503).send({ error: 'Could not reach Ollama', detail: err.message });
  825. }
  826. }
  827. if (['openai', 'groq', 'gemini'].includes(name)) {
  828. return { models: PROVIDER_MODELS[name] };
  829. }
  830. return reply.code(404).send({ error: `Unknown provider: ${name}` });
  831. });
  832. app.get('/ai/models', async (request, reply) => {
  833. const ws = request.workspaceId;
  834. const config = await getCredentials(ws, 'ai_config');
  835. const provider = config?.provider || 'ollama';
  836. if (provider !== 'ollama') {
  837. return { models: PROVIDER_MODELS[provider] || [], provider };
  838. }
  839. const endpoint = request.query.endpoint || config?.endpoint || DEFAULT_OLLAMA_ENDPOINT;
  840. try {
  841. const res = await axios.get(`${endpoint}/api/tags`, { timeout: 5000 });
  842. const models = (res.data.models || []).map((m) => m.name);
  843. return { models, endpoint };
  844. } catch (err) {
  845. return reply.code(503).send({ error: 'Could not reach Ollama — check the endpoint', detail: err.message });
  846. }
  847. });
  848. // ─── Community Research ───────────────────────────────────────────────────────
  849. async function fetchRedditSnippets(query, limit = 5) {
  850. try {
  851. const res = await axios.get(
  852. `https://www.reddit.com/search.json?q=${encodeURIComponent(query)}&sort=hot&limit=${limit}&t=month`,
  853. { headers: { 'User-Agent': 'SocialManager/1.0 (research bot)' }, timeout: 8000 },
  854. );
  855. return (res.data?.data?.children || [])
  856. .map((p) => p.data)
  857. .filter((d) => d.title)
  858. .map((d) => `"${d.title}": ${(d.selftext || d.url || '').slice(0, 180)}`);
  859. } catch { return []; }
  860. }
  861. // POST /ai/research — scrape Reddit for industry/keyword discussions, AI-summarise into brief
  862. // Stores researchBrief + researchBriefAt on account_profiles
  863. app.post('/ai/research', async (request, reply) => {
  864. const ws = request.workspaceId;
  865. const { accountKey, topics } = request.body || {};
  866. const db = await getDb();
  867. const profileKey = accountKey || null;
  868. const profile = profileKey
  869. ? (await db.collection('account_profiles').findOne({ _id: profileKey, workspaceId: ws }))
  870. || (await db.collection('account_profiles').findOne({ workspaceId: ws }))
  871. : await db.collection('account_profiles').findOne({ workspaceId: ws });
  872. const industry = profile?.industry || '';
  873. const keywords = profile?.keywords || '';
  874. const businessName = profile?.businessName || '';
  875. const extraTopics = Array.isArray(topics) ? topics.slice(0, 3) : [];
  876. // Build 3 search queries from profile context
  877. const queries = [
  878. industry ? `${industry} challenges pain points` : null,
  879. keywords ? `${keywords} community discussion` : null,
  880. businessName ? `${businessName} competitors alternatives` : null,
  881. ...extraTopics.map((t) => String(t)),
  882. ].filter(Boolean).slice(0, 4);
  883. if (!queries.length) return reply.code(400).send({ error: 'No research context — fill in Industry or Keywords in your Account Profile first' });
  884. const snippets = [];
  885. await Promise.all(queries.map(async (q) => {
  886. const results = await fetchRedditSnippets(q, 5);
  887. snippets.push(...results);
  888. }));
  889. if (!snippets.length) {
  890. return reply.code(503).send({ error: 'Could not fetch community data — Reddit may be temporarily unavailable' });
  891. }
  892. const system = 'You are an audience research analyst. Return ONLY valid JSON — no markdown, no explanation.';
  893. const prompt = `Based on these community discussions about "${industry || keywords || businessName}":
  894. ${snippets.slice(0, 20).map((s, i) => `${i + 1}. ${s}`).join('\n')}
  895. Extract a research brief with these exact fields:
  896. {
  897. "painPoints": ["<3-5 real audience frustrations or challenges found in the discussions>"],
  898. "trendingTopics": ["<3-5 topics the community is actively discussing right now>"],
  899. "communityLanguage": ["<5-8 exact phrases, words, or terms the audience uses — quote them>"],
  900. "contentAngles": ["<3-5 specific post angles that would resonate based on what you found>"]
  901. }
  902. Return ONLY the JSON object.`;
  903. try {
  904. const pconf = await getActiveProviderConfig(request.workspaceId);
  905. const model = pconf.model;
  906. let text = '';
  907. if (pconf.provider === 'ollama') {
  908. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  909. text = res.data.response;
  910. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  911. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  912. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  913. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  914. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  915. text = res.data.choices[0]?.message?.content || '';
  916. } else if (pconf.provider === 'gemini') {
  917. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  918. const res = await axios.post(
  919. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  920. { contents: buildGeminiContents(prompt, system) }, { timeout: 60000 },
  921. );
  922. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  923. } else {
  924. return reply.code(400).send({ error: 'AI not configured' });
  925. }
  926. let brief = null;
  927. try {
  928. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  929. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  930. brief = JSON.parse(jsonStr);
  931. if (!brief.painPoints) throw new Error('Missing painPoints');
  932. } catch {
  933. return reply.code(503).send({ error: 'AI returned invalid research format — try again' });
  934. }
  935. const updatedAt = new Date();
  936. if (profileKey) {
  937. await db.collection('account_profiles').updateOne(
  938. { _id: profileKey, workspaceId: ws },
  939. { $set: { researchBrief: brief, researchBriefAt: updatedAt } },
  940. { upsert: false },
  941. );
  942. }
  943. log.info({ action: 'ai_research', accountKey: profileKey || 'any', snippets: snippets.length, outcome: 'success' });
  944. return { brief, accountKey: profileKey, updatedAt };
  945. } catch (err) {
  946. log.error({ action: 'ai_research', outcome: 'failure', err: err.message });
  947. return reply.code(503).send({ error: `Research failed: ${err.message}` });
  948. }
  949. });
  950. // Helper: inject research brief into a system prompt when available
  951. async function buildResearchBriefSuffix(accountKey, ws = 'default') {
  952. if (!accountKey) return '';
  953. try {
  954. const db = await getDb();
  955. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  956. const b = profile?.researchBrief;
  957. if (!b) return '';
  958. const parts = [];
  959. if (b.painPoints?.length) parts.push(`Audience pain points: ${b.painPoints.join('; ')}`);
  960. if (b.trendingTopics?.length) parts.push(`Trending topics right now: ${b.trendingTopics.join('; ')}`);
  961. if (b.communityLanguage?.length) parts.push(`Language the audience uses: ${b.communityLanguage.join(', ')}`);
  962. if (b.contentAngles?.length) parts.push(`Proven content angles: ${b.contentAngles.join('; ')}`);
  963. if (!parts.length) return '';
  964. return '\n\nAUDIENCE RESEARCH CONTEXT (use this to make the post feel native to the community):\n' + parts.join('\n');
  965. } catch { return ''; }
  966. }
  967. app.post('/ai/generate', async (request, reply) => {
  968. const ws = request.workspaceId;
  969. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext, useResearchBrief, accountKey, destinations } = request.body || {};
  970. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  971. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix(ws) : '';
  972. const researchSuffix = useResearchBrief ? await buildResearchBriefSuffix(accountKey, ws) : '';
  973. const platformRules = buildPlatformRulesBlock(destinations);
  974. const system = rawSystem ? rawSystem + competitorSuffix + researchSuffix + platformRules : ((competitorSuffix + researchSuffix + platformRules) || undefined);
  975. const pconf = await getActiveProviderConfig(request.workspaceId);
  976. const model = reqModel || pconf.model;
  977. try {
  978. if (pconf.provider === 'ollama') {
  979. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  980. return { text: res.data.response, model, done: res.data.done };
  981. }
  982. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  983. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  984. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  985. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  986. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  987. return { text: res.data.choices[0]?.message?.content || '', model, done: true };
  988. }
  989. if (pconf.provider === 'gemini') {
  990. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  991. const res = await axios.post(
  992. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  993. { contents: buildGeminiContents(prompt, system) },
  994. { timeout: 90000 },
  995. );
  996. return { text: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model, done: true };
  997. }
  998. return reply.code(400).send({ error: `Unknown provider: ${pconf.provider}` });
  999. } catch (err) {
  1000. const status = err.response?.status || 503;
  1001. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  1002. }
  1003. });
  1004. const CAPTION_PROMPT = 'Generate an engaging, concise social media caption for this image. Write only the caption text with relevant hashtags. No explanations or preamble.';
  1005. // Vision caption — supports ollama, openai, gemini (groq has no vision)
  1006. app.post('/ai/caption', async (request, reply) => {
  1007. const { imageUrl, model: reqModel } = request.body || {};
  1008. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  1009. const pconf = await getActiveProviderConfig(request.workspaceId);
  1010. let imageBase64, imageMime;
  1011. try {
  1012. let imageBuffer;
  1013. if (imageUrl.startsWith('/media/')) {
  1014. const filename = path.basename(imageUrl);
  1015. imageBuffer = fs.readFileSync(path.join(UPLOAD_DIR, filename));
  1016. } else {
  1017. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  1018. imageBuffer = Buffer.from(imgRes.data);
  1019. imageMime = imgRes.headers['content-type'] || 'image/jpeg';
  1020. }
  1021. imageBase64 = imageBuffer.toString('base64');
  1022. if (!imageMime) imageMime = 'image/jpeg';
  1023. } catch (err) {
  1024. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  1025. }
  1026. try {
  1027. const model = reqModel || pconf.visionModel || pconf.model;
  1028. if (pconf.provider === 'ollama') {
  1029. const res = await axios.post(`${pconf.endpoint}/api/generate`, {
  1030. model, prompt: CAPTION_PROMPT, images: [imageBase64], stream: false,
  1031. }, { timeout: 90000 });
  1032. return { caption: res.data.response, model };
  1033. }
  1034. if (pconf.provider === 'openai') {
  1035. if (!pconf.apiKey) return reply.code(503).send({ error: 'OpenAI API key not configured' });
  1036. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1037. model: model || 'gpt-4o',
  1038. messages: [{ role: 'user', content: [
  1039. { type: 'text', text: CAPTION_PROMPT },
  1040. { type: 'image_url', image_url: { url: `data:${imageMime};base64,${imageBase64}` } },
  1041. ]}],
  1042. stream: false,
  1043. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  1044. return { caption: res.data.choices[0]?.message?.content || '', model };
  1045. }
  1046. if (pconf.provider === 'gemini') {
  1047. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  1048. const geminiModel = model || 'gemini-1.5-flash';
  1049. const res = await axios.post(
  1050. `https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent?key=${pconf.apiKey}`,
  1051. { contents: [{ role: 'user', parts: [
  1052. { text: CAPTION_PROMPT },
  1053. { inlineData: { mimeType: imageMime, data: imageBase64 } },
  1054. ]}]},
  1055. { timeout: 90000 },
  1056. );
  1057. return { caption: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model: geminiModel };
  1058. }
  1059. return reply.code(400).send({ error: `Provider ${pconf.provider} does not support vision captions` });
  1060. } catch (err) {
  1061. const status = err.response?.status || 503;
  1062. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  1063. }
  1064. });
  1065. // SSE streaming endpoint — normalized data: { token, done } format for all providers
  1066. app.post('/ai/stream', async (request, reply) => {
  1067. const ws = request.workspaceId;
  1068. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext, useResearchBrief, accountKey, destinations } = request.body || {};
  1069. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  1070. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix(ws) : '';
  1071. const researchSuffix = useResearchBrief ? await buildResearchBriefSuffix(accountKey, ws) : '';
  1072. const platformRules = buildPlatformRulesBlock(destinations);
  1073. const system = rawSystem ? rawSystem + competitorSuffix + researchSuffix + platformRules : ((competitorSuffix + researchSuffix + platformRules) || undefined);
  1074. const pconf = await getActiveProviderConfig(request.workspaceId);
  1075. const model = reqModel || pconf.model;
  1076. reply.raw.setHeader('Content-Type', 'text/event-stream');
  1077. reply.raw.setHeader('Cache-Control', 'no-cache');
  1078. reply.raw.setHeader('X-Accel-Buffering', 'no');
  1079. reply.raw.setHeader('Connection', 'keep-alive');
  1080. reply.raw.flushHeaders();
  1081. const writeToken = (token, done = false) => reply.raw.write(`data: ${JSON.stringify({ token, done })}\n\n`);
  1082. const writeError = (msg) => { reply.raw.write(`data: ${JSON.stringify({ error: msg, done: true })}\n\n`); reply.raw.end(); };
  1083. try {
  1084. if (pconf.provider === 'ollama') {
  1085. const ollamaRes = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  1086. ollamaRes.data.on('data', (chunk) => {
  1087. try {
  1088. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  1089. const data = JSON.parse(line);
  1090. writeToken(data.response || '', !!data.done);
  1091. }
  1092. } catch (_) {}
  1093. });
  1094. ollamaRes.data.on('end', () => reply.raw.end());
  1095. ollamaRes.data.on('error', (err) => writeError(err.message));
  1096. return;
  1097. }
  1098. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1099. if (!pconf.apiKey) return writeError(`${pconf.provider} API key not configured`);
  1100. const upstreamRes = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1101. model, messages: buildOpenAIMessages(prompt, system), stream: true,
  1102. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, responseType: 'stream', timeout: 120000 });
  1103. upstreamRes.data.on('data', (chunk) => {
  1104. try {
  1105. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  1106. if (!line.startsWith('data: ')) continue;
  1107. const payload = line.slice(6).trim();
  1108. if (payload === '[DONE]') { writeToken('', true); return; }
  1109. const data = JSON.parse(payload);
  1110. const token = data.choices?.[0]?.delta?.content || '';
  1111. if (token) writeToken(token);
  1112. }
  1113. } catch (_) {}
  1114. });
  1115. upstreamRes.data.on('end', () => reply.raw.end());
  1116. upstreamRes.data.on('error', (err) => writeError(err.message));
  1117. return;
  1118. }
  1119. if (pconf.provider === 'gemini') {
  1120. if (!pconf.apiKey) return writeError('Gemini API key not configured');
  1121. const geminiRes = await axios.post(
  1122. `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${pconf.apiKey}`,
  1123. { contents: buildGeminiContents(prompt, system) },
  1124. { responseType: 'stream', timeout: 120000 },
  1125. );
  1126. geminiRes.data.on('data', (chunk) => {
  1127. try {
  1128. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  1129. if (!line.startsWith('data: ')) continue;
  1130. const data = JSON.parse(line.slice(6));
  1131. const token = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1132. if (token) writeToken(token);
  1133. }
  1134. } catch (_) {}
  1135. });
  1136. geminiRes.data.on('end', () => { writeToken('', true); reply.raw.end(); });
  1137. geminiRes.data.on('error', (err) => writeError(err.message));
  1138. return;
  1139. }
  1140. writeError(`Unknown provider: ${pconf.provider}`);
  1141. } catch (err) {
  1142. writeError(err.message);
  1143. }
  1144. });
  1145. // ─── Monthly Content Calendar ─────────────────────────────────────────────────
  1146. // POST /ai/content-brief — generate a narrative brief only (step 1 of 2-step calendar flow)
  1147. // Body: { accountKey?, platforms[], month? (YYYY-MM) }
  1148. app.post('/ai/content-brief', async (request, reply) => {
  1149. const ws = request.workspaceId;
  1150. const { accountKey, platforms = [], month } = request.body || {};
  1151. if (!platforms.length) return reply.code(400).send({ error: 'Select at least one platform' });
  1152. const db = await getDb();
  1153. const calMonth = month || new Date().toISOString().slice(0, 7);
  1154. const monthName = new Date(`${calMonth}-01`).toLocaleString('en', { month: 'long', year: 'numeric' });
  1155. const profileKey = accountKey || null;
  1156. const profile = profileKey
  1157. ? (await db.collection('account_profiles').findOne({ _id: profileKey, workspaceId: ws }))
  1158. || (await db.collection('account_profiles').findOne({ workspaceId: ws }))
  1159. : await db.collection('account_profiles').findOne({ workspaceId: ws });
  1160. const contextParts = [];
  1161. if (profile) {
  1162. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  1163. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  1164. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  1165. if (profile.toneOfVoice) contextParts.push(`Tone: ${profile.toneOfVoice}`);
  1166. if (profile.targetAudience) contextParts.push(`Audience: ${profile.targetAudience}`);
  1167. if (profile.keywords) contextParts.push(`Keywords: ${profile.keywords}`);
  1168. }
  1169. const platformList = platforms.slice(0, 5).join(', ');
  1170. const platformNoteKeys = platforms.slice(0, 5).map((p) => `"${p}": "<one-sentence strategy>"`).join(', ');
  1171. const system = 'You are a social media content strategist. Return ONLY a valid JSON object with no markdown or explanation.';
  1172. const prompt = `${contextParts.length ? contextParts.join('\n') + '\n\n' : ''}Create a brief for the ${monthName} content calendar. Platforms: ${platformList}.
  1173. Return this exact JSON:
  1174. {
  1175. "theme": "<one compelling sentence that defines the month's narrative — the red thread across all content>",
  1176. "pillars": ["<content pillar 1>", "<content pillar 2>", "<content pillar 3>"],
  1177. "toneGuidance": "<one sentence describing the voice and energy for this month>",
  1178. "platformNotes": { ${platformNoteKeys} }
  1179. }
  1180. Return ONLY valid JSON.`;
  1181. try {
  1182. const pconf = await getActiveProviderConfig(request.workspaceId);
  1183. const model = pconf.model;
  1184. let text = '';
  1185. if (pconf.provider === 'ollama') {
  1186. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  1187. text = res.data.response;
  1188. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1189. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  1190. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1191. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1192. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  1193. text = res.data.choices[0]?.message?.content || '';
  1194. } else if (pconf.provider === 'gemini') {
  1195. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  1196. const res = await axios.post(
  1197. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1198. { contents: buildGeminiContents(prompt, system) },
  1199. { timeout: 90000 },
  1200. );
  1201. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1202. } else {
  1203. return reply.code(400).send({ error: 'AI not configured' });
  1204. }
  1205. let brief = null;
  1206. try {
  1207. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  1208. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  1209. brief = JSON.parse(jsonStr);
  1210. if (typeof brief.theme !== 'string' || !brief.theme) throw new Error('Missing theme');
  1211. if (!Array.isArray(brief.pillars)) brief.pillars = [];
  1212. } catch {
  1213. return reply.code(503).send({ error: 'AI returned invalid brief format — try again' });
  1214. }
  1215. log.info({ action: 'content_brief', month: calMonth, platforms: platforms.join(','), outcome: 'success' });
  1216. return { success: true, brief, monthName, month: calMonth };
  1217. } catch (err) {
  1218. log.error({ action: 'content_brief', outcome: 'failure', err: err.message });
  1219. return reply.code(503).send({ error: `Brief generation failed: ${err.message}` });
  1220. }
  1221. });
  1222. // POST /ai/content-calendar — generate a monthly content plan with narrative brief + sample posts
  1223. // Body: { accountKey?, platforms[], month? (YYYY-MM), approvedBrief? }
  1224. app.post('/ai/content-calendar', async (request, reply) => {
  1225. const ws = request.workspaceId;
  1226. const { accountKey, platforms = [], month, approvedBrief } = request.body || {};
  1227. if (!platforms.length) return reply.code(400).send({ error: 'Select at least one platform' });
  1228. const db = await getDb();
  1229. const calMonth = month || new Date().toISOString().slice(0, 7);
  1230. const [year, mon] = calMonth.split('-');
  1231. const monthName = new Date(`${calMonth}-01`).toLocaleString('en', { month: 'long', year: 'numeric' });
  1232. // Load account profile for context
  1233. const profileKey = accountKey || null;
  1234. const profile = profileKey
  1235. ? (await db.collection('account_profiles').findOne({ _id: profileKey, workspaceId: ws }))
  1236. || (await db.collection('account_profiles').findOne({ workspaceId: ws }))
  1237. : await db.collection('account_profiles').findOne({ workspaceId: ws });
  1238. const contextParts = ['You are a social media content strategist.'];
  1239. if (profile) {
  1240. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  1241. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  1242. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  1243. if (profile.toneOfVoice) contextParts.push(`Tone of voice: ${profile.toneOfVoice}`);
  1244. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  1245. if (profile.keywords) contextParts.push(`Keywords: ${profile.keywords}`);
  1246. }
  1247. const brandContext = contextParts.join('\n');
  1248. const activePlatforms = platforms.slice(0, 5);
  1249. const platformList = activePlatforms.join(', ');
  1250. const postsPerPlatform = 2;
  1251. const totalPosts = activePlatforms.length * postsPerPlatform;
  1252. const system = 'You are a social media content strategist. Return ONLY a valid JSON object — no markdown, no explanation, no code fences.';
  1253. const platformNoteKeys = activePlatforms.map((p) => `"${p}"`).join(', ');
  1254. const postSchema = `{ "platform": "<one of: ${platformList}>", "week": <1 or 2>, "content": "<ready-to-publish post>", "hashtags": ["<tag>"], "postType": "<educational|promotional|engagement|storytelling>", "suggestedDay": "<day>" }`;
  1255. // If an approved brief was passed, use it directly — only generate posts
  1256. const briefSection = approvedBrief
  1257. ? `The content brief has already been approved — do NOT change it. Use this brief exactly:
  1258. Theme: "${approvedBrief.theme}"
  1259. Pillars: ${(approvedBrief.pillars || []).join(', ')}
  1260. Tone: ${approvedBrief.toneGuidance || ''}
  1261. Generate posts that faithfully follow this approved brief.`
  1262. : '';
  1263. const prompt = `${brandContext}
  1264. ${briefSection}
  1265. Create a ${monthName} content calendar for: ${platformList}.
  1266. Generate ${postsPerPlatform} posts per platform (${totalPosts} posts total across weeks 1 and 2).
  1267. Platform conventions to follow:
  1268. - LinkedIn: professional hook in first line, insights, 1300-char max
  1269. - Instagram: visual-first, emojis ok, 2200-char max, 5-10 hashtags
  1270. - Facebook: conversational, question or story, 500-char ideal
  1271. - Twitter: concise, punchy, under 280 chars
  1272. - TikTok: caption hook in first 3 words, trending angle
  1273. - Pinterest: keyword-rich description, action-oriented
  1274. - Mastodon/Bluesky: authentic, community-focused, 300/500 chars
  1275. Return a single JSON object:
  1276. {
  1277. "brief": ${approvedBrief ? JSON.stringify(approvedBrief) : `{
  1278. "theme": "<one-sentence monthly narrative>",
  1279. "pillars": ["<pillar 1>", "<pillar 2>", "<pillar 3>"],
  1280. "toneGuidance": "<one sentence>",
  1281. "platformNotes": { ${platformNoteKeys.split(', ').map((k) => `${k}: "<strategy>"`).join(', ')} }
  1282. }`},
  1283. "posts": [<${totalPosts} post objects using schema: ${postSchema}>]
  1284. }
  1285. Return ONLY the JSON object.`;
  1286. try {
  1287. const pconf = await getActiveProviderConfig(request.workspaceId);
  1288. const model = pconf.model;
  1289. let text = '';
  1290. if (pconf.provider === 'ollama') {
  1291. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  1292. text = res.data.response;
  1293. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1294. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  1295. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1296. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1297. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  1298. text = res.data.choices[0]?.message?.content || '';
  1299. } else if (pconf.provider === 'gemini') {
  1300. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  1301. const res = await axios.post(
  1302. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1303. { contents: buildGeminiContents(prompt, system) },
  1304. { timeout: 180000 },
  1305. );
  1306. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1307. } else {
  1308. return reply.code(400).send({ error: 'AI not configured' });
  1309. }
  1310. let calendar = null;
  1311. try {
  1312. // Strip markdown code fences if present
  1313. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  1314. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  1315. calendar = JSON.parse(jsonStr);
  1316. if (!calendar.brief || !Array.isArray(calendar.posts)) throw new Error('Missing brief or posts array');
  1317. if (!Array.isArray(calendar.brief.pillars)) calendar.brief.pillars = [];
  1318. if (typeof calendar.brief.theme !== 'string') calendar.brief.theme = '';
  1319. calendar.posts = calendar.posts.filter((p) => p && typeof p.content === 'string').slice(0, totalPosts);
  1320. if (calendar.posts.length === 0) throw new Error('No valid posts in response');
  1321. } catch (parseErr) {
  1322. log.warn({ action: 'content_calendar', outcome: 'parse_failure', err: parseErr.message });
  1323. return reply.code(503).send({ error: 'AI returned invalid calendar format — try again or use a more capable model' });
  1324. }
  1325. const doc = {
  1326. accountKey: accountKey || null,
  1327. month: calMonth,
  1328. monthName,
  1329. platforms,
  1330. brief: calendar.brief,
  1331. posts: calendar.posts,
  1332. workspaceId: ws,
  1333. createdAt: new Date(),
  1334. };
  1335. const result = await db.collection('content_calendars').insertOne(doc);
  1336. log.info({ action: 'content_calendar', month: calMonth, platforms: platforms.join(','), posts: calendar.posts.length, outcome: 'success' });
  1337. return { success: true, calendarId: result.insertedId.toString(), ...doc };
  1338. } catch (err) {
  1339. log.error({ action: 'content_calendar', outcome: 'failure', err: err.message });
  1340. return reply.code(503).send({ error: `Calendar generation failed: ${err.message}` });
  1341. }
  1342. });
  1343. // GET /ai/content-calendar/:id — retrieve a saved calendar
  1344. app.get('/ai/content-calendar/:id', async (request, reply) => {
  1345. const ws = request.workspaceId;
  1346. let oid;
  1347. try { oid = new ObjectId(request.params.id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1348. const db = await getDb();
  1349. const cal = await db.collection('content_calendars').findOne({ _id: oid, workspaceId: ws });
  1350. if (!cal) return reply.code(404).send({ error: 'Calendar not found' });
  1351. return { calendarId: cal._id.toString(), ...cal };
  1352. });
  1353. // GET /ai/content-calendars — list recent calendars
  1354. app.get('/ai/content-calendars', async (request) => {
  1355. const ws = request.workspaceId;
  1356. const db = await getDb();
  1357. const cals = await db.collection('content_calendars')
  1358. .find({ workspaceId: ws }, { projection: { posts: 0 } })
  1359. .sort({ createdAt: -1 })
  1360. .limit(20)
  1361. .toArray();
  1362. return { calendars: cals.map((c) => ({ calendarId: c._id.toString(), month: c.month, monthName: c.monthName, platforms: c.platforms, brief: c.brief, createdAt: c.createdAt })) };
  1363. });
  1364. // ─── Bulk AI Draft Generation ─────────────────────────────────────────────────
  1365. // POST /ai/bulk-draft — kick off a batch; returns batchId immediately (non-blocking)
  1366. // Body: { topics: string[], destinations: Destination[], tone?: string, model?: string }
  1367. app.post('/ai/bulk-draft', async (request, reply) => {
  1368. const ws = request.workspaceId;
  1369. const { topics, destinations = [], tone = '', model: reqModel } = request.body || {};
  1370. if (!Array.isArray(topics) || !topics.length) return reply.code(400).send({ error: 'topics array is required' });
  1371. const filteredTopics = topics.map((t) => (typeof t === 'string' ? t.trim() : '')).filter(Boolean);
  1372. if (!filteredTopics.length) return reply.code(400).send({ error: 'No valid topics provided' });
  1373. const db = await getDb();
  1374. const batchId = new ObjectId();
  1375. const now = new Date();
  1376. await db.collection('bulk_draft_batches').insertOne({
  1377. _id: batchId,
  1378. total: filteredTopics.length,
  1379. completed: 0,
  1380. failed: 0,
  1381. status: 'processing',
  1382. workspaceId: ws,
  1383. createdAt: now,
  1384. updatedAt: now,
  1385. });
  1386. const selectedDests = destinations.filter((d) => d.selected);
  1387. const toneClause = tone ? `Write in a ${tone} tone.` : '';
  1388. const platformRules = buildPlatformRulesBlock(selectedDests);
  1389. const system = `You are a social media content writer. Create engaging, concise posts that perform well. ${toneClause} Write only the post text with relevant hashtags. No explanations or preamble.${platformRules}`;
  1390. // Fire-and-forget — process topics sequentially in the background
  1391. (async () => {
  1392. const pconf = await getActiveProviderConfig(request.workspaceId);
  1393. const model = reqModel || pconf.model;
  1394. for (const topic of filteredTopics) {
  1395. try {
  1396. const prompt = `Write a social media post about: ${topic}`;
  1397. let content = '';
  1398. if (pconf.provider === 'ollama') {
  1399. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  1400. content = res.data.response || '';
  1401. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1402. if (!pconf.apiKey) throw new Error(`${pconf.provider} API key not configured`);
  1403. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1404. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1405. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  1406. content = res.data.choices[0]?.message?.content || '';
  1407. } else if (pconf.provider === 'gemini') {
  1408. if (!pconf.apiKey) throw new Error('Gemini API key not configured');
  1409. const res = await axios.post(
  1410. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1411. { contents: buildGeminiContents(prompt, system) },
  1412. { timeout: 90000 },
  1413. );
  1414. content = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1415. }
  1416. if (content.trim()) {
  1417. const draftNow = new Date();
  1418. await db.collection('drafts').insertOne({
  1419. content: content.trim(),
  1420. mediaUrl: '',
  1421. scheduledAt: '',
  1422. destinations: selectedDests,
  1423. batchId: batchId.toString(),
  1424. topic,
  1425. workspaceId: request.workspaceId,
  1426. createdAt: draftNow,
  1427. updatedAt: draftNow,
  1428. });
  1429. }
  1430. await db.collection('bulk_draft_batches').updateOne(
  1431. { _id: batchId },
  1432. { $inc: { completed: 1 }, $set: { updatedAt: new Date() } },
  1433. );
  1434. } catch (err) {
  1435. log.error({ action: 'bulk_draft_topic', topic, outcome: 'failure', err: err.message });
  1436. await db.collection('bulk_draft_batches').updateOne(
  1437. { _id: batchId },
  1438. { $inc: { failed: 1 }, $set: { updatedAt: new Date() } },
  1439. );
  1440. }
  1441. }
  1442. await db.collection('bulk_draft_batches').updateOne(
  1443. { _id: batchId },
  1444. { $set: { status: 'done', updatedAt: new Date() } },
  1445. );
  1446. log.info({ action: 'bulk_draft_batch', batchId: batchId.toString(), total: filteredTopics.length, outcome: 'success' });
  1447. })().catch((err) => {
  1448. log.error({ action: 'bulk_draft_batch', batchId: batchId.toString(), outcome: 'failure', err: err.message });
  1449. getDb().then((d) => d.collection('bulk_draft_batches').updateOne(
  1450. { _id: batchId },
  1451. { $set: { status: 'failed', updatedAt: new Date() } },
  1452. )).catch(() => {});
  1453. });
  1454. return reply.code(202).send({ batchId: batchId.toString() });
  1455. });
  1456. // GET /ai/bulk-draft/:batchId — poll batch progress
  1457. app.get('/ai/bulk-draft/:batchId', async (request, reply) => {
  1458. const ws = request.workspaceId;
  1459. const { batchId } = request.params;
  1460. let oid;
  1461. try { oid = new ObjectId(batchId); } catch { return reply.code(400).send({ error: 'Invalid batchId' }); }
  1462. const db = await getDb();
  1463. const batch = await db.collection('bulk_draft_batches').findOne({ _id: oid, workspaceId: ws });
  1464. if (!batch) return reply.code(404).send({ error: 'Batch not found' });
  1465. return {
  1466. batchId: batch._id.toString(),
  1467. total: batch.total,
  1468. completed: batch.completed,
  1469. failed: batch.failed,
  1470. status: batch.status,
  1471. processed: batch.completed + batch.failed,
  1472. };
  1473. });
  1474. // ─── Platform service URLs ────────────────────────────────────────────────────
  1475. const PLATFORM_SERVICES = {
  1476. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  1477. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  1478. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  1479. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  1480. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  1481. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  1482. };
  1483. // Direct multi-platform post endpoint.
  1484. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  1485. app.post('/post', async (request, reply) => {
  1486. const { content, destinations = [], firstComment } = request.body || {};
  1487. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  1488. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  1489. const workspaceId = request.workspaceId;
  1490. const results = await Promise.allSettled(
  1491. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  1492. const serviceUrl = PLATFORM_SERVICES[platform];
  1493. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  1494. const res = await axios.post(
  1495. `${serviceUrl}/post`,
  1496. { content, accountId, imageUrl, videoUrl, link, firstComment: firstComment?.trim() || undefined },
  1497. { timeout: 30000, headers: { 'X-Workspace-Id': workspaceId } }
  1498. );
  1499. return { platform, accountId, ...res.data };
  1500. })
  1501. );
  1502. const output = results.map((r, i) =>
  1503. r.status === 'fulfilled'
  1504. ? r.value
  1505. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  1506. );
  1507. const anyFailed = output.some((r) => !r.success);
  1508. const anySucceeded = output.some((r) => r.success);
  1509. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  1510. // Record the post for analytics
  1511. try {
  1512. const db = await getDb();
  1513. await db.collection('posts').insertOne({
  1514. _id: crypto.randomUUID(),
  1515. type: 'immediate',
  1516. content,
  1517. ...(firstComment?.trim() && { firstComment: firstComment.trim() }),
  1518. destinations,
  1519. platformResults: Object.fromEntries(
  1520. output.map((r) => [
  1521. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  1522. { success: r.success, ...(r.error && { error: r.error }) },
  1523. ])
  1524. ),
  1525. status: postStatus,
  1526. workspaceId: request.workspaceId,
  1527. publishedAt: new Date(),
  1528. createdAt: new Date(),
  1529. });
  1530. } catch (err) {
  1531. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  1532. }
  1533. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  1534. });
  1535. // ─── Legacy post route ────────────────────────────────────────────────────────
  1536. let rabbitMQProducer = new RabbitMQProducer();
  1537. app.post('/', async (request, reply) => {
  1538. try {
  1539. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  1540. reply.send({ status: 'ok' });
  1541. } catch (error) {
  1542. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  1543. reply.status(500).send({ error: 'Internal Server Error' });
  1544. }
  1545. });
  1546. // ─── Meta App Credentials ────────────────────────────────────────────────────
  1547. // Save Facebook App ID + Secret (entered by user in Settings UI)
  1548. app.post('/credentials/meta-app', async (request, reply) => {
  1549. const ws = request.workspaceId;
  1550. const { appId, appSecret } = request.body || {};
  1551. if (!appId || !appSecret) {
  1552. return reply.code(400).send({ error: 'appId and appSecret are required' });
  1553. }
  1554. await setCredentials(ws, 'meta_app', { appId, appSecret: encryptToken(appSecret) });
  1555. return { success: true };
  1556. });
  1557. // Get Meta App config (secret is masked for UI display)
  1558. app.get('/credentials/meta-app', async (request) => {
  1559. const ws = request.workspaceId;
  1560. const cred = await getCredentials(ws, 'meta_app');
  1561. if (!cred) return { configured: false };
  1562. const plainSecret = decryptToken(cred.appSecret) || '';
  1563. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  1564. });
  1565. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  1566. // Return the Facebook OAuth URL to redirect the user to
  1567. app.get('/auth/meta/init', async (request, reply) => {
  1568. const ws = request.workspaceId;
  1569. const cred = await getCredentials(ws, 'meta_app');
  1570. if (!cred?.appId) {
  1571. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  1572. }
  1573. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1574. const scopes = [
  1575. 'pages_manage_posts',
  1576. 'pages_read_engagement',
  1577. 'instagram_basic',
  1578. 'instagram_content_publish',
  1579. 'instagram_manage_insights',
  1580. ].join(',');
  1581. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code&state=${encodeURIComponent(ws)}`;
  1582. return { url };
  1583. });
  1584. // OAuth callback — Facebook redirects here after user authorises
  1585. app.get('/auth/meta/callback', async (request, reply) => {
  1586. const { code, state, error: oauthError } = request.query;
  1587. // Recover workspace from state param (browser redirects carry no X-Workspace-Id header)
  1588. const ws = (state && String(state).trim()) ? String(state) : request.workspaceId;
  1589. if (oauthError) {
  1590. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  1591. }
  1592. if (!code) {
  1593. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  1594. }
  1595. try {
  1596. const appCred = await getCredentials(ws, 'meta_app');
  1597. if (!appCred?.appId) throw new Error('App credentials not configured');
  1598. const appSecret = decryptToken(appCred.appSecret);
  1599. if (!appSecret) throw new Error('Failed to decrypt app secret');
  1600. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1601. // Exchange code for short-lived token
  1602. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1603. params: {
  1604. client_id: appCred.appId,
  1605. client_secret: appSecret,
  1606. redirect_uri: redirectUri,
  1607. code,
  1608. },
  1609. });
  1610. // Upgrade to long-lived user token (~60 days)
  1611. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1612. params: {
  1613. grant_type: 'fb_exchange_token',
  1614. client_id: appCred.appId,
  1615. client_secret: appSecret,
  1616. fb_exchange_token: shortRes.data.access_token,
  1617. },
  1618. });
  1619. const userToken = longRes.data.access_token;
  1620. // Fetch all managed Facebook Pages
  1621. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  1622. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  1623. });
  1624. const pages = [];
  1625. const igAccounts = [];
  1626. for (const page of pagesRes.data.data || []) {
  1627. pages.push({
  1628. id: page.id,
  1629. name: page.name,
  1630. accessToken: encryptToken(page.access_token),
  1631. picture: page.picture?.data?.url || null,
  1632. selected: false,
  1633. });
  1634. // Check for linked Instagram Business Account
  1635. try {
  1636. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  1637. params: {
  1638. fields: 'instagram_business_account',
  1639. access_token: page.access_token,
  1640. },
  1641. });
  1642. if (igRes.data.instagram_business_account?.id) {
  1643. const igId = igRes.data.instagram_business_account.id;
  1644. // Fetch IG account details
  1645. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  1646. params: {
  1647. fields: 'id,username,name,profile_picture_url',
  1648. access_token: userToken,
  1649. },
  1650. });
  1651. igAccounts.push({
  1652. id: igId,
  1653. username: igProfile.data.username || igProfile.data.name,
  1654. name: igProfile.data.name,
  1655. avatar: igProfile.data.profile_picture_url || null,
  1656. accessToken: encryptToken(userToken),
  1657. pageId: page.id,
  1658. selected: false,
  1659. });
  1660. }
  1661. } catch (_) {
  1662. // Page has no linked Instagram account — skip
  1663. }
  1664. }
  1665. // Store discovery results for the UI to pick from
  1666. await setCredentials(ws, 'meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1667. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1668. } catch (err) {
  1669. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1670. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1671. }
  1672. });
  1673. // Return pending discovery results so the UI can render the page picker
  1674. app.get('/auth/meta/discovered', async (request) => {
  1675. const ws = request.workspaceId;
  1676. const discovery = await getCredentials(ws, 'meta_discovery');
  1677. if (!discovery) return { pages: [], igAccounts: [] };
  1678. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1679. });
  1680. // User has chosen which pages/accounts to connect
  1681. app.post('/auth/meta/save', async (request, reply) => {
  1682. const ws = request.workspaceId;
  1683. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1684. const discovery = await getCredentials(ws, 'meta_discovery');
  1685. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1686. const fbPages = (discovery.pages || []).map((p) => ({
  1687. ...p,
  1688. selected: selectedPageIds.includes(p.id),
  1689. }));
  1690. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1691. ...a,
  1692. selected: selectedIgAccountIds.includes(a.id),
  1693. }));
  1694. await setCredentials(ws, 'facebook', { pages: fbPages });
  1695. await setCredentials(ws, 'instagram', { accounts: igAccounts });
  1696. await deleteCredentials(ws, 'meta_discovery');
  1697. _tokenExpiryCache = null; // invalidate cache after reconnect
  1698. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1699. });
  1700. // Disconnect all Meta platforms
  1701. app.delete('/credentials/meta', async (request) => {
  1702. const ws = request.workspaceId;
  1703. await deleteCredentials(ws, 'facebook');
  1704. await deleteCredentials(ws, 'instagram');
  1705. await deleteCredentials(ws, 'meta_discovery');
  1706. return { success: true };
  1707. });
  1708. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1709. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1710. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1711. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1712. app.post('/credentials/pinterest-app', async (request, reply) => {
  1713. const ws = request.workspaceId;
  1714. const { clientId, clientSecret } = request.body || {};
  1715. if (!clientId || !clientSecret) {
  1716. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1717. }
  1718. await setCredentials(ws, 'pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1719. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1720. return { success: true };
  1721. });
  1722. app.get('/credentials/pinterest-app', async (request) => {
  1723. const ws = request.workspaceId;
  1724. const cred = await getCredentials(ws, 'pinterest_app');
  1725. if (!cred) return { configured: false };
  1726. const plain = decryptToken(cred.clientSecret) || '';
  1727. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1728. });
  1729. app.get('/auth/pinterest/init', async (request, reply) => {
  1730. const ws = request.workspaceId;
  1731. const cred = await getCredentials(ws, 'pinterest_app');
  1732. if (!cred?.clientId) {
  1733. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1734. }
  1735. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1736. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1737. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}&state=${encodeURIComponent(ws)}`;
  1738. return { url };
  1739. });
  1740. app.get('/auth/pinterest/callback', async (request, reply) => {
  1741. const { code, state, error: oauthError } = request.query;
  1742. const ws = (state && String(state).trim()) ? String(state) : request.workspaceId;
  1743. if (oauthError) {
  1744. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1745. }
  1746. if (!code) {
  1747. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1748. }
  1749. try {
  1750. const appCred = await getCredentials(ws, 'pinterest_app');
  1751. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1752. const clientSecret = decryptToken(appCred.clientSecret);
  1753. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1754. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1755. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1756. const tokenRes = await axios.post(
  1757. PINTEREST_TOKEN_URL,
  1758. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1759. {
  1760. headers: {
  1761. Authorization: `Basic ${basicAuth}`,
  1762. 'Content-Type': 'application/x-www-form-urlencoded',
  1763. },
  1764. timeout: 15000,
  1765. }
  1766. );
  1767. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1768. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1769. const [userRes, boardsRes] = await Promise.all([
  1770. axios.get(`${PINTEREST_API}/user_account`, {
  1771. headers: { Authorization: `Bearer ${access_token}` },
  1772. timeout: 10000,
  1773. }),
  1774. axios.get(`${PINTEREST_API}/boards`, {
  1775. headers: { Authorization: `Bearer ${access_token}` },
  1776. params: { page_size: 100 },
  1777. timeout: 15000,
  1778. }),
  1779. ]);
  1780. const boards = (boardsRes.data.items || []).map((b) => ({
  1781. id: b.id,
  1782. name: b.name,
  1783. privacy: b.privacy,
  1784. selected: false,
  1785. }));
  1786. await setCredentials(ws, 'pinterest', {
  1787. userId: userRes.data.username,
  1788. username: userRes.data.username,
  1789. displayName: userRes.data.business_name || userRes.data.username,
  1790. avatar: userRes.data.profile_image,
  1791. accessToken: encryptToken(access_token),
  1792. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1793. tokenExpiry,
  1794. boards,
  1795. });
  1796. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1797. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1798. } catch (err) {
  1799. const msg = err.response?.data?.message || err.message;
  1800. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1801. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1802. }
  1803. });
  1804. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1805. const ws = request.workspaceId;
  1806. const { selectedBoardIds = [] } = request.body || {};
  1807. const cred = await getCredentials(ws, 'pinterest');
  1808. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1809. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1810. await setCredentials(ws, 'pinterest', { ...cred, boards });
  1811. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1812. return { success: true, selected: boards.filter((b) => b.selected).length };
  1813. });
  1814. app.delete('/credentials/pinterest', async (request) => {
  1815. const ws = request.workspaceId;
  1816. await deleteCredentials(ws, 'pinterest');
  1817. return { success: true };
  1818. });
  1819. // ─── TikTok OAuth ─────────────────────────────────────────────────────────────
  1820. const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
  1821. const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
  1822. const TIKTOK_API = 'https://open.tiktokapis.com/v2';
  1823. app.post('/credentials/tiktok-app', async (request, reply) => {
  1824. const ws = request.workspaceId;
  1825. const { clientKey, clientSecret } = request.body || {};
  1826. if (!clientKey || !clientSecret) return reply.code(400).send({ error: 'clientKey and clientSecret are required' });
  1827. await setCredentials(ws, 'tiktok_app', { clientKey, clientSecret: encryptToken(clientSecret) });
  1828. log.info({ action: 'tiktok_app_save', outcome: 'success' });
  1829. return { success: true };
  1830. });
  1831. app.get('/credentials/tiktok-app', async (request) => {
  1832. const ws = request.workspaceId;
  1833. const cred = await getCredentials(ws, 'tiktok_app');
  1834. if (!cred?.clientKey) return { configured: false };
  1835. return { configured: true, clientKey: cred.clientKey, clientSecretHint: `****${decryptToken(cred.clientSecret).slice(-4)}` };
  1836. });
  1837. app.get('/auth/tiktok/init', async (request, reply) => {
  1838. const ws = request.workspaceId;
  1839. const cred = await getCredentials(ws, 'tiktok_app');
  1840. if (!cred?.clientKey) return reply.code(400).send({ error: 'Save your TikTok Client Key and Secret first' });
  1841. const codeVerifier = crypto.randomBytes(32).toString('base64url');
  1842. const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1843. const state = crypto.randomBytes(16).toString('hex');
  1844. // Persist PKCE verifier for the callback
  1845. const pkceId = credId(ws, 'tiktok_pkce');
  1846. const db = await getDb();
  1847. await db.collection('platform_credentials').updateOne(
  1848. { _id: pkceId },
  1849. { $set: { _id: pkceId, workspaceId: ws, codeVerifier, state, createdAt: new Date() } },
  1850. { upsert: true }
  1851. );
  1852. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1853. const scopes = 'user.info.basic,video.list,video.publish';
  1854. const params = new URLSearchParams({
  1855. client_key: cred.clientKey,
  1856. scope: scopes,
  1857. response_type: 'code',
  1858. redirect_uri: redirectUri,
  1859. state,
  1860. code_challenge: codeChallenge,
  1861. code_challenge_method: 'S256',
  1862. });
  1863. return { url: `${TIKTOK_AUTH_URL}?${params.toString()}` };
  1864. });
  1865. app.get('/auth/tiktok/callback', async (request, reply) => {
  1866. const { code, state, error: oauthError, error_description } = request.query;
  1867. if (oauthError) {
  1868. const msg = error_description || oauthError;
  1869. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1870. }
  1871. if (!code) {
  1872. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=no_code`);
  1873. }
  1874. try {
  1875. const db = await getDb();
  1876. // Look up PKCE by state value — recovers the workspace ID that initiated the OAuth
  1877. const pkce = await db.collection('platform_credentials').findOne({ state });
  1878. if (!pkce?.codeVerifier) throw new Error('PKCE state not found — try connecting again');
  1879. const ws = pkce.workspaceId || request.workspaceId;
  1880. const appCred = await getCredentials(ws, 'tiktok_app');
  1881. if (!appCred?.clientKey) throw new Error('App credentials not configured');
  1882. const clientSecret = decryptToken(appCred.clientSecret);
  1883. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1884. const tokenRes = await axios.post(
  1885. TIKTOK_TOKEN_URL,
  1886. new URLSearchParams({
  1887. client_key: appCred.clientKey,
  1888. client_secret: clientSecret,
  1889. code,
  1890. grant_type: 'authorization_code',
  1891. redirect_uri: redirectUri,
  1892. code_verifier: pkce.codeVerifier,
  1893. }).toString(),
  1894. { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000 }
  1895. );
  1896. const { access_token, refresh_token, expires_in, refresh_expires_in, open_id } = tokenRes.data;
  1897. const tokenExpiry = new Date(Date.now() + (expires_in || 86400) * 1000).toISOString();
  1898. const refreshExpiry = new Date(Date.now() + (refresh_expires_in || 31536000) * 1000).toISOString();
  1899. const userRes = await axios.get(`${TIKTOK_API}/user/info/`, {
  1900. headers: { Authorization: `Bearer ${access_token}` },
  1901. params: { fields: 'open_id,display_name,avatar_url,username' },
  1902. timeout: 10000,
  1903. });
  1904. const user = userRes.data?.data?.user || {};
  1905. await setCredentials(ws, 'tiktok', {
  1906. openId: open_id || user.open_id,
  1907. username: user.username || user.display_name,
  1908. displayName: user.display_name,
  1909. avatar: user.avatar_url || null,
  1910. accessToken: encryptToken(access_token),
  1911. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1912. tokenExpiry,
  1913. refreshExpiry,
  1914. });
  1915. // Clean up PKCE temp state
  1916. await db.collection('platform_credentials').deleteOne({ _id: credId(ws, 'tiktok_pkce') });
  1917. log.info({ action: 'tiktok_oauth_callback', username: user.username || user.display_name, outcome: 'success' });
  1918. reply.redirect(`${APP_BASE_URL}/settings?tiktok_connected=1`);
  1919. } catch (err) {
  1920. const msg = err.response?.data?.error?.message || err.response?.data?.message || err.message;
  1921. log.error({ action: 'tiktok_oauth_callback', outcome: 'failure', err: msg });
  1922. reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1923. }
  1924. });
  1925. app.delete('/credentials/tiktok', async (request) => {
  1926. const ws = request.workspaceId;
  1927. await deleteCredentials(ws, 'tiktok');
  1928. return { success: true };
  1929. });
  1930. // ─── Credential Status ────────────────────────────────────────────────────────
  1931. // Aggregate connection status for all DB-managed platforms
  1932. app.get('/credentials', async (request) => {
  1933. const ws = request.workspaceId;
  1934. const [metaApp, fb, ig, pinterest, tiktok] = await Promise.all([
  1935. getCredentials(ws, 'meta_app'),
  1936. getCredentials(ws, 'facebook'),
  1937. getCredentials(ws, 'instagram'),
  1938. getCredentials(ws, 'pinterest'),
  1939. getCredentials(ws, 'tiktok'),
  1940. ]);
  1941. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1942. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1943. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1944. return {
  1945. metaApp: { configured: !!(metaApp?.appId) },
  1946. facebook: {
  1947. connected: fbPages.length > 0,
  1948. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1949. allPages: (fb?.pages || []).map(({ id, name, picture, selected }) => ({ id, name, picture, selected: !!selected })),
  1950. },
  1951. instagram: {
  1952. connected: igAccounts.length > 0,
  1953. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1954. allAccounts: (ig?.accounts || []).map(({ id, username, avatar, selected }) => ({ id, username, avatar, selected: !!selected })),
  1955. },
  1956. pinterest: {
  1957. connected: pinterestBoards.length > 0,
  1958. username: pinterest?.username || null,
  1959. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1960. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1961. },
  1962. tiktok: {
  1963. connected: !!(tiktok?.accessToken),
  1964. username: tiktok?.username || null,
  1965. displayName: tiktok?.displayName || null,
  1966. avatar: tiktok?.avatar || null,
  1967. },
  1968. };
  1969. });
  1970. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1971. // Update which Facebook pages are selected for this workspace
  1972. app.post('/credentials/facebook/pages', async (request) => {
  1973. const ws = request.workspaceId;
  1974. const { selectedPageIds } = request.body;
  1975. const fb = await getCredentials(ws, 'facebook');
  1976. if (!fb) return { success: false, error: 'Not connected' };
  1977. const updated = (fb.pages || []).map((p) => ({ ...p, selected: selectedPageIds.includes(p.id) }));
  1978. await setCredentials(ws, 'facebook', { pages: updated });
  1979. return { success: true };
  1980. });
  1981. // Update which Instagram accounts are selected for this workspace
  1982. app.post('/credentials/instagram/accounts', async (request) => {
  1983. const ws = request.workspaceId;
  1984. const { selectedAccountIds } = request.body;
  1985. const ig = await getCredentials(ws, 'instagram');
  1986. if (!ig) return { success: false, error: 'Not connected' };
  1987. const updated = (ig.accounts || []).map((a) => ({ ...a, selected: selectedAccountIds.includes(a.id) }));
  1988. await setCredentials(ws, 'instagram', { accounts: updated });
  1989. return { success: true };
  1990. });
  1991. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1992. const INDUSTRY_DEFAULTS = {
  1993. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1994. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1995. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1996. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1997. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1998. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1999. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  2000. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  2001. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  2002. tiktok: [[2,18],[3,18],[4,18],[5,12],[0,14]],
  2003. };
  2004. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  2005. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  2006. // at least `afterMs` milliseconds in the future.
  2007. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  2008. const candidate = new Date(afterMs);
  2009. candidate.setUTCHours(hourUTC, 0, 0, 0);
  2010. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  2011. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  2012. candidate.setUTCDate(candidate.getUTCDate() + 7);
  2013. } else {
  2014. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  2015. }
  2016. return candidate;
  2017. }
  2018. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  2019. app.get('/schedule/suggestions', async (request, reply) => {
  2020. const { platform, accountId } = request.query;
  2021. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  2022. const ws = request.workspaceId;
  2023. const db = await getDb();
  2024. const query = { workspaceId: ws, platform, ...(accountId && { accountId }) };
  2025. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  2026. let slots;
  2027. let source;
  2028. if (dataPoints >= 10) {
  2029. const agg = await db.collection('post_metrics').aggregate([
  2030. { $match: query },
  2031. { $group: {
  2032. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  2033. avgEngagement: { $avg: '$metrics.engagementTotal' },
  2034. count: { $sum: 1 },
  2035. }},
  2036. { $sort: { avgEngagement: -1 } },
  2037. { $limit: 5 },
  2038. ]).toArray();
  2039. slots = agg.map((r) => [r._id.day, r._id.hour]);
  2040. source = 'history';
  2041. } else {
  2042. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  2043. source = 'default';
  2044. }
  2045. // 30-minute lead time so the user has time to finish writing
  2046. const afterMs = Date.now() + 30 * 60 * 1000;
  2047. const suggestions = slots
  2048. .map(([day, hour]) => {
  2049. const dt = nextOccurrence(day, hour, afterMs);
  2050. const h12 = hour % 12 || 12;
  2051. const ampm = hour < 12 ? 'am' : 'pm';
  2052. return {
  2053. utc: dt.toISOString(),
  2054. dayOfWeek: day,
  2055. hour,
  2056. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  2057. };
  2058. })
  2059. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  2060. .slice(0, 4);
  2061. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  2062. return { source, suggestions };
  2063. });
  2064. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  2065. async function crawlFacebookMetrics(db, ws = 'default') {
  2066. const fb = await getCredentials(ws, 'facebook');
  2067. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  2068. if (!pages.length) return { count: 0 };
  2069. let count = 0;
  2070. for (const page of pages) {
  2071. const token = decryptToken(page.accessToken);
  2072. if (!token) continue;
  2073. try {
  2074. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  2075. params: {
  2076. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  2077. limit: 100,
  2078. access_token: token,
  2079. },
  2080. timeout: 30000,
  2081. });
  2082. for (const post of res.data.data || []) {
  2083. const likes = post.reactions?.summary?.total_count || 0;
  2084. const comments = post.comments?.summary?.total_count || 0;
  2085. const shares = post.shares?.count || 0;
  2086. const publishedAt = new Date(post.created_time);
  2087. await db.collection('post_metrics').updateOne(
  2088. { platform: 'facebook', postId: post.id, workspaceId: ws },
  2089. {
  2090. $set: {
  2091. platform: 'facebook',
  2092. accountId: page.id,
  2093. accountName: page.name,
  2094. postId: post.id,
  2095. content: post.message || null,
  2096. publishedAt,
  2097. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  2098. hourOfDay: publishedAt.getUTCHours(),
  2099. dayOfWeek: publishedAt.getUTCDay(),
  2100. workspaceId: ws,
  2101. fetchedAt: new Date(),
  2102. },
  2103. },
  2104. { upsert: true }
  2105. );
  2106. count++;
  2107. }
  2108. } catch (err) {
  2109. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  2110. }
  2111. }
  2112. return { count };
  2113. }
  2114. async function crawlInstagramMetrics(db, ws = 'default') {
  2115. const ig = await getCredentials(ws, 'instagram');
  2116. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  2117. if (!accounts.length) return { count: 0 };
  2118. let count = 0;
  2119. for (const account of accounts) {
  2120. const token = decryptToken(account.accessToken);
  2121. if (!token) continue;
  2122. try {
  2123. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  2124. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  2125. timeout: 30000,
  2126. });
  2127. for (const media of mediaRes.data.data || []) {
  2128. const likes = media.like_count || 0;
  2129. const comments = media.comments_count || 0;
  2130. const publishedAt = new Date(media.timestamp);
  2131. let views = 0;
  2132. let saves = 0;
  2133. try {
  2134. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  2135. params: { metric: 'reach,saved', access_token: token },
  2136. timeout: 10000,
  2137. });
  2138. for (const ins of insRes.data.data || []) {
  2139. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  2140. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  2141. }
  2142. } catch (_) {}
  2143. await db.collection('post_metrics').updateOne(
  2144. { platform: 'instagram', postId: media.id, workspaceId: ws },
  2145. {
  2146. $set: {
  2147. platform: 'instagram',
  2148. accountId: account.id,
  2149. accountName: account.username,
  2150. postId: media.id,
  2151. content: media.caption || null,
  2152. publishedAt,
  2153. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  2154. hourOfDay: publishedAt.getUTCHours(),
  2155. dayOfWeek: publishedAt.getUTCDay(),
  2156. workspaceId: ws,
  2157. fetchedAt: new Date(),
  2158. },
  2159. },
  2160. { upsert: true }
  2161. );
  2162. count++;
  2163. }
  2164. } catch (err) {
  2165. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  2166. }
  2167. }
  2168. return { count };
  2169. }
  2170. app.post('/analytics/crawl', async (request) => {
  2171. const ws = request.workspaceId;
  2172. const db = await getDb();
  2173. const results = {};
  2174. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  2175. try {
  2176. results[platform] = await crawler(db, ws);
  2177. } catch (err) {
  2178. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  2179. results[platform] = { count: 0, error: err.message };
  2180. }
  2181. }
  2182. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  2183. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  2184. return { success: true, total, byPlatform: results };
  2185. });
  2186. app.get('/analytics/insights', async (request) => {
  2187. const ws = request.workspaceId;
  2188. const filter = parseAccountFilter(request.query.account);
  2189. const metricsMatch = filter
  2190. ? { workspaceId: ws, platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  2191. : { workspaceId: ws };
  2192. const db = await getDb();
  2193. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  2194. if (total === 0) return { empty: true };
  2195. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  2196. db.collection('post_metrics').aggregate([
  2197. { $match: metricsMatch },
  2198. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  2199. { $sort: { _id: 1 } },
  2200. ]).toArray(),
  2201. db.collection('post_metrics').aggregate([
  2202. { $match: metricsMatch },
  2203. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  2204. { $sort: { _id: 1 } },
  2205. ]).toArray(),
  2206. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  2207. db.collection('post_metrics').aggregate([
  2208. { $match: metricsMatch },
  2209. { $group: {
  2210. _id: '$platform',
  2211. avgEngagement: { $avg: '$metrics.engagementTotal' },
  2212. avgLikes: { $avg: '$metrics.likes' },
  2213. avgComments: { $avg: '$metrics.comments' },
  2214. avgShares: { $avg: '$metrics.shares' },
  2215. totalPosts: { $sum: 1 },
  2216. }},
  2217. { $sort: { avgEngagement: -1 } },
  2218. ]).toArray(),
  2219. db.collection('post_metrics').aggregate([
  2220. { $match: metricsMatch },
  2221. { $group: {
  2222. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  2223. avgEngagement: { $avg: '$metrics.engagementTotal' },
  2224. count: { $sum: 1 },
  2225. }},
  2226. ]).toArray(),
  2227. ]);
  2228. const byHour = Array.from({ length: 24 }, (_, h) => {
  2229. const e = byHourRaw.find((r) => r._id === h);
  2230. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  2231. });
  2232. const byDay = Array.from({ length: 7 }, (_, d) => {
  2233. const e = byDayRaw.find((r) => r._id === d);
  2234. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  2235. });
  2236. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  2237. const day = Math.floor(i / 24);
  2238. const hour = i % 24;
  2239. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  2240. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  2241. });
  2242. return {
  2243. empty: false,
  2244. total,
  2245. byHour,
  2246. byDay,
  2247. heatmap,
  2248. topPosts: topPosts.map((p) => ({
  2249. platform: p.platform, accountName: p.accountName, postId: p.postId,
  2250. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  2251. })),
  2252. platformComparison: platformComparison.map((p) => ({
  2253. platform: p._id,
  2254. avgEngagement: Math.round(p.avgEngagement),
  2255. avgLikes: Math.round(p.avgLikes),
  2256. avgComments: Math.round(p.avgComments),
  2257. avgShares: Math.round(p.avgShares),
  2258. totalPosts: p.totalPosts,
  2259. })),
  2260. };
  2261. });
  2262. // ─── Analytics ────────────────────────────────────────────────────────────────
  2263. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  2264. function parseAccountFilter(account) {
  2265. if (!account) return null;
  2266. const idx = account.indexOf(':');
  2267. if (idx === -1) return { platform: account };
  2268. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  2269. }
  2270. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  2271. function sjFilter(filter, workspaceId) {
  2272. const wsClause = workspaceId
  2273. ? { $or: [{ workspaceId }, { workspaceId: { $exists: false } }] }
  2274. : {};
  2275. if (!filter) return wsClause;
  2276. return {
  2277. ...wsClause,
  2278. 'destinations.platform': filter.platform,
  2279. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  2280. };
  2281. }
  2282. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  2283. function ipFilter(filter) {
  2284. if (!filter) return {};
  2285. return {
  2286. 'destinations.platform': filter.platform,
  2287. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  2288. };
  2289. }
  2290. app.get('/analytics/summary', async (request) => {
  2291. const ws = request.workspaceId;
  2292. const filter = parseAccountFilter(request.query.account);
  2293. const db = await getDb();
  2294. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  2295. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  2296. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  2297. // account filter after $unwind so a job targeting multiple platforms only
  2298. // counts the platform(s) that match the filter.
  2299. const unwindFilter = filter ? [{ $match: sjFilter(filter, ws) }] : [];
  2300. const wsIp = { workspaceId: ws };
  2301. const [
  2302. schedCompleted, schedFailed,
  2303. immPublished, immFailed,
  2304. recentSched, recentImm,
  2305. schedPlatformRaw, immPlatformRaw,
  2306. schedDayRaw, immDayRaw,
  2307. ] = await Promise.all([
  2308. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter, ws) }),
  2309. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter, ws) }),
  2310. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...wsIp, ...ipFilter(filter) }),
  2311. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...wsIp, ...ipFilter(filter) }),
  2312. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter, ws) }),
  2313. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...wsIp, ...ipFilter(filter) }),
  2314. // Platform breakdown from scheduled_jobs destinations
  2315. db.collection('scheduled_jobs').aggregate([
  2316. { $match: { status: 'completed', ...sjFilter(filter, ws) } },
  2317. { $unwind: '$destinations' },
  2318. ...unwindFilter,
  2319. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  2320. { $sort: { count: -1 } },
  2321. ]).toArray(),
  2322. // Platform breakdown from immediate posts platformResults
  2323. db.collection('posts').aggregate([
  2324. { $match: { type: 'immediate', ...wsIp, ...ipFilter(filter) } },
  2325. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  2326. { $unwind: '$results' },
  2327. { $match: { 'results.v.success': true } },
  2328. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  2329. { $group: { _id: '$platform', count: { $sum: 1 } } },
  2330. ]).toArray(),
  2331. // Activity by day from scheduled_jobs (using completedAt)
  2332. db.collection('scheduled_jobs').aggregate([
  2333. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter, ws) } },
  2334. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  2335. { $sort: { _id: 1 } },
  2336. ]).toArray(),
  2337. // Activity by day from immediate posts
  2338. db.collection('posts').aggregate([
  2339. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...wsIp, ...ipFilter(filter) } },
  2340. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  2341. { $sort: { _id: 1 } },
  2342. ]).toArray(),
  2343. ]);
  2344. const dayMap = {};
  2345. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  2346. dayMap[_id] = (dayMap[_id] || 0) + count;
  2347. }
  2348. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  2349. const platformMap = {};
  2350. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  2351. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  2352. }
  2353. const published = schedCompleted + immPublished;
  2354. const failed = schedFailed + immFailed;
  2355. const total = published + failed;
  2356. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  2357. const recentCount = recentSched + recentImm;
  2358. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  2359. });
  2360. app.get('/analytics/posts', async (request) => {
  2361. const ws = request.workspaceId;
  2362. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  2363. const skip = parseInt(request.query.skip || '0', 10);
  2364. const filter = parseAccountFilter(request.query.account);
  2365. const db = await getDb();
  2366. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter, ws) };
  2367. const ipMatch = { type: 'immediate', workspaceId: ws, ...ipFilter(filter) };
  2368. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  2369. db.collection('scheduled_jobs')
  2370. .find(sjMatch)
  2371. .sort({ completedAt: -1, scheduledAt: -1 })
  2372. .skip(skip)
  2373. .limit(limit)
  2374. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  2375. .toArray(),
  2376. db.collection('posts')
  2377. .find(ipMatch)
  2378. .sort({ publishedAt: -1 })
  2379. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  2380. .toArray(),
  2381. db.collection('scheduled_jobs').countDocuments(sjMatch),
  2382. db.collection('posts').countDocuments(ipMatch),
  2383. ]);
  2384. const normalised = [
  2385. ...scheduledJobs.map((j) => ({
  2386. _id: String(j._id),
  2387. type: 'scheduled',
  2388. content: j.content || null,
  2389. destinations: j.destinations || [],
  2390. platformResults: null,
  2391. status: j.status === 'completed' ? 'published' : 'failed',
  2392. publishedAt: j.completedAt || j.scheduledAt,
  2393. })),
  2394. ...immediatePosts.map((p) => ({
  2395. _id: String(p._id),
  2396. type: 'immediate',
  2397. content: p.content || null,
  2398. destinations: p.destinations || [],
  2399. platformResults: p.platformResults || null,
  2400. status: p.status,
  2401. publishedAt: p.publishedAt,
  2402. })),
  2403. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  2404. .slice(0, limit);
  2405. return { posts: normalised, total: schedTotal + immTotal };
  2406. });
  2407. // ─── Analytics Export ─────────────────────────────────────────────────────────
  2408. // GET /analytics/export?format=csv&account=&month=YYYY-MM
  2409. // Exports scheduled jobs + immediate posts as a downloadable CSV.
  2410. app.get('/analytics/export', async (request, reply) => {
  2411. const ws = request.workspaceId;
  2412. const { format = 'csv', account, month } = request.query;
  2413. const filter = parseAccountFilter(account);
  2414. const db = await getDb();
  2415. let dateFilter = {};
  2416. if (month) {
  2417. const start = new Date(`${month}-01T00:00:00.000Z`);
  2418. const end = new Date(start);
  2419. end.setMonth(end.getMonth() + 1);
  2420. dateFilter = { $gte: start, $lt: end };
  2421. }
  2422. const sjMatch = {
  2423. status: { $in: ['completed', 'failed'] },
  2424. ...sjFilter(filter, ws),
  2425. ...(month ? { completedAt: dateFilter } : {}),
  2426. };
  2427. const ipMatch = {
  2428. type: 'immediate',
  2429. workspaceId: ws,
  2430. ...ipFilter(filter),
  2431. ...(month ? { publishedAt: dateFilter } : {}),
  2432. };
  2433. const [scheduledJobs, immediatePosts] = await Promise.all([
  2434. db.collection('scheduled_jobs')
  2435. .find(sjMatch)
  2436. .sort({ completedAt: -1 })
  2437. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  2438. .toArray(),
  2439. db.collection('posts')
  2440. .find(ipMatch)
  2441. .sort({ publishedAt: -1 })
  2442. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  2443. .toArray(),
  2444. ]);
  2445. const rows = [
  2446. ...scheduledJobs.map((j) => ({
  2447. type: 'scheduled',
  2448. date: (j.completedAt || j.scheduledAt)?.toISOString()?.slice(0, 10) ?? '',
  2449. time: (j.completedAt || j.scheduledAt)?.toISOString()?.slice(11, 16) ?? '',
  2450. platforms: (j.destinations || []).map((d) => d.platform).join(' | '),
  2451. status: j.status === 'completed' ? 'published' : 'failed',
  2452. content: j.content || '',
  2453. })),
  2454. ...immediatePosts.map((p) => ({
  2455. type: 'immediate',
  2456. date: p.publishedAt?.toISOString()?.slice(0, 10) ?? '',
  2457. time: p.publishedAt?.toISOString()?.slice(11, 16) ?? '',
  2458. platforms: (p.destinations || []).map((d) => d.platform).join(' | '),
  2459. status: p.status,
  2460. content: p.content || '',
  2461. })),
  2462. ].sort((a, b) => b.date.localeCompare(a.date) || b.time.localeCompare(a.time));
  2463. const escape = (v) => `"${String(v).replace(/"/g, '""')}"`;
  2464. const header = ['Date', 'Time (UTC)', 'Type', 'Platforms', 'Status', 'Content'];
  2465. const lines = [
  2466. header.join(','),
  2467. ...rows.map((r) => [r.date, r.time, r.type, r.platforms, r.status, escape(r.content)].join(',')),
  2468. ];
  2469. const filename = `posts-${month || 'all'}.csv`;
  2470. reply.header('Content-Type', 'text/csv; charset=utf-8');
  2471. reply.header('Content-Disposition', `attachment; filename="${filename}"`);
  2472. return reply.send('' + lines.join('\r\n'));
  2473. });
  2474. // ─── Brand / Account Audit ────────────────────────────────────────────────────
  2475. app.post('/analytics/audit', async (request, reply) => {
  2476. const ws = request.workspaceId;
  2477. const filter = parseAccountFilter(request.query.account);
  2478. const db = await getDb();
  2479. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  2480. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  2481. const recentPosts = await db.collection('posts').find({
  2482. workspaceId: ws,
  2483. publishedAt: { $gte: thirtyDaysAgo },
  2484. ...ipFilter(filter),
  2485. }, { projection: { content: 1, destinations: 1, publishedAt: 1, status: 1 } }).toArray();
  2486. if (recentPosts.length < 3) {
  2487. return reply.code(400).send({ error: 'Not enough publishing history. Publish at least 3 posts first.' });
  2488. }
  2489. // Posting frequency
  2490. const postsLast30 = recentPosts.length;
  2491. const postsLast7 = recentPosts.filter((p) => new Date(p.publishedAt) >= sevenDaysAgo).length;
  2492. const postsPerWeek = Math.round((postsLast30 / 4) * 10) / 10;
  2493. // Platforms used
  2494. const platforms = [...new Set(recentPosts.flatMap((p) => (p.destinations || []).map((d) => d.platform)).filter(Boolean))];
  2495. // Success rate
  2496. const publishedCount = recentPosts.filter((p) => p.status === 'published').length;
  2497. const successRate = Math.round((publishedCount / postsLast30) * 100);
  2498. // Top hashtags from post content
  2499. const hashtagCounts = {};
  2500. for (const post of recentPosts) {
  2501. const re = /#([a-zA-Z]\w*)/g;
  2502. let m;
  2503. re.lastIndex = 0;
  2504. while ((m = re.exec(post.content || '')) !== null) {
  2505. const tag = `#${m[1].toLowerCase()}`;
  2506. hashtagCounts[tag] = (hashtagCounts[tag] || 0) + 1;
  2507. }
  2508. }
  2509. const topHashtags = Object.entries(hashtagCounts)
  2510. .sort((a, b) => b[1] - a[1])
  2511. .slice(0, 5)
  2512. .map(([tag, count]) => `${tag} (${count}x)`)
  2513. .join(', ');
  2514. // Posting hour distribution — identify peak hours
  2515. const hourCounts = {};
  2516. for (const post of recentPosts) {
  2517. if (post.publishedAt) {
  2518. const h = new Date(post.publishedAt).getUTCHours();
  2519. hourCounts[h] = (hourCounts[h] || 0) + 1;
  2520. }
  2521. }
  2522. const peakHours = Object.entries(hourCounts)
  2523. .sort((a, b) => b[1] - a[1])
  2524. .slice(0, 3)
  2525. .map(([h]) => `${h}:00 UTC`)
  2526. .join(', ');
  2527. // Engagement data from post_metrics
  2528. const metricsFilter = filter
  2529. ? { workspaceId: ws, platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  2530. : { workspaceId: ws };
  2531. const metrics = await db.collection('post_metrics')
  2532. .find({ ...metricsFilter, createdAt: { $gte: thirtyDaysAgo } })
  2533. .toArray();
  2534. const avgEngagement = metrics.length > 0
  2535. ? Math.round((metrics.reduce((s, m) => s + (m.metrics?.engagementTotal || 0), 0) / metrics.length) * 10) / 10
  2536. : 0;
  2537. const statsBlock = [
  2538. `Publishing stats (last 30 days):`,
  2539. `- Total posts: ${postsLast30}`,
  2540. `- Posts this week: ${postsLast7}`,
  2541. `- Posts per week (avg): ${postsPerWeek}`,
  2542. `- Platforms used: ${platforms.join(', ') || 'unknown'}`,
  2543. `- Success rate: ${successRate}%`,
  2544. `- Average engagement per post: ${avgEngagement}`,
  2545. `- Current peak posting hours (UTC): ${peakHours || 'not enough data'}`,
  2546. `- Top hashtags in use: ${topHashtags || 'none detected'}`,
  2547. ].join('\n');
  2548. const system = 'You are a social media performance analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2549. const prompt = `Audit this social media account and return a structured report.
  2550. ${statsBlock}
  2551. Return a JSON object with exactly these fields:
  2552. {
  2553. "score": <overall health score 0-100>,
  2554. "summary": "<2-3 sentence assessment>",
  2555. "postingFrequency": { "score": <0-10>, "assessment": "<one sentence>" },
  2556. "engagement": { "score": <0-10>, "benchmark": "<Excellent|Good|Average|Below Average>", "assessment": "<one sentence>" },
  2557. "contentMix": { "score": <0-10>, "assessment": "<one sentence on variety and platform fit>" },
  2558. "recommendations": ["<specific action 1>", "<specific action 2>", "<specific action 3>"]
  2559. }
  2560. Scoring benchmarks: posting 5+x/week = 8-10, 3-4x = 6-7, 1-2x = 4-5, less = 1-3.
  2561. Engagement benchmarks: >5 avg = Excellent, 3-5 = Good, 1-3 = Average, <1 = Below Average.
  2562. Return ONLY the JSON object.`;
  2563. try {
  2564. const pconf = await getActiveProviderConfig(request.workspaceId);
  2565. const model = pconf.model;
  2566. let text = '';
  2567. if (pconf.provider === 'ollama') {
  2568. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2569. text = res.data.response;
  2570. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2571. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2572. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2573. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2574. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2575. text = res.data.choices[0]?.message?.content || '';
  2576. } else if (pconf.provider === 'gemini') {
  2577. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2578. const res = await axios.post(
  2579. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2580. { contents: buildGeminiContents(prompt, system) },
  2581. { timeout: 120000 },
  2582. );
  2583. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2584. } else {
  2585. return reply.code(400).send({ error: 'AI not configured' });
  2586. }
  2587. let audit = null;
  2588. try {
  2589. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2590. audit = JSON.parse(jsonStr);
  2591. if (typeof audit.score !== 'number') throw new Error();
  2592. } catch {
  2593. return reply.code(503).send({ error: 'AI returned invalid audit format — try again' });
  2594. }
  2595. log.info({ action: 'analytics_audit', account: request.query.account || 'all', outcome: 'success' });
  2596. return {
  2597. success: true,
  2598. ...audit,
  2599. stats: { postsLast30, postsLast7, postsPerWeek, platforms, successRate, avgEngagement },
  2600. generatedAt: new Date(),
  2601. };
  2602. } catch (err) {
  2603. return reply.code(503).send({ error: 'Audit failed', detail: err.message });
  2604. }
  2605. });
  2606. // ─── Hashtag Groups ───────────────────────────────────────────────────────────
  2607. app.get('/hashtag-groups', async (request) => {
  2608. const ws = request.workspaceId;
  2609. const db = await getDb();
  2610. const groups = await db.collection('hashtag_groups').find({ workspaceId: ws }).sort({ name: 1 }).toArray();
  2611. return { groups };
  2612. });
  2613. app.post('/hashtag-groups', async (request, reply) => {
  2614. const ws = request.workspaceId;
  2615. const { name, hashtags } = request.body || {};
  2616. if (!name?.trim()) return reply.code(400).send({ error: 'name is required' });
  2617. const tags = (hashtags || []).map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2618. const db = await getDb();
  2619. const result = await db.collection('hashtag_groups').insertOne({
  2620. workspaceId: ws,
  2621. name: name.trim(),
  2622. hashtags: [...new Set(tags)],
  2623. createdAt: new Date(),
  2624. updatedAt: new Date(),
  2625. });
  2626. return { success: true, _id: result.insertedId };
  2627. });
  2628. app.put('/hashtag-groups/:id', async (request, reply) => {
  2629. const ws = request.workspaceId;
  2630. const { id } = request.params;
  2631. const { name, hashtags } = request.body || {};
  2632. const update = { updatedAt: new Date() };
  2633. if (name?.trim()) update.name = name.trim();
  2634. if (hashtags) {
  2635. const tags = hashtags.map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2636. update.hashtags = [...new Set(tags)];
  2637. }
  2638. const db = await getDb();
  2639. let oid;
  2640. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2641. await db.collection('hashtag_groups').updateOne({ _id: oid, workspaceId: ws }, { $set: update });
  2642. return { success: true };
  2643. });
  2644. app.delete('/hashtag-groups/:id', async (request, reply) => {
  2645. const ws = request.workspaceId;
  2646. const { id } = request.params;
  2647. const db = await getDb();
  2648. let oid;
  2649. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2650. await db.collection('hashtag_groups').deleteOne({ _id: oid, workspaceId: ws });
  2651. return { success: true };
  2652. });
  2653. // ─── Hashtag Stats & Scraper ──────────────────────────────────────────────────
  2654. const HASHTAG_RE = /#([a-zA-Z]\w*)/g;
  2655. function extractHashtags(text) {
  2656. if (!text) return [];
  2657. const tags = [];
  2658. let m;
  2659. HASHTAG_RE.lastIndex = 0;
  2660. while ((m = HASHTAG_RE.exec(text)) !== null) tags.push(`#${m[1].toLowerCase()}`);
  2661. return tags;
  2662. }
  2663. function gradeHashtag(count, avgEngagement) {
  2664. if (count >= 5 && avgEngagement >= 10) return 'A';
  2665. if (count >= 3 && avgEngagement >= 3) return 'B';
  2666. if (count >= 2) return 'C';
  2667. return 'D';
  2668. }
  2669. // POST /hashtags/scrape — scan YOUR published posts per-account.
  2670. // Body: { accountKey?: string } — omit to scan all accounts at once.
  2671. app.post('/hashtags/scrape', async (request) => {
  2672. const ws = request.workspaceId;
  2673. const { accountKey: filterAccount } = request.body || {};
  2674. const db = await getDb();
  2675. // tagMap key: `${accountKey}||${hashtag}`
  2676. const tagMap = {};
  2677. function touch(tag, accountKey, platform, engagement) {
  2678. const key = `${accountKey}||${tag}`;
  2679. if (!tagMap[key]) tagMap[key] = { tag, accountKey, count: 0, totalEngagement: 0, platforms: new Set() };
  2680. tagMap[key].count++;
  2681. tagMap[key].totalEngagement += engagement;
  2682. tagMap[key].platforms.add(platform);
  2683. }
  2684. // Engagement lookup keyed by content fingerprint
  2685. const postMetrics = await db.collection('post_metrics').find({ workspaceId: ws }).toArray();
  2686. const metricsByContent = {};
  2687. for (const m of postMetrics) {
  2688. if (m.content) {
  2689. const key = m.content.slice(0, 100).toLowerCase().trim();
  2690. metricsByContent[key] = (metricsByContent[key] || 0) + (m.metrics?.engagementTotal || 0);
  2691. }
  2692. }
  2693. // Scan YOUR published posts only — feeds are others' content, not your performance
  2694. const posts = await db.collection('posts').find({ workspaceId: ws }, { projection: { content: 1, destinations: 1 } }).toArray();
  2695. for (const post of posts) {
  2696. const tags = extractHashtags(post.content || '');
  2697. if (!tags.length) continue;
  2698. const engagement = post.content
  2699. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  2700. : 0;
  2701. const destinations = post.destinations?.length ? post.destinations : [{ platform: 'unknown' }];
  2702. for (const dest of destinations) {
  2703. const acctKey = dest.accountId ? `${dest.platform}:${dest.accountId}` : dest.platform;
  2704. if (filterAccount && acctKey !== filterAccount) continue;
  2705. for (const tag of tags) {
  2706. touch(tag, acctKey, dest.platform, engagement / Math.max(tags.length, 1));
  2707. }
  2708. }
  2709. }
  2710. let scraped = 0;
  2711. for (const [compoundKey, data] of Object.entries(tagMap)) {
  2712. const avgEngagement = data.count > 0 ? data.totalEngagement / data.count : 0;
  2713. await db.collection('hashtag_stats').updateOne(
  2714. { _id: compoundKey, workspaceId: ws },
  2715. {
  2716. $set: {
  2717. workspaceId: ws,
  2718. hashtag: data.tag,
  2719. accountKey: data.accountKey,
  2720. count: data.count,
  2721. avgEngagement: Math.round(avgEngagement * 10) / 10,
  2722. grade: gradeHashtag(data.count, avgEngagement),
  2723. platforms: [...data.platforms],
  2724. lastScraped: new Date(),
  2725. },
  2726. },
  2727. { upsert: true }
  2728. );
  2729. scraped++;
  2730. }
  2731. log.info({ action: 'hashtag_scrape', accountKey: filterAccount || 'all', outcome: 'success', scraped });
  2732. return { success: true, scraped };
  2733. });
  2734. app.get('/hashtags/stats', async (request) => {
  2735. const ws = request.workspaceId;
  2736. const { sort, accountKey } = request.query;
  2737. const db = await getDb();
  2738. const sortField = sort === 'engagement' ? 'avgEngagement' : 'count';
  2739. if (accountKey) {
  2740. // Per-account view
  2741. const stats = await db.collection('hashtag_stats')
  2742. .find({ workspaceId: ws, accountKey })
  2743. .sort({ [sortField]: -1 })
  2744. .limit(200)
  2745. .toArray();
  2746. return { stats };
  2747. }
  2748. // Aggregate view: group by hashtag across all accounts in this workspace
  2749. const allStats = await db.collection('hashtag_stats').find({ workspaceId: ws, accountKey: { $exists: true } }).toArray();
  2750. const grouped = new Map();
  2751. for (const s of allStats) {
  2752. if (!s.hashtag) continue;
  2753. if (!grouped.has(s.hashtag)) {
  2754. grouped.set(s.hashtag, { count: 0, totalEngagement: 0, totalCount: 0, platforms: new Set(), lastScraped: null });
  2755. }
  2756. const g = grouped.get(s.hashtag);
  2757. g.count += s.count;
  2758. g.totalEngagement += s.avgEngagement * s.count;
  2759. g.totalCount += s.count;
  2760. for (const p of (s.platforms || [])) g.platforms.add(p);
  2761. if (!g.lastScraped || (s.lastScraped && new Date(s.lastScraped) > new Date(g.lastScraped))) g.lastScraped = s.lastScraped;
  2762. }
  2763. const stats = [...grouped.entries()]
  2764. .map(([tag, g]) => {
  2765. const avgEngagement = g.totalCount > 0 ? Math.round((g.totalEngagement / g.totalCount) * 10) / 10 : 0;
  2766. return {
  2767. _id: tag,
  2768. hashtag: tag,
  2769. accountKey: null,
  2770. count: g.count,
  2771. avgEngagement,
  2772. grade: gradeHashtag(g.count, avgEngagement),
  2773. platforms: [...g.platforms],
  2774. lastScraped: g.lastScraped,
  2775. };
  2776. })
  2777. .sort((a, b) => b[sortField] - a[sortField])
  2778. .slice(0, 200);
  2779. return { stats };
  2780. });
  2781. app.post('/hashtags/ai-suggest', async (request, reply) => {
  2782. const ws = request.workspaceId;
  2783. const { accountKey, topTags = [], count = 20 } = request.body || {};
  2784. let profileCtx = '';
  2785. if (accountKey) {
  2786. try {
  2787. const db = await getDb();
  2788. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  2789. if (profile) {
  2790. const parts = [];
  2791. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  2792. if (profile.description) parts.push(`Description: ${profile.description}`);
  2793. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  2794. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  2795. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  2796. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  2797. profileCtx = parts.join('\n');
  2798. }
  2799. } catch (_) {}
  2800. }
  2801. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  2802. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  2803. const prompt = [
  2804. `Suggest ${count} high-performing hashtags for a social media account.`,
  2805. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  2806. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  2807. `\nReturn exactly ${count} unique hashtags as a space-separated list. Mix popular and niche tags. Include a variety of sizes (broad, medium, niche). Example: #photography #naturephotography #landscapephoto`,
  2808. ].filter(Boolean).join('');
  2809. try {
  2810. const pconf = await getActiveProviderConfig(request.workspaceId);
  2811. const model = pconf.model;
  2812. let text = '';
  2813. if (pconf.provider === 'ollama') {
  2814. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  2815. text = res.data.response;
  2816. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2817. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2818. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2819. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2820. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  2821. text = res.data.choices[0]?.message?.content || '';
  2822. } else if (pconf.provider === 'gemini') {
  2823. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2824. const res = await axios.post(
  2825. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2826. { contents: buildGeminiContents(prompt, system) },
  2827. { timeout: 60000 },
  2828. );
  2829. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2830. } else {
  2831. return reply.code(400).send({ error: 'AI not configured' });
  2832. }
  2833. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  2834. return { success: true, hashtags: tags };
  2835. } catch (err) {
  2836. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  2837. }
  2838. });
  2839. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  2840. async function extractTextFromUrl(url) {
  2841. try {
  2842. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  2843. const html = res.data || '';
  2844. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  2845. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  2846. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  2847. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  2848. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  2849. } catch {
  2850. return '';
  2851. }
  2852. }
  2853. async function scrapeBluesky(profileUrl) {
  2854. try {
  2855. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  2856. if (!handle) return '';
  2857. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  2858. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  2859. return posts.join('\n').slice(0, 3000);
  2860. } catch {
  2861. return '';
  2862. }
  2863. }
  2864. async function scrapeMastodon(profileUrl) {
  2865. try {
  2866. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  2867. if (!m) return '';
  2868. const [, instance, username] = m;
  2869. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  2870. const accountId = lookupRes.data?.id;
  2871. if (!accountId) return '';
  2872. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  2873. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  2874. return posts.join('\n').slice(0, 3000);
  2875. } catch {
  2876. return '';
  2877. }
  2878. }
  2879. async function runCompetitorScrape(competitorId) {
  2880. const db = await getDb();
  2881. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  2882. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  2883. const newItems = [];
  2884. if (competitor.websiteUrl) {
  2885. const text = await extractTextFromUrl(competitor.websiteUrl);
  2886. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  2887. }
  2888. const socialEntries = Object.entries(competitor.socialUrls || {});
  2889. for (const [platform, url] of socialEntries) {
  2890. if (!url) continue;
  2891. let text = '';
  2892. if (platform === 'bluesky') text = await scrapeBluesky(url);
  2893. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  2894. else text = await extractTextFromUrl(url);
  2895. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  2896. }
  2897. const existing = competitor.scrapedContent || [];
  2898. // Detect whether any newly scraped content differs from what was previously stored
  2899. const existingFingerprints = new Set(existing.map((s) => s.url + '||' + s.text.slice(0, 200)));
  2900. const contentChanged = newItems.some((item) => !existingFingerprints.has(item.url + '||' + item.text.slice(0, 200)));
  2901. const combined = [...newItems, ...existing].slice(0, 20);
  2902. await db.collection('competitors').updateOne(
  2903. { _id: new ObjectId(competitorId) },
  2904. { $set: { scrapedContent: combined, contentChanged, lastScraped: new Date(), updatedAt: new Date() } },
  2905. );
  2906. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  2907. }
  2908. async function buildCompetitorSystemSuffix(ws = 'default') {
  2909. try {
  2910. const db = await getDb();
  2911. const competitors = await db.collection('competitors').find({
  2912. workspaceId: ws,
  2913. $or: [{ 'aiAnalysis.positioning': { $nin: ['', null] } }, { aiSummary: { $nin: ['', null] } }],
  2914. }).toArray();
  2915. if (!competitors.length) return '';
  2916. const lines = competitors.map((c) => {
  2917. if (c.aiAnalysis?.positioning) {
  2918. const a = c.aiAnalysis;
  2919. const parts = [`- ${c.name}:`];
  2920. if (a.positioning) parts.push(` Positioning: ${a.positioning}`);
  2921. if (a.gaps?.length) parts.push(` Weaknesses/gaps: ${a.gaps.join('; ')}`);
  2922. if (a.themes?.length) parts.push(` Key themes: ${a.themes.join(', ')}`);
  2923. return parts.join('\n');
  2924. }
  2925. return `- ${c.name}: ${c.aiSummary}`;
  2926. }).join('\n');
  2927. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  2928. } catch {
  2929. return '';
  2930. }
  2931. }
  2932. // Save Google Places API key (used for local competitor discovery)
  2933. app.post('/credentials/google-places', async (request, reply) => {
  2934. const ws = request.workspaceId;
  2935. const { apiKey } = request.body || {};
  2936. if (!apiKey?.trim()) return reply.code(400).send({ error: 'apiKey is required' });
  2937. await setCredentials(ws, 'google_places', { apiKey: apiKey.trim() });
  2938. return { success: true };
  2939. });
  2940. app.get('/credentials/google-places', async (request) => {
  2941. const ws = request.workspaceId;
  2942. const cred = await getCredentials(ws, 'google_places');
  2943. return { configured: !!cred?.apiKey, keyHint: cred?.apiKey ? `****${cred.apiKey.slice(-4)}` : null };
  2944. });
  2945. app.delete('/credentials/google-places', async (request) => {
  2946. const ws = request.workspaceId;
  2947. await deleteCredentials(ws, 'google_places');
  2948. return { success: true };
  2949. });
  2950. // Discover local competitors via Google Places API
  2951. app.post('/competitors/discover-local', async (request, reply) => {
  2952. const ws = request.workspaceId;
  2953. const { location, businessType, radiusMeters = 5000 } = request.body || {};
  2954. if (!location) return reply.code(400).send({ error: 'location is required' });
  2955. const cred = await getCredentials(ws, 'google_places');
  2956. if (!cred?.apiKey) return reply.code(400).send({ error: 'Google Places API key not configured — add it in Settings.' });
  2957. // Step 1: Geocode the location string to coordinates
  2958. let lat, lng;
  2959. try {
  2960. const geoRes = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
  2961. params: { address: location, key: cred.apiKey },
  2962. timeout: 10000,
  2963. });
  2964. const loc = geoRes.data.results?.[0]?.geometry?.location;
  2965. if (!loc) return reply.code(400).send({ error: `Could not geocode location: "${location}"` });
  2966. lat = loc.lat;
  2967. lng = loc.lng;
  2968. } catch (err) {
  2969. return reply.code(503).send({ error: 'Geocoding failed', detail: err.message });
  2970. }
  2971. // Step 2: Text Search for nearby businesses of the given type
  2972. try {
  2973. const query = businessType ? `${businessType} near ${location}` : location;
  2974. const searchRes = await axios.get('https://maps.googleapis.com/maps/api/place/textsearch/json', {
  2975. params: {
  2976. query,
  2977. location: `${lat},${lng}`,
  2978. radius: Math.min(radiusMeters, 50000),
  2979. key: cred.apiKey,
  2980. },
  2981. timeout: 10000,
  2982. });
  2983. const places = (searchRes.data.results || []).slice(0, 10);
  2984. if (!places.length) return { success: true, suggestions: [] };
  2985. // Step 3: Fetch website URLs for places that have them
  2986. const suggestions = [];
  2987. for (const place of places.slice(0, 8)) {
  2988. try {
  2989. const detailRes = await axios.get('https://maps.googleapis.com/maps/api/place/details/json', {
  2990. params: { place_id: place.place_id, fields: 'name,website,formatted_address,rating', key: cred.apiKey },
  2991. timeout: 8000,
  2992. });
  2993. const detail = detailRes.data.result || {};
  2994. suggestions.push({
  2995. name: detail.name || place.name,
  2996. websiteUrl: detail.website || null,
  2997. address: detail.formatted_address || '',
  2998. rating: detail.rating || null,
  2999. reason: `Local ${businessType || 'business'} near ${location}${detail.rating ? ` · ${detail.rating}★` : ''}`,
  3000. });
  3001. } catch {
  3002. suggestions.push({ name: place.name, websiteUrl: null, address: '', rating: null, reason: `Local ${businessType || 'business'} near ${location}` });
  3003. }
  3004. }
  3005. log.info({ action: 'discover_local_competitors', location, count: suggestions.length, outcome: 'success' });
  3006. return { success: true, suggestions };
  3007. } catch (err) {
  3008. return reply.code(503).send({ error: 'Google Places search failed', detail: err.message });
  3009. }
  3010. });
  3011. // Discover competitors automatically using AI + account profile context
  3012. app.post('/competitors/discover', async (request, reply) => {
  3013. const ws = request.workspaceId;
  3014. const db = await getDb();
  3015. // Use the first account profile for business context
  3016. const profile = await db.collection('account_profiles').findOne({ workspaceId: ws });
  3017. const contextParts = [];
  3018. if (profile) {
  3019. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  3020. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  3021. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  3022. if (profile.websiteUrl) contextParts.push(`Website: ${profile.websiteUrl}`);
  3023. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  3024. }
  3025. if (!contextParts.length) {
  3026. return reply.code(400).send({ error: 'Set up at least one Account Profile in Settings before discovering competitors.' });
  3027. }
  3028. const system = 'You are a market research analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  3029. const prompt = `Based on the following business profile, identify the top 5 direct competitors.
  3030. ${contextParts.join('\n')}
  3031. Return ONLY a JSON array of objects, e.g.:
  3032. [{"name":"Competitor Name","websiteUrl":"https://example.com","reason":"One sentence on why they compete directly"}]
  3033. Rules:
  3034. - Return real, existing businesses only.
  3035. - Include only direct competitors (same product/service category, same target audience).
  3036. - websiteUrl must be a valid https URL to the competitor's main website.
  3037. - No explanation outside the JSON array.`;
  3038. try {
  3039. const pconf = await getActiveProviderConfig(request.workspaceId);
  3040. const model = pconf.model;
  3041. let text = '';
  3042. if (pconf.provider === 'ollama') {
  3043. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3044. text = res.data.response;
  3045. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3046. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3047. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3048. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3049. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3050. text = res.data.choices[0]?.message?.content || '';
  3051. } else if (pconf.provider === 'gemini') {
  3052. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3053. const res = await axios.post(
  3054. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3055. { contents: buildGeminiContents(prompt, system) },
  3056. { timeout: 120000 },
  3057. );
  3058. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3059. } else {
  3060. return reply.code(400).send({ error: 'AI not configured' });
  3061. }
  3062. let suggestions = [];
  3063. try {
  3064. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3065. const parsed = JSON.parse(jsonStr);
  3066. if (!Array.isArray(parsed)) throw new Error();
  3067. suggestions = parsed
  3068. .filter((s) => s && typeof s.name === 'string' && typeof s.websiteUrl === 'string')
  3069. .slice(0, 5)
  3070. .map((s) => ({
  3071. name: s.name.trim(),
  3072. websiteUrl: s.websiteUrl.trim(),
  3073. reason: typeof s.reason === 'string' ? s.reason.trim() : '',
  3074. }));
  3075. } catch {
  3076. return reply.code(503).send({ error: 'AI returned invalid format — try again' });
  3077. }
  3078. log.info({ action: 'competitor_discover', count: suggestions.length, outcome: 'success' });
  3079. return { success: true, suggestions };
  3080. } catch (err) {
  3081. return reply.code(503).send({ error: 'Discovery failed', detail: err.message });
  3082. }
  3083. });
  3084. // List competitors
  3085. app.get('/competitors', async (request) => {
  3086. const ws = request.workspaceId;
  3087. const db = await getDb();
  3088. const list = await db.collection('competitors').find({ workspaceId: ws }).sort({ createdAt: 1 }).toArray();
  3089. return list;
  3090. });
  3091. // Add competitor (max 5 per workspace)
  3092. app.post('/competitors', async (request, reply) => {
  3093. const ws = request.workspaceId;
  3094. const db = await getDb();
  3095. const count = await db.collection('competitors').countDocuments({ workspaceId: ws });
  3096. if (count >= 5) return reply.code(400).send({ error: 'Maximum 5 competitors allowed' });
  3097. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  3098. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  3099. const now = new Date();
  3100. const result = await db.collection('competitors').insertOne({
  3101. workspaceId: ws, name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  3102. });
  3103. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  3104. return doc;
  3105. });
  3106. // Update competitor
  3107. app.put('/competitors/:id', async (request, reply) => {
  3108. const ws = request.workspaceId;
  3109. const db = await getDb();
  3110. const { name, websiteUrl, socialUrls } = request.body || {};
  3111. const updates = { updatedAt: new Date() };
  3112. if (name !== undefined) updates.name = name;
  3113. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  3114. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  3115. const oid = new ObjectId(request.params.id);
  3116. await db.collection('competitors').updateOne({ _id: oid, workspaceId: ws }, { $set: updates });
  3117. const doc = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3118. return doc;
  3119. });
  3120. // Delete competitor
  3121. app.delete('/competitors/:id', async (request, reply) => {
  3122. const ws = request.workspaceId;
  3123. const db = await getDb();
  3124. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id), workspaceId: ws });
  3125. return { success: true };
  3126. });
  3127. // Scrape one competitor — returns jobId immediately, runs in background
  3128. app.post('/competitors/:id/scrape', async (request, reply) => {
  3129. const jobId = new ObjectId().toString();
  3130. activeScrapeJobs.set(jobId, { status: 'running', sources: 0, message: '' });
  3131. (async () => {
  3132. try {
  3133. const result = await runCompetitorScrape(request.params.id);
  3134. activeScrapeJobs.set(jobId, {
  3135. status: result.ok ? 'done' : 'failed',
  3136. sources: result.sources,
  3137. message: result.message,
  3138. });
  3139. } catch (err) {
  3140. activeScrapeJobs.set(jobId, { status: 'failed', sources: 0, message: err.message });
  3141. }
  3142. })();
  3143. return reply.code(202).send({ jobId });
  3144. });
  3145. // Poll scrape job status
  3146. app.get('/competitors/:id/scrape-status/:jobId', async (request, reply) => {
  3147. const job = activeScrapeJobs.get(request.params.jobId);
  3148. if (!job) return reply.code(404).send({ error: 'Job not found or expired' });
  3149. return job;
  3150. });
  3151. // Scrape all competitors (called by scheduler — always operates on default workspace)
  3152. app.post('/competitors/scrape-all', async (request, reply) => {
  3153. const ws = request.workspaceId;
  3154. const db = await getDb();
  3155. const all = await db.collection('competitors').find({ workspaceId: ws }).toArray();
  3156. const results = [];
  3157. for (const c of all) {
  3158. const r = await runCompetitorScrape(c._id.toString());
  3159. results.push({ id: c._id.toString(), name: c.name, ...r });
  3160. }
  3161. return { success: true, results };
  3162. });
  3163. // Summarize competitor content with AI — returns structured analysis
  3164. app.post('/competitors/:id/summarize', async (request, reply) => {
  3165. const ws = request.workspaceId;
  3166. const db = await getDb();
  3167. const oid = new ObjectId(request.params.id);
  3168. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3169. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3170. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  3171. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  3172. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  3173. const prompt = `Analyse the following content from "${competitor.name}" and return a JSON object with exactly these fields:
  3174. {
  3175. "themes": ["3-5 main content topics or pillars they focus on"],
  3176. "tone": "one sentence describing their voice and communication style",
  3177. "positioning": "one sentence on how they position themselves in the market",
  3178. "gaps": ["2-3 topics or angles they ignore or handle poorly — opportunities for you"],
  3179. "moves": ["3 specific content angles you could use to stand out against them"],
  3180. "profile": {
  3181. "pricing": "one sentence on their pricing model or tier (e.g. 'Freemium with $49/mo Pro plan', 'Premium only, starts at $99/mo', or 'Pricing not visible' if unclear)",
  3182. "keyFeatures": ["3-5 core product or service features they emphasise"],
  3183. "marketingChannels": ["2-4 social/marketing channels they actively use based on content"],
  3184. "targetCustomer": "one sentence describing their apparent ideal customer"
  3185. },
  3186. "prediction": {
  3187. "satisfiedWithPosition": <true if they appear content with their current position, false if they seem to be pushing for growth>,
  3188. "likelyNextMoves": ["2-3 strategic moves they will probably make based on current trajectory"],
  3189. "vulnerabilities": ["2-3 specific weaknesses or blind spots visible in their content"],
  3190. "retaliationTriggers": ["1-2 moves by a competitor that would most likely provoke a strong response from them"]
  3191. }
  3192. }
  3193. Content:
  3194. ${content}
  3195. Return ONLY the JSON object. No explanation, no markdown.`;
  3196. try {
  3197. const pconf = await getActiveProviderConfig(request.workspaceId);
  3198. const model = pconf.model;
  3199. let text = '';
  3200. if (pconf.provider === 'ollama') {
  3201. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  3202. text = res.data.response;
  3203. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3204. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3205. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3206. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3207. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  3208. text = res.data.choices[0]?.message?.content || '';
  3209. } else if (pconf.provider === 'gemini') {
  3210. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3211. const res = await axios.post(
  3212. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3213. { contents: buildGeminiContents(prompt, system) },
  3214. { timeout: 180000 },
  3215. );
  3216. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3217. } else {
  3218. return reply.code(400).send({ error: 'AI not configured' });
  3219. }
  3220. let aiAnalysis = null;
  3221. try {
  3222. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3223. aiAnalysis = JSON.parse(jsonStr);
  3224. if (!Array.isArray(aiAnalysis.themes)) aiAnalysis.themes = [];
  3225. if (typeof aiAnalysis.tone !== 'string') aiAnalysis.tone = '';
  3226. if (typeof aiAnalysis.positioning !== 'string') aiAnalysis.positioning = '';
  3227. if (!Array.isArray(aiAnalysis.gaps)) aiAnalysis.gaps = [];
  3228. if (!Array.isArray(aiAnalysis.moves)) aiAnalysis.moves = [];
  3229. // Validate profile block
  3230. if (!aiAnalysis.profile || typeof aiAnalysis.profile !== 'object') aiAnalysis.profile = {};
  3231. if (typeof aiAnalysis.profile.pricing !== 'string') aiAnalysis.profile.pricing = '';
  3232. if (!Array.isArray(aiAnalysis.profile.keyFeatures)) aiAnalysis.profile.keyFeatures = [];
  3233. if (!Array.isArray(aiAnalysis.profile.marketingChannels)) aiAnalysis.profile.marketingChannels = [];
  3234. if (typeof aiAnalysis.profile.targetCustomer !== 'string') aiAnalysis.profile.targetCustomer = '';
  3235. // Validate prediction block
  3236. if (!aiAnalysis.prediction || typeof aiAnalysis.prediction !== 'object') aiAnalysis.prediction = {};
  3237. if (typeof aiAnalysis.prediction.satisfiedWithPosition !== 'boolean') aiAnalysis.prediction.satisfiedWithPosition = true;
  3238. if (!Array.isArray(aiAnalysis.prediction.likelyNextMoves)) aiAnalysis.prediction.likelyNextMoves = [];
  3239. if (!Array.isArray(aiAnalysis.prediction.vulnerabilities)) aiAnalysis.prediction.vulnerabilities = [];
  3240. if (!Array.isArray(aiAnalysis.prediction.retaliationTriggers)) aiAnalysis.prediction.retaliationTriggers = [];
  3241. } catch {
  3242. aiAnalysis = null;
  3243. }
  3244. if (!aiAnalysis) return reply.code(503).send({ error: 'AI returned invalid analysis format — try again' });
  3245. await db.collection('competitors').updateOne(
  3246. { _id: oid, workspaceId: ws },
  3247. { $set: { aiAnalysis, aiSummary: '', updatedAt: new Date() } },
  3248. );
  3249. return { success: true, aiAnalysis };
  3250. } catch (err) {
  3251. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  3252. }
  3253. });
  3254. // Extract keywords from scraped content using AI (item 34)
  3255. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  3256. const ws = request.workspaceId;
  3257. const db = await getDb();
  3258. const oid = new ObjectId(request.params.id);
  3259. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3260. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3261. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  3262. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  3263. const system = 'You are an SEO and content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  3264. const prompt = `Analyse the following content from "${competitor.name}" and extract the top 20 keywords and key phrases they appear to be targeting. For each keyword, classify its search intent using one of these four types:
  3265. - informational: user wants to learn ("how to", "what is", "guide", "tips")
  3266. - commercial: user is evaluating options ("best", "vs", "review", "top", "alternative")
  3267. - transactional: user is ready to act ("buy", "free", "pricing", "download", "get started")
  3268. - navigational: user is searching for a specific brand or tool by name
  3269. Content:
  3270. ${content}
  3271. Return ONLY a JSON array, e.g.:
  3272. [{"term": "project management software", "intent": "commercial"}, {"term": "how to manage tasks", "intent": "informational"}]
  3273. No explanation, no markdown.`;
  3274. try {
  3275. const pconf = await getActiveProviderConfig(request.workspaceId);
  3276. const model = pconf.model;
  3277. let text = '';
  3278. if (pconf.provider === 'ollama') {
  3279. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3280. text = res.data.response;
  3281. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3282. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3283. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3284. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3285. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3286. text = res.data.choices[0]?.message?.content || '';
  3287. } else if (pconf.provider === 'gemini') {
  3288. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3289. const res = await axios.post(
  3290. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3291. { contents: buildGeminiContents(prompt, system) },
  3292. { timeout: 120000 },
  3293. );
  3294. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3295. } else {
  3296. return reply.code(400).send({ error: 'AI not configured' });
  3297. }
  3298. const VALID_INTENTS = new Set(['informational', 'commercial', 'transactional', 'navigational']);
  3299. let keywords = [];
  3300. try {
  3301. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3302. const parsed = JSON.parse(jsonStr);
  3303. if (!Array.isArray(parsed)) throw new Error();
  3304. const now = new Date();
  3305. keywords = parsed
  3306. .filter((k) => k && typeof k.term === 'string' && k.term.trim())
  3307. .slice(0, 20)
  3308. .map((k) => ({
  3309. term: k.term.trim(),
  3310. intent: VALID_INTENTS.has(k.intent) ? k.intent : 'informational',
  3311. extractedAt: now,
  3312. }));
  3313. } catch {
  3314. keywords = [];
  3315. }
  3316. await db.collection('competitors').updateOne(
  3317. { _id: oid, workspaceId: ws },
  3318. { $set: { keywords, updatedAt: new Date() } },
  3319. );
  3320. return { success: true, keywords };
  3321. } catch (err) {
  3322. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  3323. }
  3324. });
  3325. // Analyse content gaps — compare competitor keywords against user's hashtag_stats
  3326. app.post('/competitors/:id/analyze-gaps', async (request, reply) => {
  3327. const ws = request.workspaceId;
  3328. const db = await getDb();
  3329. const oid = new ObjectId(request.params.id);
  3330. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3331. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3332. const keywords = (competitor.keywords || []);
  3333. if (!keywords.length) return reply.code(400).send({ error: 'Extract keywords first before analysing gaps' });
  3334. const hashtagDocs = await db.collection('hashtag_stats')
  3335. .find({ workspaceId: ws, accountKey: { $exists: true } }, { projection: { _id: 0, hashtag: 1 } })
  3336. .toArray();
  3337. const hashtagStatsEmpty = hashtagDocs.length === 0;
  3338. // Deduplicate across accounts — same hashtag used by any account counts as covered
  3339. const uniqueTags = [...new Set(hashtagDocs.map((h) => h.hashtag).filter(Boolean))];
  3340. const hashtagTexts = uniqueTags.map((tag) => ({ id: tag, text: tag.replace(/^#/, '').toLowerCase() }));
  3341. const INTENT_ORDER = { transactional: 0, commercial: 1, informational: 2, navigational: 3 };
  3342. function findMatchingHashtags(term) {
  3343. const words = term.toLowerCase().split(/\s+/).filter((w) => w.length >= 4);
  3344. return hashtagTexts
  3345. .filter(({ text }) => words.some((w) => text.includes(w)))
  3346. .map(({ id }) => id);
  3347. }
  3348. const gaps = [];
  3349. const covered = [];
  3350. for (const kw of keywords) {
  3351. const term = typeof kw === 'string' ? kw : kw.term;
  3352. const intent = typeof kw === 'string' ? 'informational' : (kw.intent || 'informational');
  3353. const matched = findMatchingHashtags(term);
  3354. if (matched.length) {
  3355. covered.push({ term, intent, matchedHashtags: matched.slice(0, 4) });
  3356. } else {
  3357. gaps.push({ term, intent });
  3358. }
  3359. }
  3360. gaps.sort((a, b) => (INTENT_ORDER[a.intent] ?? 99) - (INTENT_ORDER[b.intent] ?? 99));
  3361. const gapAnalysis = { gaps, covered, totalKeywords: keywords.length, hashtagStatsEmpty, lastAnalyzed: new Date() };
  3362. await db.collection('competitors').updateOne(
  3363. { _id: oid, workspaceId: ws },
  3364. { $set: { gapAnalysis, updatedAt: new Date() } },
  3365. );
  3366. return { success: true, ...gapAnalysis };
  3367. });
  3368. // Detect and classify market signals from latest scraped content
  3369. app.post('/competitors/:id/detect-signals', async (request, reply) => {
  3370. const ws = request.workspaceId;
  3371. const db = await getDb();
  3372. const oid = new ObjectId(request.params.id);
  3373. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3374. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3375. const recentContent = (competitor.scrapedContent || []).slice(0, 10);
  3376. if (!recentContent.length) return reply.code(400).send({ error: 'Scrape first before detecting signals' });
  3377. const contentText = recentContent.map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 4000);
  3378. const baseline = competitor.aiAnalysis
  3379. ? `Previous profile — Themes: ${(competitor.aiAnalysis.themes || []).join(', ')}. Tone: ${competitor.aiAnalysis.tone || 'unknown'}.`
  3380. : 'No prior analysis available.';
  3381. const system = 'You are a competitive intelligence analyst specialising in market signal detection. Return only valid JSON with no explanation, no markdown.';
  3382. const prompt = `Analyse the latest content from competitor "${competitor.name}" and detect any notable changes or strategic signals.
  3383. Baseline context:
  3384. ${baseline}
  3385. Latest scraped content:
  3386. ${contentText}
  3387. Classify any changes you detect. Use these signal types:
  3388. - topic_expansion: new content themes or topics not previously seen
  3389. - tone_shift: measurable change in communication style or voice
  3390. - campaign_launch: evidence of a new marketing campaign or product promotion
  3391. - pricing_change: any mention of new pricing, offers, or discounts
  3392. - market_entry: signs of entering a new platform, audience, or geography
  3393. - competitive_aggression: direct competitor comparisons, attack marketing, or poaching language
  3394. - frequency_change: evidence of significantly more or less content activity
  3395. Return ONLY a JSON array (empty array [] if no significant signals):
  3396. [{"type":"<type>","description":"<one sentence describing the specific change>","severity":"<low|medium|high>"}]
  3397. Severity guide: high = major strategic shift, medium = notable change worth monitoring, low = minor or uncertain change.`;
  3398. try {
  3399. const pconf = await getActiveProviderConfig(request.workspaceId);
  3400. const model = pconf.model;
  3401. let text = '';
  3402. if (pconf.provider === 'ollama') {
  3403. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3404. text = res.data.response;
  3405. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3406. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3407. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3408. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3409. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3410. text = res.data.choices[0]?.message?.content || '';
  3411. } else if (pconf.provider === 'gemini') {
  3412. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3413. const res = await axios.post(
  3414. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3415. { contents: buildGeminiContents(prompt, system) },
  3416. { timeout: 120000 },
  3417. );
  3418. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3419. } else {
  3420. return reply.code(400).send({ error: 'AI not configured' });
  3421. }
  3422. const VALID_TYPES = new Set(['topic_expansion', 'tone_shift', 'campaign_launch', 'pricing_change', 'market_entry', 'competitive_aggression', 'frequency_change']);
  3423. const VALID_SEVERITIES = new Set(['low', 'medium', 'high']);
  3424. let signals = [];
  3425. try {
  3426. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3427. const parsed = JSON.parse(jsonStr);
  3428. if (!Array.isArray(parsed)) throw new Error();
  3429. const now = new Date();
  3430. signals = parsed
  3431. .filter((s) => s && VALID_TYPES.has(s.type) && typeof s.description === 'string')
  3432. .slice(0, 8)
  3433. .map((s) => ({
  3434. type: s.type,
  3435. description: s.description.trim(),
  3436. severity: VALID_SEVERITIES.has(s.severity) ? s.severity : 'medium',
  3437. detectedAt: now,
  3438. }));
  3439. } catch {
  3440. signals = [];
  3441. }
  3442. await db.collection('competitors').updateOne(
  3443. { _id: oid, workspaceId: ws },
  3444. { $set: { signals, contentChanged: false, updatedAt: new Date() } },
  3445. );
  3446. log.info({ action: 'detect_signals', competitorId: request.params.id, count: signals.length, outcome: 'success' });
  3447. return { success: true, signals };
  3448. } catch (err) {
  3449. return reply.code(503).send({ error: 'Signal detection failed', detail: err.message });
  3450. }
  3451. });
  3452. // Generate a 5-post content roadmap from competitor keywords and gaps
  3453. app.post('/competitors/:id/content-roadmap', async (request, reply) => {
  3454. const ws = request.workspaceId;
  3455. const db = await getDb();
  3456. const oid = new ObjectId(request.params.id);
  3457. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3458. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3459. const keywords = (competitor.keywords || []);
  3460. const hasKeywords = keywords.length > 0;
  3461. const hasContent = (competitor.scrapedContent || []).length > 0;
  3462. if (!hasKeywords && !hasContent) return reply.code(400).send({ error: 'Extract keywords first before generating a roadmap' });
  3463. const kwList = hasKeywords
  3464. ? keywords.map((k) => (typeof k === 'string' ? k : k.term)).join(', ')
  3465. : '';
  3466. const gaps = competitor.aiAnalysis?.gaps || [];
  3467. const moves = competitor.aiAnalysis?.moves || [];
  3468. const gapsSection = gaps.length ? `\nCompetitor gaps/weaknesses:\n${gaps.map((g) => `- ${g}`).join('\n')}` : '';
  3469. const movesSection = moves.length ? `\nSuggested differentiation angles:\n${moves.map((m) => `- ${m}`).join('\n')}` : '';
  3470. const kwSection = kwList ? `\nCompetitor's keywords: ${kwList}` : '';
  3471. const system = 'You are a content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  3472. const prompt = `Create a 5-post content roadmap to compete against "${competitor.name}".
  3473. ${kwSection}${gapsSection}${movesSection}
  3474. Generate 5 post ideas that exploit their weaknesses and differentiate clearly. For each post return:
  3475. - topic: short topic name, max 8 words
  3476. - headline: an engaging opening line or hook ready to use as post content (1-2 sentences)
  3477. - keywords: array of 2-3 keywords from the competitor's list to target (use exact terms where available)
  3478. - rationale: one sentence on why this post wins against ${competitor.name}
  3479. Return ONLY a JSON array:
  3480. [{"topic":"...","headline":"...","keywords":["..."],"rationale":"..."}]
  3481. No explanation, no markdown.`;
  3482. try {
  3483. const pconf = await getActiveProviderConfig(request.workspaceId);
  3484. const model = pconf.model;
  3485. let text = '';
  3486. if (pconf.provider === 'ollama') {
  3487. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  3488. text = res.data.response;
  3489. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3490. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3491. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3492. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3493. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  3494. text = res.data.choices[0]?.message?.content || '';
  3495. } else if (pconf.provider === 'gemini') {
  3496. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3497. const res = await axios.post(
  3498. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3499. { contents: buildGeminiContents(prompt, system) },
  3500. { timeout: 180000 },
  3501. );
  3502. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3503. } else {
  3504. return reply.code(400).send({ error: 'AI not configured' });
  3505. }
  3506. let roadmap = [];
  3507. try {
  3508. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3509. const parsed = JSON.parse(jsonStr);
  3510. if (!Array.isArray(parsed)) throw new Error();
  3511. roadmap = parsed
  3512. .filter((p) => p && typeof p.topic === 'string' && typeof p.headline === 'string')
  3513. .slice(0, 5)
  3514. .map((p) => ({
  3515. topic: p.topic.trim(),
  3516. headline: p.headline.trim(),
  3517. keywords: Array.isArray(p.keywords) ? p.keywords.filter((k) => typeof k === 'string').slice(0, 3) : [],
  3518. rationale: typeof p.rationale === 'string' ? p.rationale.trim() : '',
  3519. }));
  3520. } catch {
  3521. roadmap = [];
  3522. }
  3523. if (!roadmap.length) return reply.code(503).send({ error: 'AI returned invalid roadmap format — try again' });
  3524. await db.collection('competitors').updateOne(
  3525. { _id: oid, workspaceId: ws },
  3526. { $set: { contentRoadmap: roadmap, updatedAt: new Date() } },
  3527. );
  3528. return { success: true, contentRoadmap: roadmap };
  3529. } catch (err) {
  3530. return reply.code(503).send({ error: 'Roadmap generation failed', detail: err.message });
  3531. }
  3532. });
  3533. // ─── Quantitative Competitor Extraction ──────────────────────────────────────
  3534. app.post('/competitors/:id/extract-quantitative', async (request, reply) => {
  3535. const ws = request.workspaceId;
  3536. const db = await getDb();
  3537. let oid;
  3538. try { oid = new ObjectId(request.params.id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  3539. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3540. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3541. if (!competitor.websiteUrl) return reply.code(400).send({ error: 'Competitor has no website URL' });
  3542. const baseUrl = competitor.websiteUrl.replace(/\/$/, '');
  3543. // Fetch additional sub-pages: /pricing, /features, /about, /careers
  3544. const subPaths = ['/pricing', '/features', '/about', '/careers'];
  3545. const pageTexts = await Promise.all([
  3546. extractTextFromUrl(baseUrl),
  3547. ...subPaths.map((p) => extractTextFromUrl(baseUrl + p)),
  3548. ]);
  3549. const combinedText = pageTexts.filter(Boolean).join('\n\n---\n\n').slice(0, 8000);
  3550. if (!combinedText.trim()) {
  3551. return reply.code(503).send({ error: 'Could not fetch any content from the competitor site' });
  3552. }
  3553. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no markdown or explanation.';
  3554. const prompt = `Extract quantitative competitive data from this competitor's website content.
  3555. Competitor: ${competitor.name} (${baseUrl})
  3556. Website content:
  3557. ${combinedText}
  3558. Return this JSON:
  3559. {
  3560. "pricingTiers": [{ "name": "<tier name>", "price": "<price or 'Free' or 'Contact us'>", "highlights": ["<feature>"] }],
  3561. "keyFeatures": ["<feature 1>", "<feature 2>", "<feature 3>", "<feature 4>", "<feature 5>"],
  3562. "techStack": ["<detected technology>"],
  3563. "targetCustomer": "<one-sentence ICP>",
  3564. "jobPostings": <number of open roles detected, 0 if none>,
  3565. "growthSignals": ["<any hiring, funding, expansion, or new product signals>"],
  3566. "productCount": <estimated number of distinct products/services, 0 if unclear>
  3567. }
  3568. If data is not available for a field, use null for numbers and [] for arrays. Return ONLY valid JSON.`;
  3569. try {
  3570. const pconf = await getActiveProviderConfig(request.workspaceId);
  3571. const model = pconf.model;
  3572. let text = '';
  3573. if (pconf.provider === 'ollama') {
  3574. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3575. text = res.data.response;
  3576. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3577. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3578. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3579. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3580. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3581. text = res.data.choices[0]?.message?.content || '';
  3582. } else if (pconf.provider === 'gemini') {
  3583. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3584. const res = await axios.post(
  3585. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3586. { contents: buildGeminiContents(prompt, system) },
  3587. { timeout: 120000 },
  3588. );
  3589. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3590. } else {
  3591. return reply.code(400).send({ error: 'AI not configured' });
  3592. }
  3593. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  3594. let profile = null;
  3595. try {
  3596. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3597. profile = JSON.parse(jsonStr);
  3598. if (!profile.keyFeatures) throw new Error('Missing keyFeatures');
  3599. } catch {
  3600. return reply.code(503).send({ error: 'AI returned invalid extraction format — try again' });
  3601. }
  3602. await db.collection('competitors').updateOne(
  3603. { _id: oid, workspaceId: ws },
  3604. { $set: { quantitativeProfile: profile, quantitativeExtractedAt: new Date(), updatedAt: new Date() } },
  3605. );
  3606. log.info({ action: 'extract_quantitative', competitor: competitor.name, outcome: 'success' });
  3607. return { success: true, quantitativeProfile: profile, extractedAt: new Date() };
  3608. } catch (err) {
  3609. return reply.code(503).send({ error: 'Quantitative extraction failed', detail: err.message });
  3610. }
  3611. });
  3612. // ─── Strategic Group Map ─────────────────────────────────────────────────────
  3613. const STRATEGIC_DIMENSIONS = [
  3614. 'Price level',
  3615. 'Product / service breadth',
  3616. 'Brand strength',
  3617. 'Technology leadership',
  3618. 'Market coverage',
  3619. 'Service quality',
  3620. 'Marketing intensity',
  3621. 'Geographic reach',
  3622. ];
  3623. app.post('/competitors/strategic-map', async (request, reply) => {
  3624. const ws = request.workspaceId;
  3625. const { xAxis, yAxis, accountKey } = request.body || {};
  3626. if (!xAxis || !yAxis) return reply.code(400).send({ error: 'xAxis and yAxis are required' });
  3627. if (xAxis === yAxis) return reply.code(400).send({ error: 'xAxis and yAxis must be different dimensions' });
  3628. const db = await getDb();
  3629. const competitors = await db.collection('competitors')
  3630. .find({ workspaceId: ws, aiAnalysis: { $exists: true } })
  3631. .toArray();
  3632. if (competitors.length < 1) {
  3633. return reply.code(400).send({ error: 'Run "Summarise with AI" on at least one competitor first.' });
  3634. }
  3635. const profile = accountKey
  3636. ? await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws })
  3637. : await db.collection('account_profiles').findOne({ workspaceId: ws });
  3638. const competitorBlocks = competitors.map((c) => {
  3639. const a = c.aiAnalysis || {};
  3640. return `${c.name}: positioning="${a.positioning || 'unknown'}", tone="${a.tone || 'unknown'}", themes=[${(a.themes || []).join(', ')}]`;
  3641. }).join('\n');
  3642. const yourBrand = profile
  3643. ? `Your brand: "${profile.businessName || 'Your brand'}" — ${profile.description || ''} — ${profile.toneOfVoice || ''}`
  3644. : 'Your brand: unknown';
  3645. const system = 'You are a Porter strategy analyst. Return only valid JSON with no markdown or explanation.';
  3646. const prompt = `Plot these players on a strategic group map using two dimensions: X = "${xAxis}", Y = "${yAxis}".
  3647. ${yourBrand}
  3648. ${competitorBlocks}
  3649. Assign each player a score 1–10 on each axis. 1 = lowest/weakest on that dimension, 10 = highest/strongest.
  3650. Return:
  3651. {
  3652. "players": [
  3653. { "name": "<name>", "x": <1-10>, "y": <1-10>, "isYou": <true if your brand, false otherwise>, "note": "<one phrase describing their position>" }
  3654. ],
  3655. "clusters": ["<describe a cluster group if 2+ players are close together>"],
  3656. "whitespace": ["<opportunity in a part of the map with no players>", "<second opportunity>"],
  3657. "insight": "<2-sentence strategic insight from the map>"
  3658. }
  3659. Include your brand as a player with isYou: true. Return ONLY valid JSON.`;
  3660. try {
  3661. const pconf = await getActiveProviderConfig(request.workspaceId);
  3662. const model = pconf.model;
  3663. let text = '';
  3664. if (pconf.provider === 'ollama') {
  3665. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  3666. text = res.data.response;
  3667. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3668. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3669. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3670. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3671. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  3672. text = res.data.choices[0]?.message?.content || '';
  3673. } else if (pconf.provider === 'gemini') {
  3674. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3675. const res = await axios.post(
  3676. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3677. { contents: buildGeminiContents(prompt, system) },
  3678. { timeout: 90000 },
  3679. );
  3680. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3681. } else {
  3682. return reply.code(400).send({ error: 'AI not configured' });
  3683. }
  3684. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  3685. let result = null;
  3686. try {
  3687. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3688. result = JSON.parse(jsonStr);
  3689. if (!Array.isArray(result.players)) throw new Error('Missing players array');
  3690. } catch {
  3691. return reply.code(503).send({ error: 'AI returned invalid strategic map format — try again' });
  3692. }
  3693. log.info({ action: 'strategic_map', xAxis, yAxis, players: result.players.length, outcome: 'success' });
  3694. return { success: true, xAxis, yAxis, ...result, generatedAt: new Date() };
  3695. } catch (err) {
  3696. return reply.code(503).send({ error: 'Strategic map failed', detail: err.message });
  3697. }
  3698. });
  3699. // ─── Competitor Social Matrix ────────────────────────────────────────────────
  3700. app.post('/competitors/social-matrix', async (request, reply) => {
  3701. const ws = request.workspaceId;
  3702. const db = await getDb();
  3703. const competitors = await db.collection('competitors')
  3704. .find({ workspaceId: ws, aiAnalysis: { $exists: true } })
  3705. .toArray();
  3706. if (competitors.length < 2) {
  3707. return reply.code(400).send({ error: 'Run "Summarise with AI" on at least 2 competitors first.' });
  3708. }
  3709. const competitorBlocks = competitors.map((c) => {
  3710. const a = c.aiAnalysis || {};
  3711. return [
  3712. `Competitor: ${c.name}`,
  3713. ` Positioning: ${a.positioning || 'unknown'}`,
  3714. ` Tone: ${a.tone || 'unknown'}`,
  3715. ` Themes: ${(a.themes || []).join(', ') || 'none'}`,
  3716. ` Weaknesses/Gaps: ${(a.gaps || []).join(', ') || 'none'}`,
  3717. ` Top keywords: ${(c.keywords || []).slice(0, 5).map((k) => k.term).join(', ') || 'none'}`,
  3718. ].join('\n');
  3719. }).join('\n\n');
  3720. const system = 'You are a competitive intelligence analyst. Write in plain text, no markdown or bullet points.';
  3721. const prompt = `Here are ${competitors.length} competitors you are analysing:
  3722. ${competitorBlocks}
  3723. Write a concise competitive landscape synthesis (3–4 sentences) that:
  3724. 1. Identifies the dominant positioning gap none of them own (the white space).
  3725. 2. Names the competitor with the weakest differentiation.
  3726. 3. States the single highest-leverage content angle for someone competing against all of them.
  3727. Write as direct, specific analysis. No fluff.`;
  3728. try {
  3729. const pconf = await getActiveProviderConfig(request.workspaceId);
  3730. const model = pconf.model;
  3731. let text = '';
  3732. if (pconf.provider === 'ollama') {
  3733. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  3734. text = res.data.response;
  3735. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3736. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3737. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3738. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3739. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  3740. text = res.data.choices[0]?.message?.content || '';
  3741. } else if (pconf.provider === 'gemini') {
  3742. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3743. const res = await axios.post(
  3744. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3745. { contents: buildGeminiContents(prompt, system) },
  3746. { timeout: 90000 },
  3747. );
  3748. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3749. } else {
  3750. return reply.code(400).send({ error: 'AI not configured' });
  3751. }
  3752. if (!text.trim()) return reply.code(503).send({ error: 'AI returned empty response — try again' });
  3753. log.info({ action: 'competitor_matrix', count: competitors.length, outcome: 'success' });
  3754. return { success: true, synthesis: text.trim(), generatedAt: new Date() };
  3755. } catch (err) {
  3756. return reply.code(503).send({ error: 'Matrix synthesis failed', detail: err.message });
  3757. }
  3758. });
  3759. // ─── Porter's Five Forces Analysis ───────────────────────────────────────────
  3760. app.post('/ai/five-forces', async (request, reply) => {
  3761. const ws = request.workspaceId;
  3762. const { accountKey } = request.body || {};
  3763. if (!accountKey) return reply.code(400).send({ error: 'accountKey is required' });
  3764. const db = await getDb();
  3765. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  3766. if (!profile) return reply.code(404).send({ error: 'Account profile not found. Save a profile first.' });
  3767. if (!profile.industry && !profile.businessName) {
  3768. return reply.code(400).send({ error: 'Add at least a business name or industry to the profile first.' });
  3769. }
  3770. const profileBlock = [
  3771. profile.businessName ? `Business: ${profile.businessName}` : '',
  3772. profile.industry ? `Industry: ${profile.industry}` : '',
  3773. profile.description ? `Description: ${profile.description}` : '',
  3774. profile.targetAudience ? `Target audience: ${profile.targetAudience}` : '',
  3775. profile.keywords ? `Keywords / products: ${profile.keywords}` : '',
  3776. ].filter(Boolean).join('\n');
  3777. // Load competitor data for richer rivalry analysis
  3778. const competitors = await db.collection('competitors').find({ workspaceId: ws }, { projection: { name: 1, aiAnalysis: 1 } }).toArray();
  3779. const competitorBlock = competitors.length
  3780. ? `Known direct competitors: ${competitors.map((c) => c.name).join(', ')}.`
  3781. : '';
  3782. const system = 'You are a Porter strategy analyst. Return only valid JSON with no markdown or explanation.';
  3783. const prompt = `Analyse this business using Porter\'s Five Forces framework.
  3784. ${profileBlock}
  3785. ${competitorBlock}
  3786. Score each force 1–10 (1 = very weak/favourable, 10 = very strong/unfavourable) and return exactly:
  3787. {
  3788. "attractiveness": "<High|Moderate|Low> — one sentence on overall industry attractiveness",
  3789. "overallScore": <0–100, where 100 = maximally attractive>,
  3790. "governingForce": "<name of the single most impactful force>",
  3791. "forces": [
  3792. {
  3793. "name": "Competitive Rivalry",
  3794. "score": <1–10>,
  3795. "assessment": "<one sentence>",
  3796. "drivers": ["<driver 1>", "<driver 2>", "<driver 3>"]
  3797. },
  3798. {
  3799. "name": "Threat of New Entrants",
  3800. "score": <1–10>,
  3801. "assessment": "<one sentence>",
  3802. "drivers": ["<driver>", "<driver>", "<driver>"]
  3803. },
  3804. {
  3805. "name": "Threat of Substitutes",
  3806. "score": <1–10>,
  3807. "assessment": "<one sentence>",
  3808. "drivers": ["<driver>", "<driver>", "<driver>"]
  3809. },
  3810. {
  3811. "name": "Supplier Power",
  3812. "score": <1–10>,
  3813. "assessment": "<one sentence>",
  3814. "drivers": ["<driver>", "<driver>", "<driver>"]
  3815. },
  3816. {
  3817. "name": "Buyer Power",
  3818. "score": <1–10>,
  3819. "assessment": "<one sentence>",
  3820. "drivers": ["<driver>", "<driver>", "<driver>"]
  3821. }
  3822. ],
  3823. "positioning": ["<strategic recommendation 1>", "<strategic recommendation 2>", "<strategic recommendation 3>"]
  3824. }
  3825. Scoring: overallScore = 100 minus the average of all five force scores × 10. Return ONLY valid JSON.`;
  3826. try {
  3827. const pconf = await getActiveProviderConfig(request.workspaceId);
  3828. const model = pconf.model;
  3829. let text = '';
  3830. if (pconf.provider === 'ollama') {
  3831. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3832. text = res.data.response;
  3833. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3834. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3835. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3836. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3837. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3838. text = res.data.choices[0]?.message?.content || '';
  3839. } else if (pconf.provider === 'gemini') {
  3840. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3841. const res = await axios.post(
  3842. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3843. { contents: buildGeminiContents(prompt, system) },
  3844. { timeout: 120000 },
  3845. );
  3846. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3847. } else {
  3848. return reply.code(400).send({ error: 'AI not configured' });
  3849. }
  3850. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  3851. let result = null;
  3852. try {
  3853. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3854. result = JSON.parse(jsonStr);
  3855. if (!Array.isArray(result.forces) || result.forces.length !== 5) throw new Error('Missing forces array');
  3856. } catch {
  3857. return reply.code(503).send({ error: 'AI returned invalid Five Forces format — try again' });
  3858. }
  3859. await db.collection('account_profiles').updateOne(
  3860. { _id: accountKey, workspaceId: ws },
  3861. { $set: { industryAnalysis: result, industryAnalyzedAt: new Date(), updatedAt: new Date() } },
  3862. );
  3863. log.info({ action: 'five_forces', account: accountKey, governingForce: result.governingForce, outcome: 'success' });
  3864. return { success: true, ...result, analyzedAt: new Date() };
  3865. } catch (err) {
  3866. return reply.code(503).send({ error: 'Five Forces analysis failed', detail: err.message });
  3867. }
  3868. });
  3869. // ─── Industry Type Diagnosis ─────────────────────────────────────────────────
  3870. app.post('/ai/industry-diagnosis', async (request, reply) => {
  3871. const ws = request.workspaceId;
  3872. const { accountKey } = request.body || {};
  3873. if (!accountKey) return reply.code(400).send({ error: 'accountKey is required' });
  3874. const db = await getDb();
  3875. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  3876. if (!profile) return reply.code(404).send({ error: 'Account profile not found. Save the profile first.' });
  3877. const fields = [profile.businessName, profile.description, profile.industry, profile.toneOfVoice].filter(Boolean);
  3878. if (fields.length < 2) return reply.code(400).send({ error: 'Fill in at least a business name and description before running diagnosis.' });
  3879. const profileBlock = [
  3880. profile.businessName ? `Business name: ${profile.businessName}` : '',
  3881. profile.description ? `Description: ${profile.description}` : '',
  3882. profile.industry ? `Self-reported industry: ${profile.industry}` : '',
  3883. profile.targetAudience ? `Target audience: ${profile.targetAudience}` : '',
  3884. profile.toneOfVoice ? `Brand tone: ${profile.toneOfVoice}` : '',
  3885. profile.keywords ? `Keywords: ${profile.keywords}` : '',
  3886. profile.postingGuidelines ? `Posting guidelines: ${profile.postingGuidelines}` : '',
  3887. ].filter(Boolean).join('\n');
  3888. const system = 'You are a social media strategy expert. Return only valid JSON with no markdown or explanation.';
  3889. const prompt = `Diagnose this brand's industry archetype based on the profile below and return strategic recommendations.
  3890. ${profileBlock}
  3891. Industry archetypes to choose from (pick the closest fit):
  3892. B2B SaaS, B2B Services, E-commerce (Product), Retail / Local Business, Hospitality / Food & Beverage,
  3893. Personal Brand / Creator, Health & Wellness, Finance / Fintech, Education / EdTech, Non-profit,
  3894. Media / Entertainment, Real Estate, Professional Services (Law / Consulting / Accounting).
  3895. Return this exact JSON:
  3896. {
  3897. "diagnosedType": "<archetype name>",
  3898. "confidence": <0-100>,
  3899. "summary": "<2-sentence explanation of why this archetype fits>",
  3900. "characteristics": ["<trait 1>", "<trait 2>", "<trait 3>"],
  3901. "tactics": [
  3902. { "title": "<tactic name>", "rationale": "<why it works for this archetype>", "action": "<specific concrete action>" },
  3903. { "title": "<tactic name>", "rationale": "<why it works>", "action": "<specific action>" },
  3904. { "title": "<tactic name>", "rationale": "<why it works>", "action": "<specific action>" }
  3905. ],
  3906. "contentMix": { "educational": <pct>, "social_proof": <pct>, "promotional": <pct>, "engagement": <pct> }
  3907. }
  3908. The contentMix percentages must sum to 100.
  3909. Return ONLY valid JSON.`;
  3910. try {
  3911. const pconf = await getActiveProviderConfig(request.workspaceId);
  3912. const model = pconf.model;
  3913. let text = '';
  3914. if (pconf.provider === 'ollama') {
  3915. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3916. text = res.data.response;
  3917. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3918. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3919. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3920. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3921. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3922. text = res.data.choices[0]?.message?.content || '';
  3923. } else if (pconf.provider === 'gemini') {
  3924. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3925. const res = await axios.post(
  3926. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3927. { contents: buildGeminiContents(prompt, system) },
  3928. { timeout: 120000 },
  3929. );
  3930. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3931. } else {
  3932. return reply.code(400).send({ error: 'AI not configured' });
  3933. }
  3934. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  3935. let result = null;
  3936. try {
  3937. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3938. result = JSON.parse(jsonStr);
  3939. if (!result.diagnosedType) throw new Error();
  3940. } catch {
  3941. return reply.code(503).send({ error: 'AI returned invalid diagnosis format — try again' });
  3942. }
  3943. // Persist the diagnosis on the account profile for future use
  3944. await db.collection('account_profiles').updateOne(
  3945. { _id: accountKey, workspaceId: ws },
  3946. { $set: { industryDiagnosis: result, industryDiagnosedAt: new Date(), updatedAt: new Date() } },
  3947. );
  3948. log.info({ action: 'industry_diagnosis', account: accountKey, diagnosedType: result.diagnosedType, outcome: 'success' });
  3949. return { success: true, ...result, diagnosedAt: new Date() };
  3950. } catch (err) {
  3951. return reply.code(503).send({ error: 'Industry diagnosis failed', detail: err.message });
  3952. }
  3953. });
  3954. // ─── Social Channel Audit ────────────────────────────────────────────────────
  3955. app.post('/ai/channel-audit', async (request, reply) => {
  3956. const ws = request.workspaceId;
  3957. const { accountKey } = request.body || {};
  3958. const db = await getDb();
  3959. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  3960. // Load profile (optional — enriches completeness & bio quality sections)
  3961. let profile = null;
  3962. if (accountKey) {
  3963. profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  3964. }
  3965. // Load recent posts, optionally filtered by account
  3966. const postFilter = accountKey
  3967. ? { workspaceId: ws, publishedAt: { $gte: thirtyDaysAgo }, 'destinations.key': accountKey }
  3968. : { workspaceId: ws, publishedAt: { $gte: thirtyDaysAgo } };
  3969. const recentPosts = await db.collection('posts')
  3970. .find(postFilter, { projection: { content: 1, destinations: 1, publishedAt: 1, status: 1 } })
  3971. .toArray();
  3972. if (recentPosts.length < 2) {
  3973. return reply.code(400).send({ error: 'Not enough publishing history. Publish at least 2 posts first.' });
  3974. }
  3975. // ── Local stats computation ──────────────────────────────────────────────
  3976. const totalPosts = recentPosts.length;
  3977. // Format diversity: posts with imageUrl/videoUrl in any destination
  3978. const postsWithMedia = recentPosts.filter((p) =>
  3979. (p.destinations || []).some((d) => d.imageUrl || d.videoUrl),
  3980. ).length;
  3981. const mediaRatio = Math.round((postsWithMedia / totalPosts) * 100);
  3982. // CTA detection
  3983. const ctaWords = ['click', 'link in bio', 'shop', 'buy', 'register', 'sign up', 'subscribe', 'follow', 'comment', 'share', 'tag', 'dm'];
  3984. const postsWithCta = recentPosts.filter((p) =>
  3985. ctaWords.some((w) => (p.content || '').toLowerCase().includes(w)),
  3986. ).length;
  3987. const ctaRatio = Math.round((postsWithCta / totalPosts) * 100);
  3988. // Hashtag stats
  3989. const hashtagCounts = recentPosts.map((p) => ((p.content || '').match(/#\w+/g) || []).length);
  3990. const avgHashtags = Math.round((hashtagCounts.reduce((s, c) => s + c, 0) / totalPosts) * 10) / 10;
  3991. // Caption length
  3992. const avgCaptionLength = Math.round(recentPosts.reduce((s, p) => s + (p.content || '').length, 0) / totalPosts);
  3993. // Posting consistency: days between posts
  3994. const dates = recentPosts.map((p) => new Date(p.publishedAt).getTime()).sort((a, b) => a - b);
  3995. const gaps = dates.slice(1).map((d, i) => (d - dates[i]) / (1000 * 60 * 60 * 24));
  3996. const avgGap = gaps.length > 0 ? Math.round(gaps.reduce((s, g) => s + g, 0) / gaps.length * 10) / 10 : 30;
  3997. const maxGap = gaps.length > 0 ? Math.round(Math.max(...gaps) * 10) / 10 : 30;
  3998. // Engagement from post_metrics
  3999. const metricsFilter = accountKey
  4000. ? { workspaceId: ws, accountKey }
  4001. : { workspaceId: ws };
  4002. const metrics = await db.collection('post_metrics')
  4003. .find({ ...metricsFilter, createdAt: { $gte: thirtyDaysAgo } })
  4004. .toArray();
  4005. const avgEngagement = metrics.length > 0
  4006. ? Math.round((metrics.reduce((s, m) => s + (m.metrics?.engagementTotal || 0), 0) / metrics.length) * 10) / 10
  4007. : null;
  4008. // Profile completeness score (0-100)
  4009. let profileScore = 0;
  4010. let profileNote = 'No profile configured for this account.';
  4011. if (profile) {
  4012. const fields = [profile.businessName, profile.description, profile.industry, profile.toneOfVoice, profile.targetAudience, profile.keywords, profile.websiteUrl];
  4013. const filled = fields.filter((f) => f && (Array.isArray(f) ? f.length > 0 : String(f).trim().length > 0)).length;
  4014. profileScore = Math.round((filled / fields.length) * 100);
  4015. profileNote = `${filled}/${fields.length} profile fields completed. Business name: ${profile.businessName || 'missing'}, industry: ${profile.industry || 'missing'}.`;
  4016. }
  4017. const statsBlock = [
  4018. `Total posts (last 30 days): ${totalPosts}`,
  4019. `Posts with media (images/video): ${mediaRatio}%`,
  4020. `Posts with a CTA (click, shop, follow, etc.): ${ctaRatio}%`,
  4021. `Average hashtags per post: ${avgHashtags}`,
  4022. `Average caption length: ${avgCaptionLength} characters`,
  4023. `Average days between posts: ${avgGap} (max gap: ${maxGap} days)`,
  4024. `Average engagement per post: ${avgEngagement !== null ? avgEngagement : 'no data'}`,
  4025. `Account profile completeness: ${profileScore}% — ${profileNote}`,
  4026. profile?.description ? `Bio/description: "${profile.description.slice(0, 200)}"` : 'No bio/description set.',
  4027. profile?.toneOfVoice ? `Brand tone: ${profile.toneOfVoice}` : '',
  4028. ].filter(Boolean).join('\n');
  4029. const system = 'You are a professional social media channel auditor. Return only valid JSON with no markdown or explanation.';
  4030. const prompt = `Audit this social media channel and return a quality score report.
  4031. ${statsBlock}
  4032. Score each dimension 0-10 and return this exact JSON:
  4033. {
  4034. "score": <overall 0-100>,
  4035. "sections": [
  4036. { "name": "Profile Completeness", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4037. { "name": "Posting Consistency", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4038. { "name": "Visual Content", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4039. { "name": "CTA Usage", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4040. { "name": "Hashtag Strategy", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4041. { "name": "Engagement Quality", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] }
  4042. ],
  4043. "topActions": ["<highest-impact action 1>", "<highest-impact action 2>", "<highest-impact action 3>"]
  4044. }
  4045. Scoring benchmarks:
  4046. - Profile Completeness: 100% filled = 10, 70%+ = 7, 50%+ = 5, below = 2
  4047. - Posting Consistency: daily = 10, every 2-3 days = 7, weekly = 5, less = 2; long gaps hurt the score
  4048. - Visual Content: 80%+ posts with media = 10, 50%+ = 7, 25%+ = 4, 0% = 1
  4049. - CTA Usage: 60%+ posts with CTA = 10, 40%+ = 7, 20%+ = 4, none = 2
  4050. - Hashtag Strategy: 3-10 hashtags avg = 10, 1-2 or 11-20 = 7, 0 or 21+ = 3
  4051. - Engagement Quality: avg engagement >5 = 10, 3-5 = 7, 1-3 = 5, <1 = 2, no data = 5 (neutral)
  4052. Return ONLY valid JSON.`;
  4053. try {
  4054. const pconf = await getActiveProviderConfig(request.workspaceId);
  4055. const model = pconf.model;
  4056. let text = '';
  4057. if (pconf.provider === 'ollama') {
  4058. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  4059. text = res.data.response;
  4060. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  4061. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  4062. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  4063. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  4064. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  4065. text = res.data.choices[0]?.message?.content || '';
  4066. } else if (pconf.provider === 'gemini') {
  4067. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  4068. const res = await axios.post(
  4069. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  4070. { contents: buildGeminiContents(prompt, system) },
  4071. { timeout: 120000 },
  4072. );
  4073. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  4074. } else {
  4075. return reply.code(400).send({ error: 'AI not configured' });
  4076. }
  4077. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  4078. let result = null;
  4079. try {
  4080. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  4081. result = JSON.parse(jsonStr);
  4082. if (!Array.isArray(result.sections)) throw new Error();
  4083. } catch {
  4084. return reply.code(503).send({ error: 'AI returned invalid channel audit format — try again' });
  4085. }
  4086. log.info({ action: 'channel_audit', account: accountKey || 'all', outcome: 'success' });
  4087. return { success: true, ...result, generatedAt: new Date() };
  4088. } catch (err) {
  4089. return reply.code(503).send({ error: 'Channel audit failed', detail: err.message });
  4090. }
  4091. });
  4092. module.exports = app;