server.js 201 KB

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