server.js 215 KB

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