server.js 205 KB

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