server.js 203 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645
  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'];
  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 results = await Promise.allSettled(
  1487. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  1488. const serviceUrl = PLATFORM_SERVICES[platform];
  1489. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  1490. const res = await axios.post(
  1491. `${serviceUrl}/post`,
  1492. { content, accountId, imageUrl, videoUrl, link, firstComment: firstComment?.trim() || undefined },
  1493. { timeout: 30000 }
  1494. );
  1495. return { platform, accountId, ...res.data };
  1496. })
  1497. );
  1498. const output = results.map((r, i) =>
  1499. r.status === 'fulfilled'
  1500. ? r.value
  1501. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  1502. );
  1503. const anyFailed = output.some((r) => !r.success);
  1504. const anySucceeded = output.some((r) => r.success);
  1505. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  1506. // Record the post for analytics
  1507. try {
  1508. const db = await getDb();
  1509. await db.collection('posts').insertOne({
  1510. _id: crypto.randomUUID(),
  1511. type: 'immediate',
  1512. content,
  1513. ...(firstComment?.trim() && { firstComment: firstComment.trim() }),
  1514. destinations,
  1515. platformResults: Object.fromEntries(
  1516. output.map((r) => [
  1517. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  1518. { success: r.success, ...(r.error && { error: r.error }) },
  1519. ])
  1520. ),
  1521. status: postStatus,
  1522. workspaceId: request.workspaceId,
  1523. publishedAt: new Date(),
  1524. createdAt: new Date(),
  1525. });
  1526. } catch (err) {
  1527. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  1528. }
  1529. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  1530. });
  1531. // ─── Legacy post route ────────────────────────────────────────────────────────
  1532. let rabbitMQProducer = new RabbitMQProducer();
  1533. app.post('/', async (request, reply) => {
  1534. try {
  1535. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  1536. reply.send({ status: 'ok' });
  1537. } catch (error) {
  1538. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  1539. reply.status(500).send({ error: 'Internal Server Error' });
  1540. }
  1541. });
  1542. // ─── Meta App Credentials ────────────────────────────────────────────────────
  1543. // Save Facebook App ID + Secret (entered by user in Settings UI)
  1544. app.post('/credentials/meta-app', async (request, reply) => {
  1545. const ws = request.workspaceId;
  1546. const { appId, appSecret } = request.body || {};
  1547. if (!appId || !appSecret) {
  1548. return reply.code(400).send({ error: 'appId and appSecret are required' });
  1549. }
  1550. await setCredentials(ws, 'meta_app', { appId, appSecret: encryptToken(appSecret) });
  1551. return { success: true };
  1552. });
  1553. // Get Meta App config (secret is masked for UI display)
  1554. app.get('/credentials/meta-app', async (request) => {
  1555. const ws = request.workspaceId;
  1556. const cred = await getCredentials(ws, 'meta_app');
  1557. if (!cred) return { configured: false };
  1558. const plainSecret = decryptToken(cred.appSecret) || '';
  1559. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  1560. });
  1561. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  1562. // Return the Facebook OAuth URL to redirect the user to
  1563. app.get('/auth/meta/init', async (request, reply) => {
  1564. const ws = request.workspaceId;
  1565. const cred = await getCredentials(ws, 'meta_app');
  1566. if (!cred?.appId) {
  1567. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  1568. }
  1569. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1570. const scopes = [
  1571. 'pages_manage_posts',
  1572. 'pages_read_engagement',
  1573. 'instagram_basic',
  1574. 'instagram_content_publish',
  1575. 'instagram_manage_insights',
  1576. ].join(',');
  1577. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  1578. return { url };
  1579. });
  1580. // OAuth callback — Facebook redirects here after user authorises
  1581. app.get('/auth/meta/callback', async (request, reply) => {
  1582. const ws = request.workspaceId;
  1583. const { code, error: oauthError } = request.query;
  1584. if (oauthError) {
  1585. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  1586. }
  1587. if (!code) {
  1588. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  1589. }
  1590. try {
  1591. const appCred = await getCredentials(ws, 'meta_app');
  1592. if (!appCred?.appId) throw new Error('App credentials not configured');
  1593. const appSecret = decryptToken(appCred.appSecret);
  1594. if (!appSecret) throw new Error('Failed to decrypt app secret');
  1595. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1596. // Exchange code for short-lived token
  1597. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1598. params: {
  1599. client_id: appCred.appId,
  1600. client_secret: appSecret,
  1601. redirect_uri: redirectUri,
  1602. code,
  1603. },
  1604. });
  1605. // Upgrade to long-lived user token (~60 days)
  1606. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1607. params: {
  1608. grant_type: 'fb_exchange_token',
  1609. client_id: appCred.appId,
  1610. client_secret: appSecret,
  1611. fb_exchange_token: shortRes.data.access_token,
  1612. },
  1613. });
  1614. const userToken = longRes.data.access_token;
  1615. // Fetch all managed Facebook Pages
  1616. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  1617. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  1618. });
  1619. const pages = [];
  1620. const igAccounts = [];
  1621. for (const page of pagesRes.data.data || []) {
  1622. pages.push({
  1623. id: page.id,
  1624. name: page.name,
  1625. accessToken: encryptToken(page.access_token),
  1626. picture: page.picture?.data?.url || null,
  1627. selected: false,
  1628. });
  1629. // Check for linked Instagram Business Account
  1630. try {
  1631. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  1632. params: {
  1633. fields: 'instagram_business_account',
  1634. access_token: page.access_token,
  1635. },
  1636. });
  1637. if (igRes.data.instagram_business_account?.id) {
  1638. const igId = igRes.data.instagram_business_account.id;
  1639. // Fetch IG account details
  1640. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  1641. params: {
  1642. fields: 'id,username,name,profile_picture_url',
  1643. access_token: userToken,
  1644. },
  1645. });
  1646. igAccounts.push({
  1647. id: igId,
  1648. username: igProfile.data.username || igProfile.data.name,
  1649. name: igProfile.data.name,
  1650. avatar: igProfile.data.profile_picture_url || null,
  1651. accessToken: encryptToken(userToken),
  1652. pageId: page.id,
  1653. selected: false,
  1654. });
  1655. }
  1656. } catch (_) {
  1657. // Page has no linked Instagram account — skip
  1658. }
  1659. }
  1660. // Store discovery results for the UI to pick from
  1661. await setCredentials(ws, 'meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1662. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1663. } catch (err) {
  1664. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1665. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1666. }
  1667. });
  1668. // Return pending discovery results so the UI can render the page picker
  1669. app.get('/auth/meta/discovered', async (request) => {
  1670. const ws = request.workspaceId;
  1671. const discovery = await getCredentials(ws, 'meta_discovery');
  1672. if (!discovery) return { pages: [], igAccounts: [] };
  1673. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1674. });
  1675. // User has chosen which pages/accounts to connect
  1676. app.post('/auth/meta/save', async (request, reply) => {
  1677. const ws = request.workspaceId;
  1678. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1679. const discovery = await getCredentials(ws, 'meta_discovery');
  1680. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1681. const fbPages = (discovery.pages || []).map((p) => ({
  1682. ...p,
  1683. selected: selectedPageIds.includes(p.id),
  1684. }));
  1685. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1686. ...a,
  1687. selected: selectedIgAccountIds.includes(a.id),
  1688. }));
  1689. await setCredentials(ws, 'facebook', { pages: fbPages });
  1690. await setCredentials(ws, 'instagram', { accounts: igAccounts });
  1691. await deleteCredentials(ws, 'meta_discovery');
  1692. _tokenExpiryCache = null; // invalidate cache after reconnect
  1693. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1694. });
  1695. // Disconnect all Meta platforms
  1696. app.delete('/credentials/meta', async (request) => {
  1697. const ws = request.workspaceId;
  1698. await deleteCredentials(ws, 'facebook');
  1699. await deleteCredentials(ws, 'instagram');
  1700. await deleteCredentials(ws, 'meta_discovery');
  1701. return { success: true };
  1702. });
  1703. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1704. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1705. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1706. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1707. app.post('/credentials/pinterest-app', async (request, reply) => {
  1708. const ws = request.workspaceId;
  1709. const { clientId, clientSecret } = request.body || {};
  1710. if (!clientId || !clientSecret) {
  1711. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1712. }
  1713. await setCredentials(ws, 'pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1714. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1715. return { success: true };
  1716. });
  1717. app.get('/credentials/pinterest-app', async (request) => {
  1718. const ws = request.workspaceId;
  1719. const cred = await getCredentials(ws, 'pinterest_app');
  1720. if (!cred) return { configured: false };
  1721. const plain = decryptToken(cred.clientSecret) || '';
  1722. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1723. });
  1724. app.get('/auth/pinterest/init', async (request, reply) => {
  1725. const ws = request.workspaceId;
  1726. const cred = await getCredentials(ws, 'pinterest_app');
  1727. if (!cred?.clientId) {
  1728. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1729. }
  1730. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1731. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1732. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}`;
  1733. return { url };
  1734. });
  1735. app.get('/auth/pinterest/callback', async (request, reply) => {
  1736. const ws = request.workspaceId;
  1737. const { code, error: oauthError } = request.query;
  1738. if (oauthError) {
  1739. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1740. }
  1741. if (!code) {
  1742. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1743. }
  1744. try {
  1745. const appCred = await getCredentials(ws, 'pinterest_app');
  1746. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1747. const clientSecret = decryptToken(appCred.clientSecret);
  1748. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1749. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1750. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1751. const tokenRes = await axios.post(
  1752. PINTEREST_TOKEN_URL,
  1753. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1754. {
  1755. headers: {
  1756. Authorization: `Basic ${basicAuth}`,
  1757. 'Content-Type': 'application/x-www-form-urlencoded',
  1758. },
  1759. timeout: 15000,
  1760. }
  1761. );
  1762. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1763. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1764. const [userRes, boardsRes] = await Promise.all([
  1765. axios.get(`${PINTEREST_API}/user_account`, {
  1766. headers: { Authorization: `Bearer ${access_token}` },
  1767. timeout: 10000,
  1768. }),
  1769. axios.get(`${PINTEREST_API}/boards`, {
  1770. headers: { Authorization: `Bearer ${access_token}` },
  1771. params: { page_size: 100 },
  1772. timeout: 15000,
  1773. }),
  1774. ]);
  1775. const boards = (boardsRes.data.items || []).map((b) => ({
  1776. id: b.id,
  1777. name: b.name,
  1778. privacy: b.privacy,
  1779. selected: false,
  1780. }));
  1781. await setCredentials(ws, 'pinterest', {
  1782. userId: userRes.data.username,
  1783. username: userRes.data.username,
  1784. displayName: userRes.data.business_name || userRes.data.username,
  1785. avatar: userRes.data.profile_image,
  1786. accessToken: encryptToken(access_token),
  1787. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1788. tokenExpiry,
  1789. boards,
  1790. });
  1791. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1792. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1793. } catch (err) {
  1794. const msg = err.response?.data?.message || err.message;
  1795. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1796. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1797. }
  1798. });
  1799. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1800. const ws = request.workspaceId;
  1801. const { selectedBoardIds = [] } = request.body || {};
  1802. const cred = await getCredentials(ws, 'pinterest');
  1803. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1804. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1805. await setCredentials(ws, 'pinterest', { ...cred, boards });
  1806. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1807. return { success: true, selected: boards.filter((b) => b.selected).length };
  1808. });
  1809. app.delete('/credentials/pinterest', async (request) => {
  1810. const ws = request.workspaceId;
  1811. await deleteCredentials(ws, 'pinterest');
  1812. return { success: true };
  1813. });
  1814. // ─── TikTok OAuth ─────────────────────────────────────────────────────────────
  1815. const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
  1816. const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
  1817. const TIKTOK_API = 'https://open.tiktokapis.com/v2';
  1818. app.post('/credentials/tiktok-app', async (request, reply) => {
  1819. const ws = request.workspaceId;
  1820. const { clientKey, clientSecret } = request.body || {};
  1821. if (!clientKey || !clientSecret) return reply.code(400).send({ error: 'clientKey and clientSecret are required' });
  1822. await setCredentials(ws, 'tiktok_app', { clientKey, clientSecret: encryptToken(clientSecret) });
  1823. log.info({ action: 'tiktok_app_save', outcome: 'success' });
  1824. return { success: true };
  1825. });
  1826. app.get('/credentials/tiktok-app', async (request) => {
  1827. const ws = request.workspaceId;
  1828. const cred = await getCredentials(ws, 'tiktok_app');
  1829. if (!cred?.clientKey) return { configured: false };
  1830. return { configured: true, clientKey: cred.clientKey, clientSecretHint: `****${decryptToken(cred.clientSecret).slice(-4)}` };
  1831. });
  1832. app.get('/auth/tiktok/init', async (request, reply) => {
  1833. const ws = request.workspaceId;
  1834. const cred = await getCredentials(ws, 'tiktok_app');
  1835. if (!cred?.clientKey) return reply.code(400).send({ error: 'Save your TikTok Client Key and Secret first' });
  1836. const codeVerifier = crypto.randomBytes(32).toString('base64url');
  1837. const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1838. const state = crypto.randomBytes(16).toString('hex');
  1839. // Persist PKCE verifier for the callback
  1840. const pkceId = credId(ws, 'tiktok_pkce');
  1841. const db = await getDb();
  1842. await db.collection('platform_credentials').updateOne(
  1843. { _id: pkceId },
  1844. { $set: { _id: pkceId, workspaceId: ws, codeVerifier, state, createdAt: new Date() } },
  1845. { upsert: true }
  1846. );
  1847. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1848. const scopes = 'user.info.basic,video.list,video.publish';
  1849. const params = new URLSearchParams({
  1850. client_key: cred.clientKey,
  1851. scope: scopes,
  1852. response_type: 'code',
  1853. redirect_uri: redirectUri,
  1854. state,
  1855. code_challenge: codeChallenge,
  1856. code_challenge_method: 'S256',
  1857. });
  1858. return { url: `${TIKTOK_AUTH_URL}?${params.toString()}` };
  1859. });
  1860. app.get('/auth/tiktok/callback', async (request, reply) => {
  1861. const ws = request.workspaceId;
  1862. const { code, state, error: oauthError, error_description } = request.query;
  1863. if (oauthError) {
  1864. const msg = error_description || oauthError;
  1865. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1866. }
  1867. if (!code) {
  1868. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=no_code`);
  1869. }
  1870. try {
  1871. const db = await getDb();
  1872. const pkce = await db.collection('platform_credentials').findOne({ _id: credId(ws, 'tiktok_pkce') });
  1873. if (!pkce?.codeVerifier) throw new Error('PKCE state not found — try connecting again');
  1874. if (state && pkce.state && state !== pkce.state) throw new Error('OAuth state mismatch');
  1875. const appCred = await getCredentials(ws, 'tiktok_app');
  1876. if (!appCred?.clientKey) throw new Error('App credentials not configured');
  1877. const clientSecret = decryptToken(appCred.clientSecret);
  1878. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1879. const tokenRes = await axios.post(
  1880. TIKTOK_TOKEN_URL,
  1881. new URLSearchParams({
  1882. client_key: appCred.clientKey,
  1883. client_secret: clientSecret,
  1884. code,
  1885. grant_type: 'authorization_code',
  1886. redirect_uri: redirectUri,
  1887. code_verifier: pkce.codeVerifier,
  1888. }).toString(),
  1889. { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000 }
  1890. );
  1891. const { access_token, refresh_token, expires_in, refresh_expires_in, open_id } = tokenRes.data;
  1892. const tokenExpiry = new Date(Date.now() + (expires_in || 86400) * 1000).toISOString();
  1893. const refreshExpiry = new Date(Date.now() + (refresh_expires_in || 31536000) * 1000).toISOString();
  1894. const userRes = await axios.get(`${TIKTOK_API}/user/info/`, {
  1895. headers: { Authorization: `Bearer ${access_token}` },
  1896. params: { fields: 'open_id,display_name,avatar_url,username' },
  1897. timeout: 10000,
  1898. });
  1899. const user = userRes.data?.data?.user || {};
  1900. await setCredentials(ws, 'tiktok', {
  1901. openId: open_id || user.open_id,
  1902. username: user.username || user.display_name,
  1903. displayName: user.display_name,
  1904. avatar: user.avatar_url || null,
  1905. accessToken: encryptToken(access_token),
  1906. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1907. tokenExpiry,
  1908. refreshExpiry,
  1909. });
  1910. // Clean up PKCE temp state
  1911. await db.collection('platform_credentials').deleteOne({ _id: credId(ws, 'tiktok_pkce') });
  1912. log.info({ action: 'tiktok_oauth_callback', username: user.username || user.display_name, outcome: 'success' });
  1913. reply.redirect(`${APP_BASE_URL}/settings?tiktok_connected=1`);
  1914. } catch (err) {
  1915. const msg = err.response?.data?.error?.message || err.response?.data?.message || err.message;
  1916. log.error({ action: 'tiktok_oauth_callback', outcome: 'failure', err: msg });
  1917. reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1918. }
  1919. });
  1920. app.delete('/credentials/tiktok', async (request) => {
  1921. const ws = request.workspaceId;
  1922. await deleteCredentials(ws, 'tiktok');
  1923. return { success: true };
  1924. });
  1925. // ─── Credential Status ────────────────────────────────────────────────────────
  1926. // Aggregate connection status for all DB-managed platforms
  1927. app.get('/credentials', async (request) => {
  1928. const ws = request.workspaceId;
  1929. const [metaApp, fb, ig, pinterest, tiktok] = await Promise.all([
  1930. getCredentials(ws, 'meta_app'),
  1931. getCredentials(ws, 'facebook'),
  1932. getCredentials(ws, 'instagram'),
  1933. getCredentials(ws, 'pinterest'),
  1934. getCredentials(ws, 'tiktok'),
  1935. ]);
  1936. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1937. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1938. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1939. return {
  1940. metaApp: { configured: !!(metaApp?.appId) },
  1941. facebook: {
  1942. connected: fbPages.length > 0,
  1943. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1944. allPages: (fb?.pages || []).map(({ id, name, picture, selected }) => ({ id, name, picture, selected: !!selected })),
  1945. },
  1946. instagram: {
  1947. connected: igAccounts.length > 0,
  1948. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1949. allAccounts: (ig?.accounts || []).map(({ id, username, avatar, selected }) => ({ id, username, avatar, selected: !!selected })),
  1950. },
  1951. pinterest: {
  1952. connected: pinterestBoards.length > 0,
  1953. username: pinterest?.username || null,
  1954. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1955. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1956. },
  1957. tiktok: {
  1958. connected: !!(tiktok?.accessToken),
  1959. username: tiktok?.username || null,
  1960. displayName: tiktok?.displayName || null,
  1961. avatar: tiktok?.avatar || null,
  1962. },
  1963. };
  1964. });
  1965. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1966. // Update which Facebook pages are selected for this workspace
  1967. app.post('/credentials/facebook/pages', async (request) => {
  1968. const ws = request.workspaceId;
  1969. const { selectedPageIds } = request.body;
  1970. const fb = await getCredentials(ws, 'facebook');
  1971. if (!fb) return { success: false, error: 'Not connected' };
  1972. const updated = (fb.pages || []).map((p) => ({ ...p, selected: selectedPageIds.includes(p.id) }));
  1973. await setCredentials(ws, 'facebook', { pages: updated });
  1974. return { success: true };
  1975. });
  1976. // Update which Instagram accounts are selected for this workspace
  1977. app.post('/credentials/instagram/accounts', async (request) => {
  1978. const ws = request.workspaceId;
  1979. const { selectedAccountIds } = request.body;
  1980. const ig = await getCredentials(ws, 'instagram');
  1981. if (!ig) return { success: false, error: 'Not connected' };
  1982. const updated = (ig.accounts || []).map((a) => ({ ...a, selected: selectedAccountIds.includes(a.id) }));
  1983. await setCredentials(ws, 'instagram', { accounts: updated });
  1984. return { success: true };
  1985. });
  1986. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1987. const INDUSTRY_DEFAULTS = {
  1988. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1989. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1990. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1991. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1992. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1993. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1994. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  1995. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  1996. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  1997. tiktok: [[2,18],[3,18],[4,18],[5,12],[0,14]],
  1998. };
  1999. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  2000. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  2001. // at least `afterMs` milliseconds in the future.
  2002. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  2003. const candidate = new Date(afterMs);
  2004. candidate.setUTCHours(hourUTC, 0, 0, 0);
  2005. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  2006. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  2007. candidate.setUTCDate(candidate.getUTCDate() + 7);
  2008. } else {
  2009. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  2010. }
  2011. return candidate;
  2012. }
  2013. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  2014. app.get('/schedule/suggestions', async (request, reply) => {
  2015. const { platform, accountId } = request.query;
  2016. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  2017. const ws = request.workspaceId;
  2018. const db = await getDb();
  2019. const query = { workspaceId: ws, platform, ...(accountId && { accountId }) };
  2020. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  2021. let slots;
  2022. let source;
  2023. if (dataPoints >= 10) {
  2024. const agg = await db.collection('post_metrics').aggregate([
  2025. { $match: query },
  2026. { $group: {
  2027. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  2028. avgEngagement: { $avg: '$metrics.engagementTotal' },
  2029. count: { $sum: 1 },
  2030. }},
  2031. { $sort: { avgEngagement: -1 } },
  2032. { $limit: 5 },
  2033. ]).toArray();
  2034. slots = agg.map((r) => [r._id.day, r._id.hour]);
  2035. source = 'history';
  2036. } else {
  2037. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  2038. source = 'default';
  2039. }
  2040. // 30-minute lead time so the user has time to finish writing
  2041. const afterMs = Date.now() + 30 * 60 * 1000;
  2042. const suggestions = slots
  2043. .map(([day, hour]) => {
  2044. const dt = nextOccurrence(day, hour, afterMs);
  2045. const h12 = hour % 12 || 12;
  2046. const ampm = hour < 12 ? 'am' : 'pm';
  2047. return {
  2048. utc: dt.toISOString(),
  2049. dayOfWeek: day,
  2050. hour,
  2051. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  2052. };
  2053. })
  2054. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  2055. .slice(0, 4);
  2056. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  2057. return { source, suggestions };
  2058. });
  2059. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  2060. async function crawlFacebookMetrics(db, ws = 'default') {
  2061. const fb = await getCredentials(ws, 'facebook');
  2062. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  2063. if (!pages.length) return { count: 0 };
  2064. let count = 0;
  2065. for (const page of pages) {
  2066. const token = decryptToken(page.accessToken);
  2067. if (!token) continue;
  2068. try {
  2069. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  2070. params: {
  2071. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  2072. limit: 100,
  2073. access_token: token,
  2074. },
  2075. timeout: 30000,
  2076. });
  2077. for (const post of res.data.data || []) {
  2078. const likes = post.reactions?.summary?.total_count || 0;
  2079. const comments = post.comments?.summary?.total_count || 0;
  2080. const shares = post.shares?.count || 0;
  2081. const publishedAt = new Date(post.created_time);
  2082. await db.collection('post_metrics').updateOne(
  2083. { platform: 'facebook', postId: post.id, workspaceId: ws },
  2084. {
  2085. $set: {
  2086. platform: 'facebook',
  2087. accountId: page.id,
  2088. accountName: page.name,
  2089. postId: post.id,
  2090. content: post.message || null,
  2091. publishedAt,
  2092. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  2093. hourOfDay: publishedAt.getUTCHours(),
  2094. dayOfWeek: publishedAt.getUTCDay(),
  2095. workspaceId: ws,
  2096. fetchedAt: new Date(),
  2097. },
  2098. },
  2099. { upsert: true }
  2100. );
  2101. count++;
  2102. }
  2103. } catch (err) {
  2104. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  2105. }
  2106. }
  2107. return { count };
  2108. }
  2109. async function crawlInstagramMetrics(db, ws = 'default') {
  2110. const ig = await getCredentials(ws, 'instagram');
  2111. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  2112. if (!accounts.length) return { count: 0 };
  2113. let count = 0;
  2114. for (const account of accounts) {
  2115. const token = decryptToken(account.accessToken);
  2116. if (!token) continue;
  2117. try {
  2118. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  2119. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  2120. timeout: 30000,
  2121. });
  2122. for (const media of mediaRes.data.data || []) {
  2123. const likes = media.like_count || 0;
  2124. const comments = media.comments_count || 0;
  2125. const publishedAt = new Date(media.timestamp);
  2126. let views = 0;
  2127. let saves = 0;
  2128. try {
  2129. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  2130. params: { metric: 'reach,saved', access_token: token },
  2131. timeout: 10000,
  2132. });
  2133. for (const ins of insRes.data.data || []) {
  2134. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  2135. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  2136. }
  2137. } catch (_) {}
  2138. await db.collection('post_metrics').updateOne(
  2139. { platform: 'instagram', postId: media.id, workspaceId: ws },
  2140. {
  2141. $set: {
  2142. platform: 'instagram',
  2143. accountId: account.id,
  2144. accountName: account.username,
  2145. postId: media.id,
  2146. content: media.caption || null,
  2147. publishedAt,
  2148. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  2149. hourOfDay: publishedAt.getUTCHours(),
  2150. dayOfWeek: publishedAt.getUTCDay(),
  2151. workspaceId: ws,
  2152. fetchedAt: new Date(),
  2153. },
  2154. },
  2155. { upsert: true }
  2156. );
  2157. count++;
  2158. }
  2159. } catch (err) {
  2160. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  2161. }
  2162. }
  2163. return { count };
  2164. }
  2165. app.post('/analytics/crawl', async (request) => {
  2166. const ws = request.workspaceId;
  2167. const db = await getDb();
  2168. const results = {};
  2169. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  2170. try {
  2171. results[platform] = await crawler(db, ws);
  2172. } catch (err) {
  2173. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  2174. results[platform] = { count: 0, error: err.message };
  2175. }
  2176. }
  2177. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  2178. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  2179. return { success: true, total, byPlatform: results };
  2180. });
  2181. app.get('/analytics/insights', async (request) => {
  2182. const ws = request.workspaceId;
  2183. const filter = parseAccountFilter(request.query.account);
  2184. const metricsMatch = filter
  2185. ? { workspaceId: ws, platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  2186. : { workspaceId: ws };
  2187. const db = await getDb();
  2188. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  2189. if (total === 0) return { empty: true };
  2190. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  2191. db.collection('post_metrics').aggregate([
  2192. { $match: metricsMatch },
  2193. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  2194. { $sort: { _id: 1 } },
  2195. ]).toArray(),
  2196. db.collection('post_metrics').aggregate([
  2197. { $match: metricsMatch },
  2198. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  2199. { $sort: { _id: 1 } },
  2200. ]).toArray(),
  2201. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  2202. db.collection('post_metrics').aggregate([
  2203. { $match: metricsMatch },
  2204. { $group: {
  2205. _id: '$platform',
  2206. avgEngagement: { $avg: '$metrics.engagementTotal' },
  2207. avgLikes: { $avg: '$metrics.likes' },
  2208. avgComments: { $avg: '$metrics.comments' },
  2209. avgShares: { $avg: '$metrics.shares' },
  2210. totalPosts: { $sum: 1 },
  2211. }},
  2212. { $sort: { avgEngagement: -1 } },
  2213. ]).toArray(),
  2214. db.collection('post_metrics').aggregate([
  2215. { $match: metricsMatch },
  2216. { $group: {
  2217. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  2218. avgEngagement: { $avg: '$metrics.engagementTotal' },
  2219. count: { $sum: 1 },
  2220. }},
  2221. ]).toArray(),
  2222. ]);
  2223. const byHour = Array.from({ length: 24 }, (_, h) => {
  2224. const e = byHourRaw.find((r) => r._id === h);
  2225. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  2226. });
  2227. const byDay = Array.from({ length: 7 }, (_, d) => {
  2228. const e = byDayRaw.find((r) => r._id === d);
  2229. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  2230. });
  2231. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  2232. const day = Math.floor(i / 24);
  2233. const hour = i % 24;
  2234. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  2235. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  2236. });
  2237. return {
  2238. empty: false,
  2239. total,
  2240. byHour,
  2241. byDay,
  2242. heatmap,
  2243. topPosts: topPosts.map((p) => ({
  2244. platform: p.platform, accountName: p.accountName, postId: p.postId,
  2245. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  2246. })),
  2247. platformComparison: platformComparison.map((p) => ({
  2248. platform: p._id,
  2249. avgEngagement: Math.round(p.avgEngagement),
  2250. avgLikes: Math.round(p.avgLikes),
  2251. avgComments: Math.round(p.avgComments),
  2252. avgShares: Math.round(p.avgShares),
  2253. totalPosts: p.totalPosts,
  2254. })),
  2255. };
  2256. });
  2257. // ─── Analytics ────────────────────────────────────────────────────────────────
  2258. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  2259. function parseAccountFilter(account) {
  2260. if (!account) return null;
  2261. const idx = account.indexOf(':');
  2262. if (idx === -1) return { platform: account };
  2263. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  2264. }
  2265. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  2266. function sjFilter(filter) {
  2267. if (!filter) return {};
  2268. return {
  2269. 'destinations.platform': filter.platform,
  2270. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  2271. };
  2272. }
  2273. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  2274. function ipFilter(filter) {
  2275. if (!filter) return {};
  2276. return {
  2277. 'destinations.platform': filter.platform,
  2278. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  2279. };
  2280. }
  2281. app.get('/analytics/summary', async (request) => {
  2282. const ws = request.workspaceId;
  2283. const filter = parseAccountFilter(request.query.account);
  2284. const db = await getDb();
  2285. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  2286. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  2287. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  2288. // account filter after $unwind so a job targeting multiple platforms only
  2289. // counts the platform(s) that match the filter.
  2290. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  2291. const wsIp = { workspaceId: ws };
  2292. const [
  2293. schedCompleted, schedFailed,
  2294. immPublished, immFailed,
  2295. recentSched, recentImm,
  2296. schedPlatformRaw, immPlatformRaw,
  2297. schedDayRaw, immDayRaw,
  2298. ] = await Promise.all([
  2299. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  2300. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  2301. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...wsIp, ...ipFilter(filter) }),
  2302. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...wsIp, ...ipFilter(filter) }),
  2303. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  2304. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...wsIp, ...ipFilter(filter) }),
  2305. // Platform breakdown from scheduled_jobs destinations
  2306. db.collection('scheduled_jobs').aggregate([
  2307. { $match: { status: 'completed', ...sjFilter(filter) } },
  2308. { $unwind: '$destinations' },
  2309. ...unwindFilter,
  2310. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  2311. { $sort: { count: -1 } },
  2312. ]).toArray(),
  2313. // Platform breakdown from immediate posts platformResults
  2314. db.collection('posts').aggregate([
  2315. { $match: { type: 'immediate', ...wsIp, ...ipFilter(filter) } },
  2316. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  2317. { $unwind: '$results' },
  2318. { $match: { 'results.v.success': true } },
  2319. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  2320. { $group: { _id: '$platform', count: { $sum: 1 } } },
  2321. ]).toArray(),
  2322. // Activity by day from scheduled_jobs (using completedAt)
  2323. db.collection('scheduled_jobs').aggregate([
  2324. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  2325. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  2326. { $sort: { _id: 1 } },
  2327. ]).toArray(),
  2328. // Activity by day from immediate posts
  2329. db.collection('posts').aggregate([
  2330. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...wsIp, ...ipFilter(filter) } },
  2331. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  2332. { $sort: { _id: 1 } },
  2333. ]).toArray(),
  2334. ]);
  2335. const dayMap = {};
  2336. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  2337. dayMap[_id] = (dayMap[_id] || 0) + count;
  2338. }
  2339. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  2340. const platformMap = {};
  2341. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  2342. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  2343. }
  2344. const published = schedCompleted + immPublished;
  2345. const failed = schedFailed + immFailed;
  2346. const total = published + failed;
  2347. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  2348. const recentCount = recentSched + recentImm;
  2349. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  2350. });
  2351. app.get('/analytics/posts', async (request) => {
  2352. const ws = request.workspaceId;
  2353. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  2354. const skip = parseInt(request.query.skip || '0', 10);
  2355. const filter = parseAccountFilter(request.query.account);
  2356. const db = await getDb();
  2357. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  2358. const ipMatch = { type: 'immediate', workspaceId: ws, ...ipFilter(filter) };
  2359. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  2360. db.collection('scheduled_jobs')
  2361. .find(sjMatch)
  2362. .sort({ completedAt: -1, scheduledAt: -1 })
  2363. .skip(skip)
  2364. .limit(limit)
  2365. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  2366. .toArray(),
  2367. db.collection('posts')
  2368. .find(ipMatch)
  2369. .sort({ publishedAt: -1 })
  2370. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  2371. .toArray(),
  2372. db.collection('scheduled_jobs').countDocuments(sjMatch),
  2373. db.collection('posts').countDocuments(ipMatch),
  2374. ]);
  2375. const normalised = [
  2376. ...scheduledJobs.map((j) => ({
  2377. _id: String(j._id),
  2378. type: 'scheduled',
  2379. content: j.content || null,
  2380. destinations: j.destinations || [],
  2381. platformResults: null,
  2382. status: j.status === 'completed' ? 'published' : 'failed',
  2383. publishedAt: j.completedAt || j.scheduledAt,
  2384. })),
  2385. ...immediatePosts.map((p) => ({
  2386. _id: String(p._id),
  2387. type: 'immediate',
  2388. content: p.content || null,
  2389. destinations: p.destinations || [],
  2390. platformResults: p.platformResults || null,
  2391. status: p.status,
  2392. publishedAt: p.publishedAt,
  2393. })),
  2394. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  2395. .slice(0, limit);
  2396. return { posts: normalised, total: schedTotal + immTotal };
  2397. });
  2398. // ─── Analytics Export ─────────────────────────────────────────────────────────
  2399. // GET /analytics/export?format=csv&account=&month=YYYY-MM
  2400. // Exports scheduled jobs + immediate posts as a downloadable CSV.
  2401. app.get('/analytics/export', async (request, reply) => {
  2402. const ws = request.workspaceId;
  2403. const { format = 'csv', account, month } = request.query;
  2404. const filter = parseAccountFilter(account);
  2405. const db = await getDb();
  2406. let dateFilter = {};
  2407. if (month) {
  2408. const start = new Date(`${month}-01T00:00:00.000Z`);
  2409. const end = new Date(start);
  2410. end.setMonth(end.getMonth() + 1);
  2411. dateFilter = { $gte: start, $lt: end };
  2412. }
  2413. const sjMatch = {
  2414. status: { $in: ['completed', 'failed'] },
  2415. ...sjFilter(filter),
  2416. ...(month ? { completedAt: dateFilter } : {}),
  2417. };
  2418. const ipMatch = {
  2419. type: 'immediate',
  2420. workspaceId: ws,
  2421. ...ipFilter(filter),
  2422. ...(month ? { publishedAt: dateFilter } : {}),
  2423. };
  2424. const [scheduledJobs, immediatePosts] = await Promise.all([
  2425. db.collection('scheduled_jobs')
  2426. .find(sjMatch)
  2427. .sort({ completedAt: -1 })
  2428. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  2429. .toArray(),
  2430. db.collection('posts')
  2431. .find(ipMatch)
  2432. .sort({ publishedAt: -1 })
  2433. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  2434. .toArray(),
  2435. ]);
  2436. const rows = [
  2437. ...scheduledJobs.map((j) => ({
  2438. type: 'scheduled',
  2439. date: (j.completedAt || j.scheduledAt)?.toISOString()?.slice(0, 10) ?? '',
  2440. time: (j.completedAt || j.scheduledAt)?.toISOString()?.slice(11, 16) ?? '',
  2441. platforms: (j.destinations || []).map((d) => d.platform).join(' | '),
  2442. status: j.status === 'completed' ? 'published' : 'failed',
  2443. content: j.content || '',
  2444. })),
  2445. ...immediatePosts.map((p) => ({
  2446. type: 'immediate',
  2447. date: p.publishedAt?.toISOString()?.slice(0, 10) ?? '',
  2448. time: p.publishedAt?.toISOString()?.slice(11, 16) ?? '',
  2449. platforms: (p.destinations || []).map((d) => d.platform).join(' | '),
  2450. status: p.status,
  2451. content: p.content || '',
  2452. })),
  2453. ].sort((a, b) => b.date.localeCompare(a.date) || b.time.localeCompare(a.time));
  2454. const escape = (v) => `"${String(v).replace(/"/g, '""')}"`;
  2455. const header = ['Date', 'Time (UTC)', 'Type', 'Platforms', 'Status', 'Content'];
  2456. const lines = [
  2457. header.join(','),
  2458. ...rows.map((r) => [r.date, r.time, r.type, r.platforms, r.status, escape(r.content)].join(',')),
  2459. ];
  2460. const filename = `posts-${month || 'all'}.csv`;
  2461. reply.header('Content-Type', 'text/csv; charset=utf-8');
  2462. reply.header('Content-Disposition', `attachment; filename="${filename}"`);
  2463. return reply.send('' + lines.join('\r\n'));
  2464. });
  2465. // ─── Brand / Account Audit ────────────────────────────────────────────────────
  2466. app.post('/analytics/audit', async (request, reply) => {
  2467. const ws = request.workspaceId;
  2468. const filter = parseAccountFilter(request.query.account);
  2469. const db = await getDb();
  2470. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  2471. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  2472. const recentPosts = await db.collection('posts').find({
  2473. workspaceId: ws,
  2474. publishedAt: { $gte: thirtyDaysAgo },
  2475. ...ipFilter(filter),
  2476. }, { projection: { content: 1, destinations: 1, publishedAt: 1, status: 1 } }).toArray();
  2477. if (recentPosts.length < 3) {
  2478. return reply.code(400).send({ error: 'Not enough publishing history. Publish at least 3 posts first.' });
  2479. }
  2480. // Posting frequency
  2481. const postsLast30 = recentPosts.length;
  2482. const postsLast7 = recentPosts.filter((p) => new Date(p.publishedAt) >= sevenDaysAgo).length;
  2483. const postsPerWeek = Math.round((postsLast30 / 4) * 10) / 10;
  2484. // Platforms used
  2485. const platforms = [...new Set(recentPosts.flatMap((p) => (p.destinations || []).map((d) => d.platform)).filter(Boolean))];
  2486. // Success rate
  2487. const publishedCount = recentPosts.filter((p) => p.status === 'published').length;
  2488. const successRate = Math.round((publishedCount / postsLast30) * 100);
  2489. // Top hashtags from post content
  2490. const hashtagCounts = {};
  2491. for (const post of recentPosts) {
  2492. const re = /#([a-zA-Z]\w*)/g;
  2493. let m;
  2494. re.lastIndex = 0;
  2495. while ((m = re.exec(post.content || '')) !== null) {
  2496. const tag = `#${m[1].toLowerCase()}`;
  2497. hashtagCounts[tag] = (hashtagCounts[tag] || 0) + 1;
  2498. }
  2499. }
  2500. const topHashtags = Object.entries(hashtagCounts)
  2501. .sort((a, b) => b[1] - a[1])
  2502. .slice(0, 5)
  2503. .map(([tag, count]) => `${tag} (${count}x)`)
  2504. .join(', ');
  2505. // Posting hour distribution — identify peak hours
  2506. const hourCounts = {};
  2507. for (const post of recentPosts) {
  2508. if (post.publishedAt) {
  2509. const h = new Date(post.publishedAt).getUTCHours();
  2510. hourCounts[h] = (hourCounts[h] || 0) + 1;
  2511. }
  2512. }
  2513. const peakHours = Object.entries(hourCounts)
  2514. .sort((a, b) => b[1] - a[1])
  2515. .slice(0, 3)
  2516. .map(([h]) => `${h}:00 UTC`)
  2517. .join(', ');
  2518. // Engagement data from post_metrics
  2519. const metricsFilter = filter
  2520. ? { workspaceId: ws, platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  2521. : { workspaceId: ws };
  2522. const metrics = await db.collection('post_metrics')
  2523. .find({ ...metricsFilter, createdAt: { $gte: thirtyDaysAgo } })
  2524. .toArray();
  2525. const avgEngagement = metrics.length > 0
  2526. ? Math.round((metrics.reduce((s, m) => s + (m.metrics?.engagementTotal || 0), 0) / metrics.length) * 10) / 10
  2527. : 0;
  2528. const statsBlock = [
  2529. `Publishing stats (last 30 days):`,
  2530. `- Total posts: ${postsLast30}`,
  2531. `- Posts this week: ${postsLast7}`,
  2532. `- Posts per week (avg): ${postsPerWeek}`,
  2533. `- Platforms used: ${platforms.join(', ') || 'unknown'}`,
  2534. `- Success rate: ${successRate}%`,
  2535. `- Average engagement per post: ${avgEngagement}`,
  2536. `- Current peak posting hours (UTC): ${peakHours || 'not enough data'}`,
  2537. `- Top hashtags in use: ${topHashtags || 'none detected'}`,
  2538. ].join('\n');
  2539. const system = 'You are a social media performance analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2540. const prompt = `Audit this social media account and return a structured report.
  2541. ${statsBlock}
  2542. Return a JSON object with exactly these fields:
  2543. {
  2544. "score": <overall health score 0-100>,
  2545. "summary": "<2-3 sentence assessment>",
  2546. "postingFrequency": { "score": <0-10>, "assessment": "<one sentence>" },
  2547. "engagement": { "score": <0-10>, "benchmark": "<Excellent|Good|Average|Below Average>", "assessment": "<one sentence>" },
  2548. "contentMix": { "score": <0-10>, "assessment": "<one sentence on variety and platform fit>" },
  2549. "recommendations": ["<specific action 1>", "<specific action 2>", "<specific action 3>"]
  2550. }
  2551. Scoring benchmarks: posting 5+x/week = 8-10, 3-4x = 6-7, 1-2x = 4-5, less = 1-3.
  2552. Engagement benchmarks: >5 avg = Excellent, 3-5 = Good, 1-3 = Average, <1 = Below Average.
  2553. Return ONLY the JSON object.`;
  2554. try {
  2555. const pconf = await getActiveProviderConfig(request.workspaceId);
  2556. const model = pconf.model;
  2557. let text = '';
  2558. if (pconf.provider === 'ollama') {
  2559. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2560. text = res.data.response;
  2561. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2562. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2563. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2564. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2565. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2566. text = res.data.choices[0]?.message?.content || '';
  2567. } else if (pconf.provider === 'gemini') {
  2568. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2569. const res = await axios.post(
  2570. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2571. { contents: buildGeminiContents(prompt, system) },
  2572. { timeout: 120000 },
  2573. );
  2574. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2575. } else {
  2576. return reply.code(400).send({ error: 'AI not configured' });
  2577. }
  2578. let audit = null;
  2579. try {
  2580. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2581. audit = JSON.parse(jsonStr);
  2582. if (typeof audit.score !== 'number') throw new Error();
  2583. } catch {
  2584. return reply.code(503).send({ error: 'AI returned invalid audit format — try again' });
  2585. }
  2586. log.info({ action: 'analytics_audit', account: request.query.account || 'all', outcome: 'success' });
  2587. return {
  2588. success: true,
  2589. ...audit,
  2590. stats: { postsLast30, postsLast7, postsPerWeek, platforms, successRate, avgEngagement },
  2591. generatedAt: new Date(),
  2592. };
  2593. } catch (err) {
  2594. return reply.code(503).send({ error: 'Audit failed', detail: err.message });
  2595. }
  2596. });
  2597. // ─── Hashtag Groups ───────────────────────────────────────────────────────────
  2598. app.get('/hashtag-groups', async (request) => {
  2599. const ws = request.workspaceId;
  2600. const db = await getDb();
  2601. const groups = await db.collection('hashtag_groups').find({ workspaceId: ws }).sort({ name: 1 }).toArray();
  2602. return { groups };
  2603. });
  2604. app.post('/hashtag-groups', async (request, reply) => {
  2605. const ws = request.workspaceId;
  2606. const { name, hashtags } = request.body || {};
  2607. if (!name?.trim()) return reply.code(400).send({ error: 'name is required' });
  2608. const tags = (hashtags || []).map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2609. const db = await getDb();
  2610. const result = await db.collection('hashtag_groups').insertOne({
  2611. workspaceId: ws,
  2612. name: name.trim(),
  2613. hashtags: [...new Set(tags)],
  2614. createdAt: new Date(),
  2615. updatedAt: new Date(),
  2616. });
  2617. return { success: true, _id: result.insertedId };
  2618. });
  2619. app.put('/hashtag-groups/:id', async (request, reply) => {
  2620. const ws = request.workspaceId;
  2621. const { id } = request.params;
  2622. const { name, hashtags } = request.body || {};
  2623. const update = { updatedAt: new Date() };
  2624. if (name?.trim()) update.name = name.trim();
  2625. if (hashtags) {
  2626. const tags = hashtags.map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2627. update.hashtags = [...new Set(tags)];
  2628. }
  2629. const db = await getDb();
  2630. let oid;
  2631. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2632. await db.collection('hashtag_groups').updateOne({ _id: oid, workspaceId: ws }, { $set: update });
  2633. return { success: true };
  2634. });
  2635. app.delete('/hashtag-groups/:id', async (request, reply) => {
  2636. const ws = request.workspaceId;
  2637. const { id } = request.params;
  2638. const db = await getDb();
  2639. let oid;
  2640. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2641. await db.collection('hashtag_groups').deleteOne({ _id: oid, workspaceId: ws });
  2642. return { success: true };
  2643. });
  2644. // ─── Hashtag Stats & Scraper ──────────────────────────────────────────────────
  2645. const HASHTAG_RE = /#([a-zA-Z]\w*)/g;
  2646. function extractHashtags(text) {
  2647. if (!text) return [];
  2648. const tags = [];
  2649. let m;
  2650. HASHTAG_RE.lastIndex = 0;
  2651. while ((m = HASHTAG_RE.exec(text)) !== null) tags.push(`#${m[1].toLowerCase()}`);
  2652. return tags;
  2653. }
  2654. function gradeHashtag(count, avgEngagement) {
  2655. if (count >= 5 && avgEngagement >= 10) return 'A';
  2656. if (count >= 3 && avgEngagement >= 3) return 'B';
  2657. if (count >= 2) return 'C';
  2658. return 'D';
  2659. }
  2660. // POST /hashtags/scrape — scan YOUR published posts per-account.
  2661. // Body: { accountKey?: string } — omit to scan all accounts at once.
  2662. app.post('/hashtags/scrape', async (request) => {
  2663. const ws = request.workspaceId;
  2664. const { accountKey: filterAccount } = request.body || {};
  2665. const db = await getDb();
  2666. // tagMap key: `${accountKey}||${hashtag}`
  2667. const tagMap = {};
  2668. function touch(tag, accountKey, platform, engagement) {
  2669. const key = `${accountKey}||${tag}`;
  2670. if (!tagMap[key]) tagMap[key] = { tag, accountKey, count: 0, totalEngagement: 0, platforms: new Set() };
  2671. tagMap[key].count++;
  2672. tagMap[key].totalEngagement += engagement;
  2673. tagMap[key].platforms.add(platform);
  2674. }
  2675. // Engagement lookup keyed by content fingerprint
  2676. const postMetrics = await db.collection('post_metrics').find({ workspaceId: ws }).toArray();
  2677. const metricsByContent = {};
  2678. for (const m of postMetrics) {
  2679. if (m.content) {
  2680. const key = m.content.slice(0, 100).toLowerCase().trim();
  2681. metricsByContent[key] = (metricsByContent[key] || 0) + (m.metrics?.engagementTotal || 0);
  2682. }
  2683. }
  2684. // Scan YOUR published posts only — feeds are others' content, not your performance
  2685. const posts = await db.collection('posts').find({ workspaceId: ws }, { projection: { content: 1, destinations: 1 } }).toArray();
  2686. for (const post of posts) {
  2687. const tags = extractHashtags(post.content || '');
  2688. if (!tags.length) continue;
  2689. const engagement = post.content
  2690. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  2691. : 0;
  2692. const destinations = post.destinations?.length ? post.destinations : [{ platform: 'unknown' }];
  2693. for (const dest of destinations) {
  2694. const acctKey = dest.accountId ? `${dest.platform}:${dest.accountId}` : dest.platform;
  2695. if (filterAccount && acctKey !== filterAccount) continue;
  2696. for (const tag of tags) {
  2697. touch(tag, acctKey, dest.platform, engagement / Math.max(tags.length, 1));
  2698. }
  2699. }
  2700. }
  2701. let scraped = 0;
  2702. for (const [compoundKey, data] of Object.entries(tagMap)) {
  2703. const avgEngagement = data.count > 0 ? data.totalEngagement / data.count : 0;
  2704. await db.collection('hashtag_stats').updateOne(
  2705. { _id: compoundKey, workspaceId: ws },
  2706. {
  2707. $set: {
  2708. workspaceId: ws,
  2709. hashtag: data.tag,
  2710. accountKey: data.accountKey,
  2711. count: data.count,
  2712. avgEngagement: Math.round(avgEngagement * 10) / 10,
  2713. grade: gradeHashtag(data.count, avgEngagement),
  2714. platforms: [...data.platforms],
  2715. lastScraped: new Date(),
  2716. },
  2717. },
  2718. { upsert: true }
  2719. );
  2720. scraped++;
  2721. }
  2722. log.info({ action: 'hashtag_scrape', accountKey: filterAccount || 'all', outcome: 'success', scraped });
  2723. return { success: true, scraped };
  2724. });
  2725. app.get('/hashtags/stats', async (request) => {
  2726. const ws = request.workspaceId;
  2727. const { sort, accountKey } = request.query;
  2728. const db = await getDb();
  2729. const sortField = sort === 'engagement' ? 'avgEngagement' : 'count';
  2730. if (accountKey) {
  2731. // Per-account view
  2732. const stats = await db.collection('hashtag_stats')
  2733. .find({ workspaceId: ws, accountKey })
  2734. .sort({ [sortField]: -1 })
  2735. .limit(200)
  2736. .toArray();
  2737. return { stats };
  2738. }
  2739. // Aggregate view: group by hashtag across all accounts in this workspace
  2740. const allStats = await db.collection('hashtag_stats').find({ workspaceId: ws, accountKey: { $exists: true } }).toArray();
  2741. const grouped = new Map();
  2742. for (const s of allStats) {
  2743. if (!s.hashtag) continue;
  2744. if (!grouped.has(s.hashtag)) {
  2745. grouped.set(s.hashtag, { count: 0, totalEngagement: 0, totalCount: 0, platforms: new Set(), lastScraped: null });
  2746. }
  2747. const g = grouped.get(s.hashtag);
  2748. g.count += s.count;
  2749. g.totalEngagement += s.avgEngagement * s.count;
  2750. g.totalCount += s.count;
  2751. for (const p of (s.platforms || [])) g.platforms.add(p);
  2752. if (!g.lastScraped || (s.lastScraped && new Date(s.lastScraped) > new Date(g.lastScraped))) g.lastScraped = s.lastScraped;
  2753. }
  2754. const stats = [...grouped.entries()]
  2755. .map(([tag, g]) => {
  2756. const avgEngagement = g.totalCount > 0 ? Math.round((g.totalEngagement / g.totalCount) * 10) / 10 : 0;
  2757. return {
  2758. _id: tag,
  2759. hashtag: tag,
  2760. accountKey: null,
  2761. count: g.count,
  2762. avgEngagement,
  2763. grade: gradeHashtag(g.count, avgEngagement),
  2764. platforms: [...g.platforms],
  2765. lastScraped: g.lastScraped,
  2766. };
  2767. })
  2768. .sort((a, b) => b[sortField] - a[sortField])
  2769. .slice(0, 200);
  2770. return { stats };
  2771. });
  2772. app.post('/hashtags/ai-suggest', async (request, reply) => {
  2773. const ws = request.workspaceId;
  2774. const { accountKey, topTags = [], count = 20 } = request.body || {};
  2775. let profileCtx = '';
  2776. if (accountKey) {
  2777. try {
  2778. const db = await getDb();
  2779. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  2780. if (profile) {
  2781. const parts = [];
  2782. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  2783. if (profile.description) parts.push(`Description: ${profile.description}`);
  2784. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  2785. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  2786. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  2787. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  2788. profileCtx = parts.join('\n');
  2789. }
  2790. } catch (_) {}
  2791. }
  2792. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  2793. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  2794. const prompt = [
  2795. `Suggest ${count} high-performing hashtags for a social media account.`,
  2796. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  2797. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  2798. `\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`,
  2799. ].filter(Boolean).join('');
  2800. try {
  2801. const pconf = await getActiveProviderConfig(request.workspaceId);
  2802. const model = pconf.model;
  2803. let text = '';
  2804. if (pconf.provider === 'ollama') {
  2805. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  2806. text = res.data.response;
  2807. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2808. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2809. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2810. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2811. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  2812. text = res.data.choices[0]?.message?.content || '';
  2813. } else if (pconf.provider === 'gemini') {
  2814. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2815. const res = await axios.post(
  2816. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2817. { contents: buildGeminiContents(prompt, system) },
  2818. { timeout: 60000 },
  2819. );
  2820. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2821. } else {
  2822. return reply.code(400).send({ error: 'AI not configured' });
  2823. }
  2824. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  2825. return { success: true, hashtags: tags };
  2826. } catch (err) {
  2827. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  2828. }
  2829. });
  2830. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  2831. async function extractTextFromUrl(url) {
  2832. try {
  2833. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  2834. const html = res.data || '';
  2835. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  2836. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  2837. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  2838. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  2839. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  2840. } catch {
  2841. return '';
  2842. }
  2843. }
  2844. async function scrapeBluesky(profileUrl) {
  2845. try {
  2846. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  2847. if (!handle) return '';
  2848. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  2849. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  2850. return posts.join('\n').slice(0, 3000);
  2851. } catch {
  2852. return '';
  2853. }
  2854. }
  2855. async function scrapeMastodon(profileUrl) {
  2856. try {
  2857. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  2858. if (!m) return '';
  2859. const [, instance, username] = m;
  2860. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  2861. const accountId = lookupRes.data?.id;
  2862. if (!accountId) return '';
  2863. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  2864. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  2865. return posts.join('\n').slice(0, 3000);
  2866. } catch {
  2867. return '';
  2868. }
  2869. }
  2870. async function runCompetitorScrape(competitorId) {
  2871. const db = await getDb();
  2872. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  2873. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  2874. const newItems = [];
  2875. if (competitor.websiteUrl) {
  2876. const text = await extractTextFromUrl(competitor.websiteUrl);
  2877. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  2878. }
  2879. const socialEntries = Object.entries(competitor.socialUrls || {});
  2880. for (const [platform, url] of socialEntries) {
  2881. if (!url) continue;
  2882. let text = '';
  2883. if (platform === 'bluesky') text = await scrapeBluesky(url);
  2884. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  2885. else text = await extractTextFromUrl(url);
  2886. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  2887. }
  2888. const existing = competitor.scrapedContent || [];
  2889. // Detect whether any newly scraped content differs from what was previously stored
  2890. const existingFingerprints = new Set(existing.map((s) => s.url + '||' + s.text.slice(0, 200)));
  2891. const contentChanged = newItems.some((item) => !existingFingerprints.has(item.url + '||' + item.text.slice(0, 200)));
  2892. const combined = [...newItems, ...existing].slice(0, 20);
  2893. await db.collection('competitors').updateOne(
  2894. { _id: new ObjectId(competitorId) },
  2895. { $set: { scrapedContent: combined, contentChanged, lastScraped: new Date(), updatedAt: new Date() } },
  2896. );
  2897. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  2898. }
  2899. async function buildCompetitorSystemSuffix(ws = 'default') {
  2900. try {
  2901. const db = await getDb();
  2902. const competitors = await db.collection('competitors').find({
  2903. workspaceId: ws,
  2904. $or: [{ 'aiAnalysis.positioning': { $nin: ['', null] } }, { aiSummary: { $nin: ['', null] } }],
  2905. }).toArray();
  2906. if (!competitors.length) return '';
  2907. const lines = competitors.map((c) => {
  2908. if (c.aiAnalysis?.positioning) {
  2909. const a = c.aiAnalysis;
  2910. const parts = [`- ${c.name}:`];
  2911. if (a.positioning) parts.push(` Positioning: ${a.positioning}`);
  2912. if (a.gaps?.length) parts.push(` Weaknesses/gaps: ${a.gaps.join('; ')}`);
  2913. if (a.themes?.length) parts.push(` Key themes: ${a.themes.join(', ')}`);
  2914. return parts.join('\n');
  2915. }
  2916. return `- ${c.name}: ${c.aiSummary}`;
  2917. }).join('\n');
  2918. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  2919. } catch {
  2920. return '';
  2921. }
  2922. }
  2923. // Save Google Places API key (used for local competitor discovery)
  2924. app.post('/credentials/google-places', async (request, reply) => {
  2925. const ws = request.workspaceId;
  2926. const { apiKey } = request.body || {};
  2927. if (!apiKey?.trim()) return reply.code(400).send({ error: 'apiKey is required' });
  2928. await setCredentials(ws, 'google_places', { apiKey: apiKey.trim() });
  2929. return { success: true };
  2930. });
  2931. app.get('/credentials/google-places', async (request) => {
  2932. const ws = request.workspaceId;
  2933. const cred = await getCredentials(ws, 'google_places');
  2934. return { configured: !!cred?.apiKey, keyHint: cred?.apiKey ? `****${cred.apiKey.slice(-4)}` : null };
  2935. });
  2936. app.delete('/credentials/google-places', async (request) => {
  2937. const ws = request.workspaceId;
  2938. await deleteCredentials(ws, 'google_places');
  2939. return { success: true };
  2940. });
  2941. // Discover local competitors via Google Places API
  2942. app.post('/competitors/discover-local', async (request, reply) => {
  2943. const ws = request.workspaceId;
  2944. const { location, businessType, radiusMeters = 5000 } = request.body || {};
  2945. if (!location) return reply.code(400).send({ error: 'location is required' });
  2946. const cred = await getCredentials(ws, 'google_places');
  2947. if (!cred?.apiKey) return reply.code(400).send({ error: 'Google Places API key not configured — add it in Settings.' });
  2948. // Step 1: Geocode the location string to coordinates
  2949. let lat, lng;
  2950. try {
  2951. const geoRes = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
  2952. params: { address: location, key: cred.apiKey },
  2953. timeout: 10000,
  2954. });
  2955. const loc = geoRes.data.results?.[0]?.geometry?.location;
  2956. if (!loc) return reply.code(400).send({ error: `Could not geocode location: "${location}"` });
  2957. lat = loc.lat;
  2958. lng = loc.lng;
  2959. } catch (err) {
  2960. return reply.code(503).send({ error: 'Geocoding failed', detail: err.message });
  2961. }
  2962. // Step 2: Text Search for nearby businesses of the given type
  2963. try {
  2964. const query = businessType ? `${businessType} near ${location}` : location;
  2965. const searchRes = await axios.get('https://maps.googleapis.com/maps/api/place/textsearch/json', {
  2966. params: {
  2967. query,
  2968. location: `${lat},${lng}`,
  2969. radius: Math.min(radiusMeters, 50000),
  2970. key: cred.apiKey,
  2971. },
  2972. timeout: 10000,
  2973. });
  2974. const places = (searchRes.data.results || []).slice(0, 10);
  2975. if (!places.length) return { success: true, suggestions: [] };
  2976. // Step 3: Fetch website URLs for places that have them
  2977. const suggestions = [];
  2978. for (const place of places.slice(0, 8)) {
  2979. try {
  2980. const detailRes = await axios.get('https://maps.googleapis.com/maps/api/place/details/json', {
  2981. params: { place_id: place.place_id, fields: 'name,website,formatted_address,rating', key: cred.apiKey },
  2982. timeout: 8000,
  2983. });
  2984. const detail = detailRes.data.result || {};
  2985. suggestions.push({
  2986. name: detail.name || place.name,
  2987. websiteUrl: detail.website || null,
  2988. address: detail.formatted_address || '',
  2989. rating: detail.rating || null,
  2990. reason: `Local ${businessType || 'business'} near ${location}${detail.rating ? ` · ${detail.rating}★` : ''}`,
  2991. });
  2992. } catch {
  2993. suggestions.push({ name: place.name, websiteUrl: null, address: '', rating: null, reason: `Local ${businessType || 'business'} near ${location}` });
  2994. }
  2995. }
  2996. log.info({ action: 'discover_local_competitors', location, count: suggestions.length, outcome: 'success' });
  2997. return { success: true, suggestions };
  2998. } catch (err) {
  2999. return reply.code(503).send({ error: 'Google Places search failed', detail: err.message });
  3000. }
  3001. });
  3002. // Discover competitors automatically using AI + account profile context
  3003. app.post('/competitors/discover', async (request, reply) => {
  3004. const ws = request.workspaceId;
  3005. const db = await getDb();
  3006. // Use the first account profile for business context
  3007. const profile = await db.collection('account_profiles').findOne({ workspaceId: ws });
  3008. const contextParts = [];
  3009. if (profile) {
  3010. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  3011. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  3012. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  3013. if (profile.websiteUrl) contextParts.push(`Website: ${profile.websiteUrl}`);
  3014. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  3015. }
  3016. if (!contextParts.length) {
  3017. return reply.code(400).send({ error: 'Set up at least one Account Profile in Settings before discovering competitors.' });
  3018. }
  3019. const system = 'You are a market research analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  3020. const prompt = `Based on the following business profile, identify the top 5 direct competitors.
  3021. ${contextParts.join('\n')}
  3022. Return ONLY a JSON array of objects, e.g.:
  3023. [{"name":"Competitor Name","websiteUrl":"https://example.com","reason":"One sentence on why they compete directly"}]
  3024. Rules:
  3025. - Return real, existing businesses only.
  3026. - Include only direct competitors (same product/service category, same target audience).
  3027. - websiteUrl must be a valid https URL to the competitor's main website.
  3028. - No explanation outside the JSON array.`;
  3029. try {
  3030. const pconf = await getActiveProviderConfig(request.workspaceId);
  3031. const model = pconf.model;
  3032. let text = '';
  3033. if (pconf.provider === 'ollama') {
  3034. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3035. text = res.data.response;
  3036. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3037. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3038. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3039. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3040. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3041. text = res.data.choices[0]?.message?.content || '';
  3042. } else if (pconf.provider === 'gemini') {
  3043. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3044. const res = await axios.post(
  3045. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3046. { contents: buildGeminiContents(prompt, system) },
  3047. { timeout: 120000 },
  3048. );
  3049. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3050. } else {
  3051. return reply.code(400).send({ error: 'AI not configured' });
  3052. }
  3053. let suggestions = [];
  3054. try {
  3055. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3056. const parsed = JSON.parse(jsonStr);
  3057. if (!Array.isArray(parsed)) throw new Error();
  3058. suggestions = parsed
  3059. .filter((s) => s && typeof s.name === 'string' && typeof s.websiteUrl === 'string')
  3060. .slice(0, 5)
  3061. .map((s) => ({
  3062. name: s.name.trim(),
  3063. websiteUrl: s.websiteUrl.trim(),
  3064. reason: typeof s.reason === 'string' ? s.reason.trim() : '',
  3065. }));
  3066. } catch {
  3067. return reply.code(503).send({ error: 'AI returned invalid format — try again' });
  3068. }
  3069. log.info({ action: 'competitor_discover', count: suggestions.length, outcome: 'success' });
  3070. return { success: true, suggestions };
  3071. } catch (err) {
  3072. return reply.code(503).send({ error: 'Discovery failed', detail: err.message });
  3073. }
  3074. });
  3075. // List competitors
  3076. app.get('/competitors', async (request) => {
  3077. const ws = request.workspaceId;
  3078. const db = await getDb();
  3079. const list = await db.collection('competitors').find({ workspaceId: ws }).sort({ createdAt: 1 }).toArray();
  3080. return list;
  3081. });
  3082. // Add competitor (max 5 per workspace)
  3083. app.post('/competitors', async (request, reply) => {
  3084. const ws = request.workspaceId;
  3085. const db = await getDb();
  3086. const count = await db.collection('competitors').countDocuments({ workspaceId: ws });
  3087. if (count >= 5) return reply.code(400).send({ error: 'Maximum 5 competitors allowed' });
  3088. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  3089. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  3090. const now = new Date();
  3091. const result = await db.collection('competitors').insertOne({
  3092. workspaceId: ws, name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  3093. });
  3094. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  3095. return doc;
  3096. });
  3097. // Update competitor
  3098. app.put('/competitors/:id', async (request, reply) => {
  3099. const ws = request.workspaceId;
  3100. const db = await getDb();
  3101. const { name, websiteUrl, socialUrls } = request.body || {};
  3102. const updates = { updatedAt: new Date() };
  3103. if (name !== undefined) updates.name = name;
  3104. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  3105. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  3106. const oid = new ObjectId(request.params.id);
  3107. await db.collection('competitors').updateOne({ _id: oid, workspaceId: ws }, { $set: updates });
  3108. const doc = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3109. return doc;
  3110. });
  3111. // Delete competitor
  3112. app.delete('/competitors/:id', async (request, reply) => {
  3113. const ws = request.workspaceId;
  3114. const db = await getDb();
  3115. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id), workspaceId: ws });
  3116. return { success: true };
  3117. });
  3118. // Scrape one competitor — returns jobId immediately, runs in background
  3119. app.post('/competitors/:id/scrape', async (request, reply) => {
  3120. const jobId = new ObjectId().toString();
  3121. activeScrapeJobs.set(jobId, { status: 'running', sources: 0, message: '' });
  3122. (async () => {
  3123. try {
  3124. const result = await runCompetitorScrape(request.params.id);
  3125. activeScrapeJobs.set(jobId, {
  3126. status: result.ok ? 'done' : 'failed',
  3127. sources: result.sources,
  3128. message: result.message,
  3129. });
  3130. } catch (err) {
  3131. activeScrapeJobs.set(jobId, { status: 'failed', sources: 0, message: err.message });
  3132. }
  3133. })();
  3134. return reply.code(202).send({ jobId });
  3135. });
  3136. // Poll scrape job status
  3137. app.get('/competitors/:id/scrape-status/:jobId', async (request, reply) => {
  3138. const job = activeScrapeJobs.get(request.params.jobId);
  3139. if (!job) return reply.code(404).send({ error: 'Job not found or expired' });
  3140. return job;
  3141. });
  3142. // Scrape all competitors (called by scheduler — always operates on default workspace)
  3143. app.post('/competitors/scrape-all', async (request, reply) => {
  3144. const ws = request.workspaceId;
  3145. const db = await getDb();
  3146. const all = await db.collection('competitors').find({ workspaceId: ws }).toArray();
  3147. const results = [];
  3148. for (const c of all) {
  3149. const r = await runCompetitorScrape(c._id.toString());
  3150. results.push({ id: c._id.toString(), name: c.name, ...r });
  3151. }
  3152. return { success: true, results };
  3153. });
  3154. // Summarize competitor content with AI — returns structured analysis
  3155. app.post('/competitors/:id/summarize', async (request, reply) => {
  3156. const ws = request.workspaceId;
  3157. const db = await getDb();
  3158. const oid = new ObjectId(request.params.id);
  3159. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3160. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3161. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  3162. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  3163. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  3164. const prompt = `Analyse the following content from "${competitor.name}" and return a JSON object with exactly these fields:
  3165. {
  3166. "themes": ["3-5 main content topics or pillars they focus on"],
  3167. "tone": "one sentence describing their voice and communication style",
  3168. "positioning": "one sentence on how they position themselves in the market",
  3169. "gaps": ["2-3 topics or angles they ignore or handle poorly — opportunities for you"],
  3170. "moves": ["3 specific content angles you could use to stand out against them"],
  3171. "profile": {
  3172. "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)",
  3173. "keyFeatures": ["3-5 core product or service features they emphasise"],
  3174. "marketingChannels": ["2-4 social/marketing channels they actively use based on content"],
  3175. "targetCustomer": "one sentence describing their apparent ideal customer"
  3176. },
  3177. "prediction": {
  3178. "satisfiedWithPosition": <true if they appear content with their current position, false if they seem to be pushing for growth>,
  3179. "likelyNextMoves": ["2-3 strategic moves they will probably make based on current trajectory"],
  3180. "vulnerabilities": ["2-3 specific weaknesses or blind spots visible in their content"],
  3181. "retaliationTriggers": ["1-2 moves by a competitor that would most likely provoke a strong response from them"]
  3182. }
  3183. }
  3184. Content:
  3185. ${content}
  3186. Return ONLY the JSON object. No explanation, no markdown.`;
  3187. try {
  3188. const pconf = await getActiveProviderConfig(request.workspaceId);
  3189. const model = pconf.model;
  3190. let text = '';
  3191. if (pconf.provider === 'ollama') {
  3192. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  3193. text = res.data.response;
  3194. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3195. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3196. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3197. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3198. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  3199. text = res.data.choices[0]?.message?.content || '';
  3200. } else if (pconf.provider === 'gemini') {
  3201. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3202. const res = await axios.post(
  3203. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3204. { contents: buildGeminiContents(prompt, system) },
  3205. { timeout: 180000 },
  3206. );
  3207. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3208. } else {
  3209. return reply.code(400).send({ error: 'AI not configured' });
  3210. }
  3211. let aiAnalysis = null;
  3212. try {
  3213. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3214. aiAnalysis = JSON.parse(jsonStr);
  3215. if (!Array.isArray(aiAnalysis.themes)) aiAnalysis.themes = [];
  3216. if (typeof aiAnalysis.tone !== 'string') aiAnalysis.tone = '';
  3217. if (typeof aiAnalysis.positioning !== 'string') aiAnalysis.positioning = '';
  3218. if (!Array.isArray(aiAnalysis.gaps)) aiAnalysis.gaps = [];
  3219. if (!Array.isArray(aiAnalysis.moves)) aiAnalysis.moves = [];
  3220. // Validate profile block
  3221. if (!aiAnalysis.profile || typeof aiAnalysis.profile !== 'object') aiAnalysis.profile = {};
  3222. if (typeof aiAnalysis.profile.pricing !== 'string') aiAnalysis.profile.pricing = '';
  3223. if (!Array.isArray(aiAnalysis.profile.keyFeatures)) aiAnalysis.profile.keyFeatures = [];
  3224. if (!Array.isArray(aiAnalysis.profile.marketingChannels)) aiAnalysis.profile.marketingChannels = [];
  3225. if (typeof aiAnalysis.profile.targetCustomer !== 'string') aiAnalysis.profile.targetCustomer = '';
  3226. // Validate prediction block
  3227. if (!aiAnalysis.prediction || typeof aiAnalysis.prediction !== 'object') aiAnalysis.prediction = {};
  3228. if (typeof aiAnalysis.prediction.satisfiedWithPosition !== 'boolean') aiAnalysis.prediction.satisfiedWithPosition = true;
  3229. if (!Array.isArray(aiAnalysis.prediction.likelyNextMoves)) aiAnalysis.prediction.likelyNextMoves = [];
  3230. if (!Array.isArray(aiAnalysis.prediction.vulnerabilities)) aiAnalysis.prediction.vulnerabilities = [];
  3231. if (!Array.isArray(aiAnalysis.prediction.retaliationTriggers)) aiAnalysis.prediction.retaliationTriggers = [];
  3232. } catch {
  3233. aiAnalysis = null;
  3234. }
  3235. if (!aiAnalysis) return reply.code(503).send({ error: 'AI returned invalid analysis format — try again' });
  3236. await db.collection('competitors').updateOne(
  3237. { _id: oid, workspaceId: ws },
  3238. { $set: { aiAnalysis, aiSummary: '', updatedAt: new Date() } },
  3239. );
  3240. return { success: true, aiAnalysis };
  3241. } catch (err) {
  3242. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  3243. }
  3244. });
  3245. // Extract keywords from scraped content using AI (item 34)
  3246. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  3247. const ws = request.workspaceId;
  3248. const db = await getDb();
  3249. const oid = new ObjectId(request.params.id);
  3250. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3251. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3252. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  3253. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  3254. const system = 'You are an SEO and content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  3255. 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:
  3256. - informational: user wants to learn ("how to", "what is", "guide", "tips")
  3257. - commercial: user is evaluating options ("best", "vs", "review", "top", "alternative")
  3258. - transactional: user is ready to act ("buy", "free", "pricing", "download", "get started")
  3259. - navigational: user is searching for a specific brand or tool by name
  3260. Content:
  3261. ${content}
  3262. Return ONLY a JSON array, e.g.:
  3263. [{"term": "project management software", "intent": "commercial"}, {"term": "how to manage tasks", "intent": "informational"}]
  3264. No explanation, no markdown.`;
  3265. try {
  3266. const pconf = await getActiveProviderConfig(request.workspaceId);
  3267. const model = pconf.model;
  3268. let text = '';
  3269. if (pconf.provider === 'ollama') {
  3270. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3271. text = res.data.response;
  3272. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3273. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3274. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3275. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3276. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3277. text = res.data.choices[0]?.message?.content || '';
  3278. } else if (pconf.provider === 'gemini') {
  3279. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3280. const res = await axios.post(
  3281. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3282. { contents: buildGeminiContents(prompt, system) },
  3283. { timeout: 120000 },
  3284. );
  3285. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3286. } else {
  3287. return reply.code(400).send({ error: 'AI not configured' });
  3288. }
  3289. const VALID_INTENTS = new Set(['informational', 'commercial', 'transactional', 'navigational']);
  3290. let keywords = [];
  3291. try {
  3292. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3293. const parsed = JSON.parse(jsonStr);
  3294. if (!Array.isArray(parsed)) throw new Error();
  3295. const now = new Date();
  3296. keywords = parsed
  3297. .filter((k) => k && typeof k.term === 'string' && k.term.trim())
  3298. .slice(0, 20)
  3299. .map((k) => ({
  3300. term: k.term.trim(),
  3301. intent: VALID_INTENTS.has(k.intent) ? k.intent : 'informational',
  3302. extractedAt: now,
  3303. }));
  3304. } catch {
  3305. keywords = [];
  3306. }
  3307. await db.collection('competitors').updateOne(
  3308. { _id: oid, workspaceId: ws },
  3309. { $set: { keywords, updatedAt: new Date() } },
  3310. );
  3311. return { success: true, keywords };
  3312. } catch (err) {
  3313. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  3314. }
  3315. });
  3316. // Analyse content gaps — compare competitor keywords against user's hashtag_stats
  3317. app.post('/competitors/:id/analyze-gaps', async (request, reply) => {
  3318. const ws = request.workspaceId;
  3319. const db = await getDb();
  3320. const oid = new ObjectId(request.params.id);
  3321. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3322. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3323. const keywords = (competitor.keywords || []);
  3324. if (!keywords.length) return reply.code(400).send({ error: 'Extract keywords first before analysing gaps' });
  3325. const hashtagDocs = await db.collection('hashtag_stats')
  3326. .find({ workspaceId: ws, accountKey: { $exists: true } }, { projection: { _id: 0, hashtag: 1 } })
  3327. .toArray();
  3328. const hashtagStatsEmpty = hashtagDocs.length === 0;
  3329. // Deduplicate across accounts — same hashtag used by any account counts as covered
  3330. const uniqueTags = [...new Set(hashtagDocs.map((h) => h.hashtag).filter(Boolean))];
  3331. const hashtagTexts = uniqueTags.map((tag) => ({ id: tag, text: tag.replace(/^#/, '').toLowerCase() }));
  3332. const INTENT_ORDER = { transactional: 0, commercial: 1, informational: 2, navigational: 3 };
  3333. function findMatchingHashtags(term) {
  3334. const words = term.toLowerCase().split(/\s+/).filter((w) => w.length >= 4);
  3335. return hashtagTexts
  3336. .filter(({ text }) => words.some((w) => text.includes(w)))
  3337. .map(({ id }) => id);
  3338. }
  3339. const gaps = [];
  3340. const covered = [];
  3341. for (const kw of keywords) {
  3342. const term = typeof kw === 'string' ? kw : kw.term;
  3343. const intent = typeof kw === 'string' ? 'informational' : (kw.intent || 'informational');
  3344. const matched = findMatchingHashtags(term);
  3345. if (matched.length) {
  3346. covered.push({ term, intent, matchedHashtags: matched.slice(0, 4) });
  3347. } else {
  3348. gaps.push({ term, intent });
  3349. }
  3350. }
  3351. gaps.sort((a, b) => (INTENT_ORDER[a.intent] ?? 99) - (INTENT_ORDER[b.intent] ?? 99));
  3352. const gapAnalysis = { gaps, covered, totalKeywords: keywords.length, hashtagStatsEmpty, lastAnalyzed: new Date() };
  3353. await db.collection('competitors').updateOne(
  3354. { _id: oid, workspaceId: ws },
  3355. { $set: { gapAnalysis, updatedAt: new Date() } },
  3356. );
  3357. return { success: true, ...gapAnalysis };
  3358. });
  3359. // Detect and classify market signals from latest scraped content
  3360. app.post('/competitors/:id/detect-signals', async (request, reply) => {
  3361. const ws = request.workspaceId;
  3362. const db = await getDb();
  3363. const oid = new ObjectId(request.params.id);
  3364. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3365. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3366. const recentContent = (competitor.scrapedContent || []).slice(0, 10);
  3367. if (!recentContent.length) return reply.code(400).send({ error: 'Scrape first before detecting signals' });
  3368. const contentText = recentContent.map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 4000);
  3369. const baseline = competitor.aiAnalysis
  3370. ? `Previous profile — Themes: ${(competitor.aiAnalysis.themes || []).join(', ')}. Tone: ${competitor.aiAnalysis.tone || 'unknown'}.`
  3371. : 'No prior analysis available.';
  3372. const system = 'You are a competitive intelligence analyst specialising in market signal detection. Return only valid JSON with no explanation, no markdown.';
  3373. const prompt = `Analyse the latest content from competitor "${competitor.name}" and detect any notable changes or strategic signals.
  3374. Baseline context:
  3375. ${baseline}
  3376. Latest scraped content:
  3377. ${contentText}
  3378. Classify any changes you detect. Use these signal types:
  3379. - topic_expansion: new content themes or topics not previously seen
  3380. - tone_shift: measurable change in communication style or voice
  3381. - campaign_launch: evidence of a new marketing campaign or product promotion
  3382. - pricing_change: any mention of new pricing, offers, or discounts
  3383. - market_entry: signs of entering a new platform, audience, or geography
  3384. - competitive_aggression: direct competitor comparisons, attack marketing, or poaching language
  3385. - frequency_change: evidence of significantly more or less content activity
  3386. Return ONLY a JSON array (empty array [] if no significant signals):
  3387. [{"type":"<type>","description":"<one sentence describing the specific change>","severity":"<low|medium|high>"}]
  3388. Severity guide: high = major strategic shift, medium = notable change worth monitoring, low = minor or uncertain change.`;
  3389. try {
  3390. const pconf = await getActiveProviderConfig(request.workspaceId);
  3391. const model = pconf.model;
  3392. let text = '';
  3393. if (pconf.provider === 'ollama') {
  3394. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3395. text = res.data.response;
  3396. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3397. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3398. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3399. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3400. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3401. text = res.data.choices[0]?.message?.content || '';
  3402. } else if (pconf.provider === 'gemini') {
  3403. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3404. const res = await axios.post(
  3405. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3406. { contents: buildGeminiContents(prompt, system) },
  3407. { timeout: 120000 },
  3408. );
  3409. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3410. } else {
  3411. return reply.code(400).send({ error: 'AI not configured' });
  3412. }
  3413. const VALID_TYPES = new Set(['topic_expansion', 'tone_shift', 'campaign_launch', 'pricing_change', 'market_entry', 'competitive_aggression', 'frequency_change']);
  3414. const VALID_SEVERITIES = new Set(['low', 'medium', 'high']);
  3415. let signals = [];
  3416. try {
  3417. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3418. const parsed = JSON.parse(jsonStr);
  3419. if (!Array.isArray(parsed)) throw new Error();
  3420. const now = new Date();
  3421. signals = parsed
  3422. .filter((s) => s && VALID_TYPES.has(s.type) && typeof s.description === 'string')
  3423. .slice(0, 8)
  3424. .map((s) => ({
  3425. type: s.type,
  3426. description: s.description.trim(),
  3427. severity: VALID_SEVERITIES.has(s.severity) ? s.severity : 'medium',
  3428. detectedAt: now,
  3429. }));
  3430. } catch {
  3431. signals = [];
  3432. }
  3433. await db.collection('competitors').updateOne(
  3434. { _id: oid, workspaceId: ws },
  3435. { $set: { signals, contentChanged: false, updatedAt: new Date() } },
  3436. );
  3437. log.info({ action: 'detect_signals', competitorId: request.params.id, count: signals.length, outcome: 'success' });
  3438. return { success: true, signals };
  3439. } catch (err) {
  3440. return reply.code(503).send({ error: 'Signal detection failed', detail: err.message });
  3441. }
  3442. });
  3443. // Generate a 5-post content roadmap from competitor keywords and gaps
  3444. app.post('/competitors/:id/content-roadmap', async (request, reply) => {
  3445. const ws = request.workspaceId;
  3446. const db = await getDb();
  3447. const oid = new ObjectId(request.params.id);
  3448. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3449. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3450. const keywords = (competitor.keywords || []);
  3451. const hasKeywords = keywords.length > 0;
  3452. const hasContent = (competitor.scrapedContent || []).length > 0;
  3453. if (!hasKeywords && !hasContent) return reply.code(400).send({ error: 'Extract keywords first before generating a roadmap' });
  3454. const kwList = hasKeywords
  3455. ? keywords.map((k) => (typeof k === 'string' ? k : k.term)).join(', ')
  3456. : '';
  3457. const gaps = competitor.aiAnalysis?.gaps || [];
  3458. const moves = competitor.aiAnalysis?.moves || [];
  3459. const gapsSection = gaps.length ? `\nCompetitor gaps/weaknesses:\n${gaps.map((g) => `- ${g}`).join('\n')}` : '';
  3460. const movesSection = moves.length ? `\nSuggested differentiation angles:\n${moves.map((m) => `- ${m}`).join('\n')}` : '';
  3461. const kwSection = kwList ? `\nCompetitor's keywords: ${kwList}` : '';
  3462. const system = 'You are a content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  3463. const prompt = `Create a 5-post content roadmap to compete against "${competitor.name}".
  3464. ${kwSection}${gapsSection}${movesSection}
  3465. Generate 5 post ideas that exploit their weaknesses and differentiate clearly. For each post return:
  3466. - topic: short topic name, max 8 words
  3467. - headline: an engaging opening line or hook ready to use as post content (1-2 sentences)
  3468. - keywords: array of 2-3 keywords from the competitor's list to target (use exact terms where available)
  3469. - rationale: one sentence on why this post wins against ${competitor.name}
  3470. Return ONLY a JSON array:
  3471. [{"topic":"...","headline":"...","keywords":["..."],"rationale":"..."}]
  3472. No explanation, no markdown.`;
  3473. try {
  3474. const pconf = await getActiveProviderConfig(request.workspaceId);
  3475. const model = pconf.model;
  3476. let text = '';
  3477. if (pconf.provider === 'ollama') {
  3478. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  3479. text = res.data.response;
  3480. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3481. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3482. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3483. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3484. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  3485. text = res.data.choices[0]?.message?.content || '';
  3486. } else if (pconf.provider === 'gemini') {
  3487. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3488. const res = await axios.post(
  3489. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3490. { contents: buildGeminiContents(prompt, system) },
  3491. { timeout: 180000 },
  3492. );
  3493. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3494. } else {
  3495. return reply.code(400).send({ error: 'AI not configured' });
  3496. }
  3497. let roadmap = [];
  3498. try {
  3499. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3500. const parsed = JSON.parse(jsonStr);
  3501. if (!Array.isArray(parsed)) throw new Error();
  3502. roadmap = parsed
  3503. .filter((p) => p && typeof p.topic === 'string' && typeof p.headline === 'string')
  3504. .slice(0, 5)
  3505. .map((p) => ({
  3506. topic: p.topic.trim(),
  3507. headline: p.headline.trim(),
  3508. keywords: Array.isArray(p.keywords) ? p.keywords.filter((k) => typeof k === 'string').slice(0, 3) : [],
  3509. rationale: typeof p.rationale === 'string' ? p.rationale.trim() : '',
  3510. }));
  3511. } catch {
  3512. roadmap = [];
  3513. }
  3514. if (!roadmap.length) return reply.code(503).send({ error: 'AI returned invalid roadmap format — try again' });
  3515. await db.collection('competitors').updateOne(
  3516. { _id: oid, workspaceId: ws },
  3517. { $set: { contentRoadmap: roadmap, updatedAt: new Date() } },
  3518. );
  3519. return { success: true, contentRoadmap: roadmap };
  3520. } catch (err) {
  3521. return reply.code(503).send({ error: 'Roadmap generation failed', detail: err.message });
  3522. }
  3523. });
  3524. // ─── Quantitative Competitor Extraction ──────────────────────────────────────
  3525. app.post('/competitors/:id/extract-quantitative', async (request, reply) => {
  3526. const ws = request.workspaceId;
  3527. const db = await getDb();
  3528. let oid;
  3529. try { oid = new ObjectId(request.params.id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  3530. const competitor = await db.collection('competitors').findOne({ _id: oid, workspaceId: ws });
  3531. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3532. if (!competitor.websiteUrl) return reply.code(400).send({ error: 'Competitor has no website URL' });
  3533. const baseUrl = competitor.websiteUrl.replace(/\/$/, '');
  3534. // Fetch additional sub-pages: /pricing, /features, /about, /careers
  3535. const subPaths = ['/pricing', '/features', '/about', '/careers'];
  3536. const pageTexts = await Promise.all([
  3537. extractTextFromUrl(baseUrl),
  3538. ...subPaths.map((p) => extractTextFromUrl(baseUrl + p)),
  3539. ]);
  3540. const combinedText = pageTexts.filter(Boolean).join('\n\n---\n\n').slice(0, 8000);
  3541. if (!combinedText.trim()) {
  3542. return reply.code(503).send({ error: 'Could not fetch any content from the competitor site' });
  3543. }
  3544. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no markdown or explanation.';
  3545. const prompt = `Extract quantitative competitive data from this competitor's website content.
  3546. Competitor: ${competitor.name} (${baseUrl})
  3547. Website content:
  3548. ${combinedText}
  3549. Return this JSON:
  3550. {
  3551. "pricingTiers": [{ "name": "<tier name>", "price": "<price or 'Free' or 'Contact us'>", "highlights": ["<feature>"] }],
  3552. "keyFeatures": ["<feature 1>", "<feature 2>", "<feature 3>", "<feature 4>", "<feature 5>"],
  3553. "techStack": ["<detected technology>"],
  3554. "targetCustomer": "<one-sentence ICP>",
  3555. "jobPostings": <number of open roles detected, 0 if none>,
  3556. "growthSignals": ["<any hiring, funding, expansion, or new product signals>"],
  3557. "productCount": <estimated number of distinct products/services, 0 if unclear>
  3558. }
  3559. If data is not available for a field, use null for numbers and [] for arrays. Return ONLY valid JSON.`;
  3560. try {
  3561. const pconf = await getActiveProviderConfig(request.workspaceId);
  3562. const model = pconf.model;
  3563. let text = '';
  3564. if (pconf.provider === 'ollama') {
  3565. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3566. text = res.data.response;
  3567. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3568. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3569. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3570. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3571. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3572. text = res.data.choices[0]?.message?.content || '';
  3573. } else if (pconf.provider === 'gemini') {
  3574. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3575. const res = await axios.post(
  3576. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3577. { contents: buildGeminiContents(prompt, system) },
  3578. { timeout: 120000 },
  3579. );
  3580. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3581. } else {
  3582. return reply.code(400).send({ error: 'AI not configured' });
  3583. }
  3584. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  3585. let profile = null;
  3586. try {
  3587. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3588. profile = JSON.parse(jsonStr);
  3589. if (!profile.keyFeatures) throw new Error('Missing keyFeatures');
  3590. } catch {
  3591. return reply.code(503).send({ error: 'AI returned invalid extraction format — try again' });
  3592. }
  3593. await db.collection('competitors').updateOne(
  3594. { _id: oid, workspaceId: ws },
  3595. { $set: { quantitativeProfile: profile, quantitativeExtractedAt: new Date(), updatedAt: new Date() } },
  3596. );
  3597. log.info({ action: 'extract_quantitative', competitor: competitor.name, outcome: 'success' });
  3598. return { success: true, quantitativeProfile: profile, extractedAt: new Date() };
  3599. } catch (err) {
  3600. return reply.code(503).send({ error: 'Quantitative extraction failed', detail: err.message });
  3601. }
  3602. });
  3603. // ─── Strategic Group Map ─────────────────────────────────────────────────────
  3604. const STRATEGIC_DIMENSIONS = [
  3605. 'Price level',
  3606. 'Product / service breadth',
  3607. 'Brand strength',
  3608. 'Technology leadership',
  3609. 'Market coverage',
  3610. 'Service quality',
  3611. 'Marketing intensity',
  3612. 'Geographic reach',
  3613. ];
  3614. app.post('/competitors/strategic-map', async (request, reply) => {
  3615. const ws = request.workspaceId;
  3616. const { xAxis, yAxis, accountKey } = request.body || {};
  3617. if (!xAxis || !yAxis) return reply.code(400).send({ error: 'xAxis and yAxis are required' });
  3618. if (xAxis === yAxis) return reply.code(400).send({ error: 'xAxis and yAxis must be different dimensions' });
  3619. const db = await getDb();
  3620. const competitors = await db.collection('competitors')
  3621. .find({ workspaceId: ws, aiAnalysis: { $exists: true } })
  3622. .toArray();
  3623. if (competitors.length < 1) {
  3624. return reply.code(400).send({ error: 'Run "Summarise with AI" on at least one competitor first.' });
  3625. }
  3626. const profile = accountKey
  3627. ? await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws })
  3628. : await db.collection('account_profiles').findOne({ workspaceId: ws });
  3629. const competitorBlocks = competitors.map((c) => {
  3630. const a = c.aiAnalysis || {};
  3631. return `${c.name}: positioning="${a.positioning || 'unknown'}", tone="${a.tone || 'unknown'}", themes=[${(a.themes || []).join(', ')}]`;
  3632. }).join('\n');
  3633. const yourBrand = profile
  3634. ? `Your brand: "${profile.businessName || 'Your brand'}" — ${profile.description || ''} — ${profile.toneOfVoice || ''}`
  3635. : 'Your brand: unknown';
  3636. const system = 'You are a Porter strategy analyst. Return only valid JSON with no markdown or explanation.';
  3637. const prompt = `Plot these players on a strategic group map using two dimensions: X = "${xAxis}", Y = "${yAxis}".
  3638. ${yourBrand}
  3639. ${competitorBlocks}
  3640. Assign each player a score 1–10 on each axis. 1 = lowest/weakest on that dimension, 10 = highest/strongest.
  3641. Return:
  3642. {
  3643. "players": [
  3644. { "name": "<name>", "x": <1-10>, "y": <1-10>, "isYou": <true if your brand, false otherwise>, "note": "<one phrase describing their position>" }
  3645. ],
  3646. "clusters": ["<describe a cluster group if 2+ players are close together>"],
  3647. "whitespace": ["<opportunity in a part of the map with no players>", "<second opportunity>"],
  3648. "insight": "<2-sentence strategic insight from the map>"
  3649. }
  3650. Include your brand as a player with isYou: true. Return ONLY valid JSON.`;
  3651. try {
  3652. const pconf = await getActiveProviderConfig(request.workspaceId);
  3653. const model = pconf.model;
  3654. let text = '';
  3655. if (pconf.provider === 'ollama') {
  3656. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  3657. text = res.data.response;
  3658. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3659. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3660. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3661. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3662. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  3663. text = res.data.choices[0]?.message?.content || '';
  3664. } else if (pconf.provider === 'gemini') {
  3665. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3666. const res = await axios.post(
  3667. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3668. { contents: buildGeminiContents(prompt, system) },
  3669. { timeout: 90000 },
  3670. );
  3671. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3672. } else {
  3673. return reply.code(400).send({ error: 'AI not configured' });
  3674. }
  3675. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  3676. let result = null;
  3677. try {
  3678. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3679. result = JSON.parse(jsonStr);
  3680. if (!Array.isArray(result.players)) throw new Error('Missing players array');
  3681. } catch {
  3682. return reply.code(503).send({ error: 'AI returned invalid strategic map format — try again' });
  3683. }
  3684. log.info({ action: 'strategic_map', xAxis, yAxis, players: result.players.length, outcome: 'success' });
  3685. return { success: true, xAxis, yAxis, ...result, generatedAt: new Date() };
  3686. } catch (err) {
  3687. return reply.code(503).send({ error: 'Strategic map failed', detail: err.message });
  3688. }
  3689. });
  3690. // ─── Competitor Social Matrix ────────────────────────────────────────────────
  3691. app.post('/competitors/social-matrix', async (request, reply) => {
  3692. const ws = request.workspaceId;
  3693. const db = await getDb();
  3694. const competitors = await db.collection('competitors')
  3695. .find({ workspaceId: ws, aiAnalysis: { $exists: true } })
  3696. .toArray();
  3697. if (competitors.length < 2) {
  3698. return reply.code(400).send({ error: 'Run "Summarise with AI" on at least 2 competitors first.' });
  3699. }
  3700. const competitorBlocks = competitors.map((c) => {
  3701. const a = c.aiAnalysis || {};
  3702. return [
  3703. `Competitor: ${c.name}`,
  3704. ` Positioning: ${a.positioning || 'unknown'}`,
  3705. ` Tone: ${a.tone || 'unknown'}`,
  3706. ` Themes: ${(a.themes || []).join(', ') || 'none'}`,
  3707. ` Weaknesses/Gaps: ${(a.gaps || []).join(', ') || 'none'}`,
  3708. ` Top keywords: ${(c.keywords || []).slice(0, 5).map((k) => k.term).join(', ') || 'none'}`,
  3709. ].join('\n');
  3710. }).join('\n\n');
  3711. const system = 'You are a competitive intelligence analyst. Write in plain text, no markdown or bullet points.';
  3712. const prompt = `Here are ${competitors.length} competitors you are analysing:
  3713. ${competitorBlocks}
  3714. Write a concise competitive landscape synthesis (3–4 sentences) that:
  3715. 1. Identifies the dominant positioning gap none of them own (the white space).
  3716. 2. Names the competitor with the weakest differentiation.
  3717. 3. States the single highest-leverage content angle for someone competing against all of them.
  3718. Write as direct, specific analysis. No fluff.`;
  3719. try {
  3720. const pconf = await getActiveProviderConfig(request.workspaceId);
  3721. const model = pconf.model;
  3722. let text = '';
  3723. if (pconf.provider === 'ollama') {
  3724. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  3725. text = res.data.response;
  3726. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3727. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3728. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3729. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3730. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  3731. text = res.data.choices[0]?.message?.content || '';
  3732. } else if (pconf.provider === 'gemini') {
  3733. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3734. const res = await axios.post(
  3735. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3736. { contents: buildGeminiContents(prompt, system) },
  3737. { timeout: 90000 },
  3738. );
  3739. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3740. } else {
  3741. return reply.code(400).send({ error: 'AI not configured' });
  3742. }
  3743. if (!text.trim()) return reply.code(503).send({ error: 'AI returned empty response — try again' });
  3744. log.info({ action: 'competitor_matrix', count: competitors.length, outcome: 'success' });
  3745. return { success: true, synthesis: text.trim(), generatedAt: new Date() };
  3746. } catch (err) {
  3747. return reply.code(503).send({ error: 'Matrix synthesis failed', detail: err.message });
  3748. }
  3749. });
  3750. // ─── Porter's Five Forces Analysis ───────────────────────────────────────────
  3751. app.post('/ai/five-forces', async (request, reply) => {
  3752. const ws = request.workspaceId;
  3753. const { accountKey } = request.body || {};
  3754. if (!accountKey) return reply.code(400).send({ error: 'accountKey is required' });
  3755. const db = await getDb();
  3756. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  3757. if (!profile) return reply.code(404).send({ error: 'Account profile not found. Save a profile first.' });
  3758. if (!profile.industry && !profile.businessName) {
  3759. return reply.code(400).send({ error: 'Add at least a business name or industry to the profile first.' });
  3760. }
  3761. const profileBlock = [
  3762. profile.businessName ? `Business: ${profile.businessName}` : '',
  3763. profile.industry ? `Industry: ${profile.industry}` : '',
  3764. profile.description ? `Description: ${profile.description}` : '',
  3765. profile.targetAudience ? `Target audience: ${profile.targetAudience}` : '',
  3766. profile.keywords ? `Keywords / products: ${profile.keywords}` : '',
  3767. ].filter(Boolean).join('\n');
  3768. // Load competitor data for richer rivalry analysis
  3769. const competitors = await db.collection('competitors').find({ workspaceId: ws }, { projection: { name: 1, aiAnalysis: 1 } }).toArray();
  3770. const competitorBlock = competitors.length
  3771. ? `Known direct competitors: ${competitors.map((c) => c.name).join(', ')}.`
  3772. : '';
  3773. const system = 'You are a Porter strategy analyst. Return only valid JSON with no markdown or explanation.';
  3774. const prompt = `Analyse this business using Porter\'s Five Forces framework.
  3775. ${profileBlock}
  3776. ${competitorBlock}
  3777. Score each force 1–10 (1 = very weak/favourable, 10 = very strong/unfavourable) and return exactly:
  3778. {
  3779. "attractiveness": "<High|Moderate|Low> — one sentence on overall industry attractiveness",
  3780. "overallScore": <0–100, where 100 = maximally attractive>,
  3781. "governingForce": "<name of the single most impactful force>",
  3782. "forces": [
  3783. {
  3784. "name": "Competitive Rivalry",
  3785. "score": <1–10>,
  3786. "assessment": "<one sentence>",
  3787. "drivers": ["<driver 1>", "<driver 2>", "<driver 3>"]
  3788. },
  3789. {
  3790. "name": "Threat of New Entrants",
  3791. "score": <1–10>,
  3792. "assessment": "<one sentence>",
  3793. "drivers": ["<driver>", "<driver>", "<driver>"]
  3794. },
  3795. {
  3796. "name": "Threat of Substitutes",
  3797. "score": <1–10>,
  3798. "assessment": "<one sentence>",
  3799. "drivers": ["<driver>", "<driver>", "<driver>"]
  3800. },
  3801. {
  3802. "name": "Supplier Power",
  3803. "score": <1–10>,
  3804. "assessment": "<one sentence>",
  3805. "drivers": ["<driver>", "<driver>", "<driver>"]
  3806. },
  3807. {
  3808. "name": "Buyer Power",
  3809. "score": <1–10>,
  3810. "assessment": "<one sentence>",
  3811. "drivers": ["<driver>", "<driver>", "<driver>"]
  3812. }
  3813. ],
  3814. "positioning": ["<strategic recommendation 1>", "<strategic recommendation 2>", "<strategic recommendation 3>"]
  3815. }
  3816. Scoring: overallScore = 100 minus the average of all five force scores × 10. Return ONLY valid JSON.`;
  3817. try {
  3818. const pconf = await getActiveProviderConfig(request.workspaceId);
  3819. const model = pconf.model;
  3820. let text = '';
  3821. if (pconf.provider === 'ollama') {
  3822. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3823. text = res.data.response;
  3824. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3825. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3826. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3827. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3828. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3829. text = res.data.choices[0]?.message?.content || '';
  3830. } else if (pconf.provider === 'gemini') {
  3831. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3832. const res = await axios.post(
  3833. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3834. { contents: buildGeminiContents(prompt, system) },
  3835. { timeout: 120000 },
  3836. );
  3837. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3838. } else {
  3839. return reply.code(400).send({ error: 'AI not configured' });
  3840. }
  3841. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  3842. let result = null;
  3843. try {
  3844. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3845. result = JSON.parse(jsonStr);
  3846. if (!Array.isArray(result.forces) || result.forces.length !== 5) throw new Error('Missing forces array');
  3847. } catch {
  3848. return reply.code(503).send({ error: 'AI returned invalid Five Forces format — try again' });
  3849. }
  3850. await db.collection('account_profiles').updateOne(
  3851. { _id: accountKey, workspaceId: ws },
  3852. { $set: { industryAnalysis: result, industryAnalyzedAt: new Date(), updatedAt: new Date() } },
  3853. );
  3854. log.info({ action: 'five_forces', account: accountKey, governingForce: result.governingForce, outcome: 'success' });
  3855. return { success: true, ...result, analyzedAt: new Date() };
  3856. } catch (err) {
  3857. return reply.code(503).send({ error: 'Five Forces analysis failed', detail: err.message });
  3858. }
  3859. });
  3860. // ─── Industry Type Diagnosis ─────────────────────────────────────────────────
  3861. app.post('/ai/industry-diagnosis', async (request, reply) => {
  3862. const ws = request.workspaceId;
  3863. const { accountKey } = request.body || {};
  3864. if (!accountKey) return reply.code(400).send({ error: 'accountKey is required' });
  3865. const db = await getDb();
  3866. const profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  3867. if (!profile) return reply.code(404).send({ error: 'Account profile not found. Save the profile first.' });
  3868. const fields = [profile.businessName, profile.description, profile.industry, profile.toneOfVoice].filter(Boolean);
  3869. if (fields.length < 2) return reply.code(400).send({ error: 'Fill in at least a business name and description before running diagnosis.' });
  3870. const profileBlock = [
  3871. profile.businessName ? `Business name: ${profile.businessName}` : '',
  3872. profile.description ? `Description: ${profile.description}` : '',
  3873. profile.industry ? `Self-reported industry: ${profile.industry}` : '',
  3874. profile.targetAudience ? `Target audience: ${profile.targetAudience}` : '',
  3875. profile.toneOfVoice ? `Brand tone: ${profile.toneOfVoice}` : '',
  3876. profile.keywords ? `Keywords: ${profile.keywords}` : '',
  3877. profile.postingGuidelines ? `Posting guidelines: ${profile.postingGuidelines}` : '',
  3878. ].filter(Boolean).join('\n');
  3879. const system = 'You are a social media strategy expert. Return only valid JSON with no markdown or explanation.';
  3880. const prompt = `Diagnose this brand's industry archetype based on the profile below and return strategic recommendations.
  3881. ${profileBlock}
  3882. Industry archetypes to choose from (pick the closest fit):
  3883. B2B SaaS, B2B Services, E-commerce (Product), Retail / Local Business, Hospitality / Food & Beverage,
  3884. Personal Brand / Creator, Health & Wellness, Finance / Fintech, Education / EdTech, Non-profit,
  3885. Media / Entertainment, Real Estate, Professional Services (Law / Consulting / Accounting).
  3886. Return this exact JSON:
  3887. {
  3888. "diagnosedType": "<archetype name>",
  3889. "confidence": <0-100>,
  3890. "summary": "<2-sentence explanation of why this archetype fits>",
  3891. "characteristics": ["<trait 1>", "<trait 2>", "<trait 3>"],
  3892. "tactics": [
  3893. { "title": "<tactic name>", "rationale": "<why it works for this archetype>", "action": "<specific concrete action>" },
  3894. { "title": "<tactic name>", "rationale": "<why it works>", "action": "<specific action>" },
  3895. { "title": "<tactic name>", "rationale": "<why it works>", "action": "<specific action>" }
  3896. ],
  3897. "contentMix": { "educational": <pct>, "social_proof": <pct>, "promotional": <pct>, "engagement": <pct> }
  3898. }
  3899. The contentMix percentages must sum to 100.
  3900. Return ONLY valid JSON.`;
  3901. try {
  3902. const pconf = await getActiveProviderConfig(request.workspaceId);
  3903. const model = pconf.model;
  3904. let text = '';
  3905. if (pconf.provider === 'ollama') {
  3906. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  3907. text = res.data.response;
  3908. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  3909. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  3910. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  3911. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  3912. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  3913. text = res.data.choices[0]?.message?.content || '';
  3914. } else if (pconf.provider === 'gemini') {
  3915. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  3916. const res = await axios.post(
  3917. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  3918. { contents: buildGeminiContents(prompt, system) },
  3919. { timeout: 120000 },
  3920. );
  3921. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  3922. } else {
  3923. return reply.code(400).send({ error: 'AI not configured' });
  3924. }
  3925. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  3926. let result = null;
  3927. try {
  3928. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  3929. result = JSON.parse(jsonStr);
  3930. if (!result.diagnosedType) throw new Error();
  3931. } catch {
  3932. return reply.code(503).send({ error: 'AI returned invalid diagnosis format — try again' });
  3933. }
  3934. // Persist the diagnosis on the account profile for future use
  3935. await db.collection('account_profiles').updateOne(
  3936. { _id: accountKey, workspaceId: ws },
  3937. { $set: { industryDiagnosis: result, industryDiagnosedAt: new Date(), updatedAt: new Date() } },
  3938. );
  3939. log.info({ action: 'industry_diagnosis', account: accountKey, diagnosedType: result.diagnosedType, outcome: 'success' });
  3940. return { success: true, ...result, diagnosedAt: new Date() };
  3941. } catch (err) {
  3942. return reply.code(503).send({ error: 'Industry diagnosis failed', detail: err.message });
  3943. }
  3944. });
  3945. // ─── Social Channel Audit ────────────────────────────────────────────────────
  3946. app.post('/ai/channel-audit', async (request, reply) => {
  3947. const ws = request.workspaceId;
  3948. const { accountKey } = request.body || {};
  3949. const db = await getDb();
  3950. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  3951. // Load profile (optional — enriches completeness & bio quality sections)
  3952. let profile = null;
  3953. if (accountKey) {
  3954. profile = await db.collection('account_profiles').findOne({ _id: accountKey, workspaceId: ws });
  3955. }
  3956. // Load recent posts, optionally filtered by account
  3957. const postFilter = accountKey
  3958. ? { workspaceId: ws, publishedAt: { $gte: thirtyDaysAgo }, 'destinations.key': accountKey }
  3959. : { workspaceId: ws, publishedAt: { $gte: thirtyDaysAgo } };
  3960. const recentPosts = await db.collection('posts')
  3961. .find(postFilter, { projection: { content: 1, destinations: 1, publishedAt: 1, status: 1 } })
  3962. .toArray();
  3963. if (recentPosts.length < 2) {
  3964. return reply.code(400).send({ error: 'Not enough publishing history. Publish at least 2 posts first.' });
  3965. }
  3966. // ── Local stats computation ──────────────────────────────────────────────
  3967. const totalPosts = recentPosts.length;
  3968. // Format diversity: posts with imageUrl/videoUrl in any destination
  3969. const postsWithMedia = recentPosts.filter((p) =>
  3970. (p.destinations || []).some((d) => d.imageUrl || d.videoUrl),
  3971. ).length;
  3972. const mediaRatio = Math.round((postsWithMedia / totalPosts) * 100);
  3973. // CTA detection
  3974. const ctaWords = ['click', 'link in bio', 'shop', 'buy', 'register', 'sign up', 'subscribe', 'follow', 'comment', 'share', 'tag', 'dm'];
  3975. const postsWithCta = recentPosts.filter((p) =>
  3976. ctaWords.some((w) => (p.content || '').toLowerCase().includes(w)),
  3977. ).length;
  3978. const ctaRatio = Math.round((postsWithCta / totalPosts) * 100);
  3979. // Hashtag stats
  3980. const hashtagCounts = recentPosts.map((p) => ((p.content || '').match(/#\w+/g) || []).length);
  3981. const avgHashtags = Math.round((hashtagCounts.reduce((s, c) => s + c, 0) / totalPosts) * 10) / 10;
  3982. // Caption length
  3983. const avgCaptionLength = Math.round(recentPosts.reduce((s, p) => s + (p.content || '').length, 0) / totalPosts);
  3984. // Posting consistency: days between posts
  3985. const dates = recentPosts.map((p) => new Date(p.publishedAt).getTime()).sort((a, b) => a - b);
  3986. const gaps = dates.slice(1).map((d, i) => (d - dates[i]) / (1000 * 60 * 60 * 24));
  3987. const avgGap = gaps.length > 0 ? Math.round(gaps.reduce((s, g) => s + g, 0) / gaps.length * 10) / 10 : 30;
  3988. const maxGap = gaps.length > 0 ? Math.round(Math.max(...gaps) * 10) / 10 : 30;
  3989. // Engagement from post_metrics
  3990. const metricsFilter = accountKey
  3991. ? { workspaceId: ws, accountKey }
  3992. : { workspaceId: ws };
  3993. const metrics = await db.collection('post_metrics')
  3994. .find({ ...metricsFilter, createdAt: { $gte: thirtyDaysAgo } })
  3995. .toArray();
  3996. const avgEngagement = metrics.length > 0
  3997. ? Math.round((metrics.reduce((s, m) => s + (m.metrics?.engagementTotal || 0), 0) / metrics.length) * 10) / 10
  3998. : null;
  3999. // Profile completeness score (0-100)
  4000. let profileScore = 0;
  4001. let profileNote = 'No profile configured for this account.';
  4002. if (profile) {
  4003. const fields = [profile.businessName, profile.description, profile.industry, profile.toneOfVoice, profile.targetAudience, profile.keywords, profile.websiteUrl];
  4004. const filled = fields.filter((f) => f && (Array.isArray(f) ? f.length > 0 : String(f).trim().length > 0)).length;
  4005. profileScore = Math.round((filled / fields.length) * 100);
  4006. profileNote = `${filled}/${fields.length} profile fields completed. Business name: ${profile.businessName || 'missing'}, industry: ${profile.industry || 'missing'}.`;
  4007. }
  4008. const statsBlock = [
  4009. `Total posts (last 30 days): ${totalPosts}`,
  4010. `Posts with media (images/video): ${mediaRatio}%`,
  4011. `Posts with a CTA (click, shop, follow, etc.): ${ctaRatio}%`,
  4012. `Average hashtags per post: ${avgHashtags}`,
  4013. `Average caption length: ${avgCaptionLength} characters`,
  4014. `Average days between posts: ${avgGap} (max gap: ${maxGap} days)`,
  4015. `Average engagement per post: ${avgEngagement !== null ? avgEngagement : 'no data'}`,
  4016. `Account profile completeness: ${profileScore}% — ${profileNote}`,
  4017. profile?.description ? `Bio/description: "${profile.description.slice(0, 200)}"` : 'No bio/description set.',
  4018. profile?.toneOfVoice ? `Brand tone: ${profile.toneOfVoice}` : '',
  4019. ].filter(Boolean).join('\n');
  4020. const system = 'You are a professional social media channel auditor. Return only valid JSON with no markdown or explanation.';
  4021. const prompt = `Audit this social media channel and return a quality score report.
  4022. ${statsBlock}
  4023. Score each dimension 0-10 and return this exact JSON:
  4024. {
  4025. "score": <overall 0-100>,
  4026. "sections": [
  4027. { "name": "Profile Completeness", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4028. { "name": "Posting Consistency", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4029. { "name": "Visual Content", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4030. { "name": "CTA Usage", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4031. { "name": "Hashtag Strategy", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] },
  4032. { "name": "Engagement Quality", "score": <0-10>, "assessment": "<one sentence>", "recommendations": ["<action>", "<action>"] }
  4033. ],
  4034. "topActions": ["<highest-impact action 1>", "<highest-impact action 2>", "<highest-impact action 3>"]
  4035. }
  4036. Scoring benchmarks:
  4037. - Profile Completeness: 100% filled = 10, 70%+ = 7, 50%+ = 5, below = 2
  4038. - Posting Consistency: daily = 10, every 2-3 days = 7, weekly = 5, less = 2; long gaps hurt the score
  4039. - Visual Content: 80%+ posts with media = 10, 50%+ = 7, 25%+ = 4, 0% = 1
  4040. - CTA Usage: 60%+ posts with CTA = 10, 40%+ = 7, 20%+ = 4, none = 2
  4041. - Hashtag Strategy: 3-10 hashtags avg = 10, 1-2 or 11-20 = 7, 0 or 21+ = 3
  4042. - Engagement Quality: avg engagement >5 = 10, 3-5 = 7, 1-3 = 5, <1 = 2, no data = 5 (neutral)
  4043. Return ONLY valid JSON.`;
  4044. try {
  4045. const pconf = await getActiveProviderConfig(request.workspaceId);
  4046. const model = pconf.model;
  4047. let text = '';
  4048. if (pconf.provider === 'ollama') {
  4049. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  4050. text = res.data.response;
  4051. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  4052. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  4053. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  4054. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  4055. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  4056. text = res.data.choices[0]?.message?.content || '';
  4057. } else if (pconf.provider === 'gemini') {
  4058. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  4059. const res = await axios.post(
  4060. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  4061. { contents: buildGeminiContents(prompt, system) },
  4062. { timeout: 120000 },
  4063. );
  4064. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  4065. } else {
  4066. return reply.code(400).send({ error: 'AI not configured' });
  4067. }
  4068. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  4069. let result = null;
  4070. try {
  4071. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  4072. result = JSON.parse(jsonStr);
  4073. if (!Array.isArray(result.sections)) throw new Error();
  4074. } catch {
  4075. return reply.code(503).send({ error: 'AI returned invalid channel audit format — try again' });
  4076. }
  4077. log.info({ action: 'channel_audit', account: accountKey || 'all', outcome: 'success' });
  4078. return { success: true, ...result, generatedAt: new Date() };
  4079. } catch (err) {
  4080. return reply.code(503).send({ error: 'Channel audit failed', detail: err.message });
  4081. }
  4082. });
  4083. module.exports = app;