server.js 203 KB

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