server.js 191 KB

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