server.js 208 KB

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