server.js 207 KB

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