server.js 205 KB

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