server.js 150 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532
  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. app.post('/ai/generate', async (request, reply) => {
  727. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext, destinations } = request.body || {};
  728. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  729. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  730. const platformRules = buildPlatformRulesBlock(destinations);
  731. const system = rawSystem ? rawSystem + competitorSuffix + platformRules : ((competitorSuffix + platformRules) || undefined);
  732. const pconf = await getActiveProviderConfig();
  733. const model = reqModel || pconf.model;
  734. try {
  735. if (pconf.provider === 'ollama') {
  736. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  737. return { text: res.data.response, model, done: res.data.done };
  738. }
  739. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  740. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  741. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  742. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  743. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  744. return { text: res.data.choices[0]?.message?.content || '', model, done: true };
  745. }
  746. if (pconf.provider === 'gemini') {
  747. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  748. const res = await axios.post(
  749. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  750. { contents: buildGeminiContents(prompt, system) },
  751. { timeout: 90000 },
  752. );
  753. return { text: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model, done: true };
  754. }
  755. return reply.code(400).send({ error: `Unknown provider: ${pconf.provider}` });
  756. } catch (err) {
  757. const status = err.response?.status || 503;
  758. return reply.code(status).send({ error: 'AI generation failed', detail: err.message });
  759. }
  760. });
  761. 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.';
  762. // Vision caption — supports ollama, openai, gemini (groq has no vision)
  763. app.post('/ai/caption', async (request, reply) => {
  764. const { imageUrl, model: reqModel } = request.body || {};
  765. if (!imageUrl) return reply.code(400).send({ error: 'imageUrl is required' });
  766. const pconf = await getActiveProviderConfig();
  767. let imageBase64, imageMime;
  768. try {
  769. let imageBuffer;
  770. if (imageUrl.startsWith('/media/')) {
  771. const filename = path.basename(imageUrl);
  772. imageBuffer = fs.readFileSync(path.join(UPLOAD_DIR, filename));
  773. } else {
  774. const imgRes = await axios.get(imageUrl, { responseType: 'arraybuffer', timeout: 15000 });
  775. imageBuffer = Buffer.from(imgRes.data);
  776. imageMime = imgRes.headers['content-type'] || 'image/jpeg';
  777. }
  778. imageBase64 = imageBuffer.toString('base64');
  779. if (!imageMime) imageMime = 'image/jpeg';
  780. } catch (err) {
  781. return reply.code(400).send({ error: 'Could not load image', detail: err.message });
  782. }
  783. try {
  784. const model = reqModel || pconf.visionModel || pconf.model;
  785. if (pconf.provider === 'ollama') {
  786. const res = await axios.post(`${pconf.endpoint}/api/generate`, {
  787. model, prompt: CAPTION_PROMPT, images: [imageBase64], stream: false,
  788. }, { timeout: 90000 });
  789. return { caption: res.data.response, model };
  790. }
  791. if (pconf.provider === 'openai') {
  792. if (!pconf.apiKey) return reply.code(503).send({ error: 'OpenAI API key not configured' });
  793. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  794. model: model || 'gpt-4o',
  795. messages: [{ role: 'user', content: [
  796. { type: 'text', text: CAPTION_PROMPT },
  797. { type: 'image_url', image_url: { url: `data:${imageMime};base64,${imageBase64}` } },
  798. ]}],
  799. stream: false,
  800. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  801. return { caption: res.data.choices[0]?.message?.content || '', model };
  802. }
  803. if (pconf.provider === 'gemini') {
  804. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  805. const geminiModel = model || 'gemini-1.5-flash';
  806. const res = await axios.post(
  807. `https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent?key=${pconf.apiKey}`,
  808. { contents: [{ role: 'user', parts: [
  809. { text: CAPTION_PROMPT },
  810. { inlineData: { mimeType: imageMime, data: imageBase64 } },
  811. ]}]},
  812. { timeout: 90000 },
  813. );
  814. return { caption: res.data.candidates?.[0]?.content?.parts?.[0]?.text || '', model: geminiModel };
  815. }
  816. return reply.code(400).send({ error: `Provider ${pconf.provider} does not support vision captions` });
  817. } catch (err) {
  818. const status = err.response?.status || 503;
  819. return reply.code(status).send({ error: 'Caption generation failed', detail: err.message });
  820. }
  821. });
  822. // SSE streaming endpoint — normalized data: { token, done } format for all providers
  823. app.post('/ai/stream', async (request, reply) => {
  824. const { prompt, system: rawSystem, model: reqModel, useCompetitorContext, destinations } = request.body || {};
  825. if (!prompt?.trim()) return reply.code(400).send({ error: 'prompt is required' });
  826. const competitorSuffix = useCompetitorContext ? await buildCompetitorSystemSuffix() : '';
  827. const platformRules = buildPlatformRulesBlock(destinations);
  828. const system = rawSystem ? rawSystem + competitorSuffix + platformRules : ((competitorSuffix + platformRules) || undefined);
  829. const pconf = await getActiveProviderConfig();
  830. const model = reqModel || pconf.model;
  831. reply.raw.setHeader('Content-Type', 'text/event-stream');
  832. reply.raw.setHeader('Cache-Control', 'no-cache');
  833. reply.raw.setHeader('X-Accel-Buffering', 'no');
  834. reply.raw.setHeader('Connection', 'keep-alive');
  835. reply.raw.flushHeaders();
  836. const writeToken = (token, done = false) => reply.raw.write(`data: ${JSON.stringify({ token, done })}\n\n`);
  837. const writeError = (msg) => { reply.raw.write(`data: ${JSON.stringify({ error: msg, done: true })}\n\n`); reply.raw.end(); };
  838. try {
  839. if (pconf.provider === 'ollama') {
  840. const ollamaRes = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: true }, { responseType: 'stream', timeout: 120000 });
  841. ollamaRes.data.on('data', (chunk) => {
  842. try {
  843. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  844. const data = JSON.parse(line);
  845. writeToken(data.response || '', !!data.done);
  846. }
  847. } catch (_) {}
  848. });
  849. ollamaRes.data.on('end', () => reply.raw.end());
  850. ollamaRes.data.on('error', (err) => writeError(err.message));
  851. return;
  852. }
  853. if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  854. if (!pconf.apiKey) return writeError(`${pconf.provider} API key not configured`);
  855. const upstreamRes = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  856. model, messages: buildOpenAIMessages(prompt, system), stream: true,
  857. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, responseType: 'stream', timeout: 120000 });
  858. upstreamRes.data.on('data', (chunk) => {
  859. try {
  860. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  861. if (!line.startsWith('data: ')) continue;
  862. const payload = line.slice(6).trim();
  863. if (payload === '[DONE]') { writeToken('', true); return; }
  864. const data = JSON.parse(payload);
  865. const token = data.choices?.[0]?.delta?.content || '';
  866. if (token) writeToken(token);
  867. }
  868. } catch (_) {}
  869. });
  870. upstreamRes.data.on('end', () => reply.raw.end());
  871. upstreamRes.data.on('error', (err) => writeError(err.message));
  872. return;
  873. }
  874. if (pconf.provider === 'gemini') {
  875. if (!pconf.apiKey) return writeError('Gemini API key not configured');
  876. const geminiRes = await axios.post(
  877. `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${pconf.apiKey}`,
  878. { contents: buildGeminiContents(prompt, system) },
  879. { responseType: 'stream', timeout: 120000 },
  880. );
  881. geminiRes.data.on('data', (chunk) => {
  882. try {
  883. for (const line of chunk.toString().split('\n').filter(Boolean)) {
  884. if (!line.startsWith('data: ')) continue;
  885. const data = JSON.parse(line.slice(6));
  886. const token = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  887. if (token) writeToken(token);
  888. }
  889. } catch (_) {}
  890. });
  891. geminiRes.data.on('end', () => { writeToken('', true); reply.raw.end(); });
  892. geminiRes.data.on('error', (err) => writeError(err.message));
  893. return;
  894. }
  895. writeError(`Unknown provider: ${pconf.provider}`);
  896. } catch (err) {
  897. writeError(err.message);
  898. }
  899. });
  900. // ─── Monthly Content Calendar ─────────────────────────────────────────────────
  901. // POST /ai/content-calendar — generate a monthly content plan with narrative brief + sample posts
  902. // Body: { accountKey?, platforms[], month? (YYYY-MM) }
  903. app.post('/ai/content-calendar', async (request, reply) => {
  904. const { accountKey, platforms = [], month } = request.body || {};
  905. if (!platforms.length) return reply.code(400).send({ error: 'Select at least one platform' });
  906. const db = await getDb();
  907. const calMonth = month || new Date().toISOString().slice(0, 7);
  908. const [year, mon] = calMonth.split('-');
  909. const monthName = new Date(`${calMonth}-01`).toLocaleString('en', { month: 'long', year: 'numeric' });
  910. // Load account profile for context
  911. const profileKey = accountKey || null;
  912. const profile = profileKey
  913. ? await db.collection('account_profiles').findOne({ _id: profileKey })
  914. : await db.collection('account_profiles').findOne({});
  915. const contextParts = ['You are a social media content strategist.'];
  916. if (profile) {
  917. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  918. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  919. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  920. if (profile.toneOfVoice) contextParts.push(`Tone of voice: ${profile.toneOfVoice}`);
  921. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  922. if (profile.keywords) contextParts.push(`Keywords: ${profile.keywords}`);
  923. }
  924. const brandContext = contextParts.join('\n');
  925. const activePlatforms = platforms.slice(0, 5);
  926. const platformList = activePlatforms.join(', ');
  927. const postsPerPlatform = 2;
  928. const totalPosts = activePlatforms.length * postsPerPlatform;
  929. const system = 'You are a social media content strategist. Return ONLY a valid JSON object — no markdown, no explanation, no code fences.';
  930. const platformNoteKeys = activePlatforms.map((p) => `"${p}"`).join(', ');
  931. const postSchema = `{ "platform": "<one of: ${platformList}>", "week": <1 or 2>, "content": "<ready-to-publish post>", "hashtags": ["<tag>"], "postType": "<educational|promotional|engagement|storytelling>", "suggestedDay": "<day>" }`;
  932. const prompt = `${brandContext}
  933. Create a ${monthName} content calendar for: ${platformList}.
  934. Generate ${postsPerPlatform} posts per platform (${totalPosts} posts total across weeks 1 and 2).
  935. Platform conventions to follow:
  936. - LinkedIn: professional hook in first line, insights, 1300-char max
  937. - Instagram: visual-first, emojis ok, 2200-char max, 5-10 hashtags
  938. - Facebook: conversational, question or story, 500-char ideal
  939. - Twitter: concise, punchy, under 280 chars
  940. - TikTok: caption hook in first 3 words, trending angle
  941. - Pinterest: keyword-rich description, action-oriented
  942. - Mastodon/Bluesky: authentic, community-focused, 300/500 chars
  943. Return a single JSON object:
  944. {
  945. "brief": {
  946. "theme": "<one-sentence monthly narrative>",
  947. "pillars": ["<pillar 1>", "<pillar 2>", "<pillar 3>"],
  948. "toneGuidance": "<one sentence>",
  949. "platformNotes": { ${platformNoteKeys.split(', ').map((k) => `${k}: "<strategy>"`).join(', ')} }
  950. },
  951. "posts": [<${totalPosts} post objects using schema: ${postSchema}>]
  952. }
  953. Return ONLY the JSON object.`;
  954. try {
  955. const pconf = await getActiveProviderConfig();
  956. const model = pconf.model;
  957. let text = '';
  958. if (pconf.provider === 'ollama') {
  959. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  960. text = res.data.response;
  961. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  962. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  963. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  964. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  965. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  966. text = res.data.choices[0]?.message?.content || '';
  967. } else if (pconf.provider === 'gemini') {
  968. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  969. const res = await axios.post(
  970. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  971. { contents: buildGeminiContents(prompt, system) },
  972. { timeout: 180000 },
  973. );
  974. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  975. } else {
  976. return reply.code(400).send({ error: 'AI not configured' });
  977. }
  978. let calendar = null;
  979. try {
  980. // Strip markdown code fences if present
  981. const cleaned = text.replace(/```(?:json)?\s*/gi, '').replace(/```\s*/g, '');
  982. const jsonStr = (cleaned.match(/\{[\s\S]*\}/) || ['{}'])[0];
  983. calendar = JSON.parse(jsonStr);
  984. if (!calendar.brief || !Array.isArray(calendar.posts)) throw new Error('Missing brief or posts array');
  985. if (!Array.isArray(calendar.brief.pillars)) calendar.brief.pillars = [];
  986. if (typeof calendar.brief.theme !== 'string') calendar.brief.theme = '';
  987. calendar.posts = calendar.posts.filter((p) => p && typeof p.content === 'string').slice(0, totalPosts);
  988. if (calendar.posts.length === 0) throw new Error('No valid posts in response');
  989. } catch (parseErr) {
  990. log.warn({ action: 'content_calendar', outcome: 'parse_failure', err: parseErr.message });
  991. return reply.code(503).send({ error: 'AI returned invalid calendar format — try again or use a more capable model' });
  992. }
  993. const doc = {
  994. accountKey: accountKey || null,
  995. month: calMonth,
  996. monthName,
  997. platforms,
  998. brief: calendar.brief,
  999. posts: calendar.posts,
  1000. createdAt: new Date(),
  1001. };
  1002. const result = await db.collection('content_calendars').insertOne(doc);
  1003. log.info({ action: 'content_calendar', month: calMonth, platforms: platforms.join(','), posts: calendar.posts.length, outcome: 'success' });
  1004. return { success: true, calendarId: result.insertedId.toString(), ...doc };
  1005. } catch (err) {
  1006. log.error({ action: 'content_calendar', outcome: 'failure', err: err.message });
  1007. return reply.code(503).send({ error: `Calendar generation failed: ${err.message}` });
  1008. }
  1009. });
  1010. // GET /ai/content-calendar/:id — retrieve a saved calendar
  1011. app.get('/ai/content-calendar/:id', async (request, reply) => {
  1012. let oid;
  1013. try { oid = new ObjectId(request.params.id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  1014. const db = await getDb();
  1015. const cal = await db.collection('content_calendars').findOne({ _id: oid });
  1016. if (!cal) return reply.code(404).send({ error: 'Calendar not found' });
  1017. return { calendarId: cal._id.toString(), ...cal };
  1018. });
  1019. // GET /ai/content-calendars — list recent calendars
  1020. app.get('/ai/content-calendars', async (request, reply) => {
  1021. const db = await getDb();
  1022. const cals = await db.collection('content_calendars')
  1023. .find({}, { projection: { posts: 0 } })
  1024. .sort({ createdAt: -1 })
  1025. .limit(20)
  1026. .toArray();
  1027. return { calendars: cals.map((c) => ({ calendarId: c._id.toString(), month: c.month, monthName: c.monthName, platforms: c.platforms, brief: c.brief, createdAt: c.createdAt })) };
  1028. });
  1029. // ─── Bulk AI Draft Generation ─────────────────────────────────────────────────
  1030. // POST /ai/bulk-draft — kick off a batch; returns batchId immediately (non-blocking)
  1031. // Body: { topics: string[], destinations: Destination[], tone?: string, model?: string }
  1032. app.post('/ai/bulk-draft', async (request, reply) => {
  1033. const { topics, destinations = [], tone = '', model: reqModel } = request.body || {};
  1034. if (!Array.isArray(topics) || !topics.length) return reply.code(400).send({ error: 'topics array is required' });
  1035. const filteredTopics = topics.map((t) => (typeof t === 'string' ? t.trim() : '')).filter(Boolean);
  1036. if (!filteredTopics.length) return reply.code(400).send({ error: 'No valid topics provided' });
  1037. const db = await getDb();
  1038. const batchId = new ObjectId();
  1039. const now = new Date();
  1040. await db.collection('bulk_draft_batches').insertOne({
  1041. _id: batchId,
  1042. total: filteredTopics.length,
  1043. completed: 0,
  1044. failed: 0,
  1045. status: 'processing',
  1046. createdAt: now,
  1047. updatedAt: now,
  1048. });
  1049. const selectedDests = destinations.filter((d) => d.selected);
  1050. const toneClause = tone ? `Write in a ${tone} tone.` : '';
  1051. const platformRules = buildPlatformRulesBlock(selectedDests);
  1052. 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}`;
  1053. // Fire-and-forget — process topics sequentially in the background
  1054. (async () => {
  1055. const pconf = await getActiveProviderConfig();
  1056. const model = reqModel || pconf.model;
  1057. for (const topic of filteredTopics) {
  1058. try {
  1059. const prompt = `Write a social media post about: ${topic}`;
  1060. let content = '';
  1061. if (pconf.provider === 'ollama') {
  1062. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 90000 });
  1063. content = res.data.response || '';
  1064. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  1065. if (!pconf.apiKey) throw new Error(`${pconf.provider} API key not configured`);
  1066. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  1067. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  1068. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 90000 });
  1069. content = res.data.choices[0]?.message?.content || '';
  1070. } else if (pconf.provider === 'gemini') {
  1071. if (!pconf.apiKey) throw new Error('Gemini API key not configured');
  1072. const res = await axios.post(
  1073. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  1074. { contents: buildGeminiContents(prompt, system) },
  1075. { timeout: 90000 },
  1076. );
  1077. content = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  1078. }
  1079. if (content.trim()) {
  1080. const draftNow = new Date();
  1081. await db.collection('drafts').insertOne({
  1082. content: content.trim(),
  1083. mediaUrl: '',
  1084. scheduledAt: '',
  1085. destinations: selectedDests,
  1086. batchId: batchId.toString(),
  1087. topic,
  1088. createdAt: draftNow,
  1089. updatedAt: draftNow,
  1090. });
  1091. }
  1092. await db.collection('bulk_draft_batches').updateOne(
  1093. { _id: batchId },
  1094. { $inc: { completed: 1 }, $set: { updatedAt: new Date() } },
  1095. );
  1096. } catch (err) {
  1097. log.error({ action: 'bulk_draft_topic', topic, outcome: 'failure', err: err.message });
  1098. await db.collection('bulk_draft_batches').updateOne(
  1099. { _id: batchId },
  1100. { $inc: { failed: 1 }, $set: { updatedAt: new Date() } },
  1101. );
  1102. }
  1103. }
  1104. await db.collection('bulk_draft_batches').updateOne(
  1105. { _id: batchId },
  1106. { $set: { status: 'done', updatedAt: new Date() } },
  1107. );
  1108. log.info({ action: 'bulk_draft_batch', batchId: batchId.toString(), total: filteredTopics.length, outcome: 'success' });
  1109. })().catch((err) => {
  1110. log.error({ action: 'bulk_draft_batch', batchId: batchId.toString(), outcome: 'failure', err: err.message });
  1111. getDb().then((d) => d.collection('bulk_draft_batches').updateOne(
  1112. { _id: batchId },
  1113. { $set: { status: 'failed', updatedAt: new Date() } },
  1114. )).catch(() => {});
  1115. });
  1116. return reply.code(202).send({ batchId: batchId.toString() });
  1117. });
  1118. // GET /ai/bulk-draft/:batchId — poll batch progress
  1119. app.get('/ai/bulk-draft/:batchId', async (request, reply) => {
  1120. const { batchId } = request.params;
  1121. let oid;
  1122. try { oid = new ObjectId(batchId); } catch { return reply.code(400).send({ error: 'Invalid batchId' }); }
  1123. const db = await getDb();
  1124. const batch = await db.collection('bulk_draft_batches').findOne({ _id: oid });
  1125. if (!batch) return reply.code(404).send({ error: 'Batch not found' });
  1126. return {
  1127. batchId: batch._id.toString(),
  1128. total: batch.total,
  1129. completed: batch.completed,
  1130. failed: batch.failed,
  1131. status: batch.status,
  1132. processed: batch.completed + batch.failed,
  1133. };
  1134. });
  1135. // ─── Platform service URLs ────────────────────────────────────────────────────
  1136. const PLATFORM_SERVICES = {
  1137. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  1138. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  1139. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  1140. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  1141. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  1142. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  1143. };
  1144. // Direct multi-platform post endpoint.
  1145. // Body: { content: string, destinations: Array<{ platform, accountId?, imageUrl?, videoUrl?, link? }> }
  1146. app.post('/post', async (request, reply) => {
  1147. const { content, destinations = [], firstComment } = request.body || {};
  1148. if (!content?.trim()) return reply.code(400).send({ error: 'content is required' });
  1149. if (!destinations.length) return reply.code(400).send({ error: 'destinations must not be empty' });
  1150. const results = await Promise.allSettled(
  1151. destinations.map(async ({ platform, accountId, imageUrl, videoUrl, link }) => {
  1152. const serviceUrl = PLATFORM_SERVICES[platform];
  1153. if (!serviceUrl) throw new Error(`Unknown platform: ${platform}`);
  1154. const res = await axios.post(
  1155. `${serviceUrl}/post`,
  1156. { content, accountId, imageUrl, videoUrl, link, firstComment: firstComment?.trim() || undefined },
  1157. { timeout: 30000 }
  1158. );
  1159. return { platform, accountId, ...res.data };
  1160. })
  1161. );
  1162. const output = results.map((r, i) =>
  1163. r.status === 'fulfilled'
  1164. ? r.value
  1165. : { platform: destinations[i].platform, accountId: destinations[i].accountId, success: false, error: r.reason?.message }
  1166. );
  1167. const anyFailed = output.some((r) => !r.success);
  1168. const anySucceeded = output.some((r) => r.success);
  1169. const postStatus = anyFailed && anySucceeded ? 'partial' : anyFailed ? 'failed' : 'published';
  1170. // Record the post for analytics
  1171. try {
  1172. const db = await getDb();
  1173. await db.collection('posts').insertOne({
  1174. _id: crypto.randomUUID(),
  1175. type: 'immediate',
  1176. content,
  1177. ...(firstComment?.trim() && { firstComment: firstComment.trim() }),
  1178. destinations,
  1179. platformResults: Object.fromEntries(
  1180. output.map((r) => [
  1181. r.accountId ? `${r.platform}:${r.accountId}` : r.platform,
  1182. { success: r.success, ...(r.error && { error: r.error }) },
  1183. ])
  1184. ),
  1185. status: postStatus,
  1186. publishedAt: new Date(),
  1187. createdAt: new Date(),
  1188. });
  1189. } catch (err) {
  1190. app.log.warn({ action: 'post_record', outcome: 'failure', err: err.message });
  1191. }
  1192. return reply.code(anyFailed ? 207 : 200).send({ results: output });
  1193. });
  1194. // ─── Legacy post route ────────────────────────────────────────────────────────
  1195. let rabbitMQProducer = new RabbitMQProducer();
  1196. app.post('/', async (request, reply) => {
  1197. try {
  1198. await rabbitMQProducer.sendMessage('formatter', request.body.message);
  1199. reply.send({ status: 'ok' });
  1200. } catch (error) {
  1201. app.log.error({ action: 'legacy_post', outcome: 'failure', err: error.message });
  1202. reply.status(500).send({ error: 'Internal Server Error' });
  1203. }
  1204. });
  1205. // ─── Meta App Credentials ────────────────────────────────────────────────────
  1206. // Save Facebook App ID + Secret (entered by user in Settings UI)
  1207. app.post('/credentials/meta-app', async (request, reply) => {
  1208. const { appId, appSecret } = request.body || {};
  1209. if (!appId || !appSecret) {
  1210. return reply.code(400).send({ error: 'appId and appSecret are required' });
  1211. }
  1212. await setCredentials('meta_app', { appId, appSecret: encryptToken(appSecret) });
  1213. return { success: true };
  1214. });
  1215. // Get Meta App config (secret is masked for UI display)
  1216. app.get('/credentials/meta-app', async () => {
  1217. const cred = await getCredentials('meta_app');
  1218. if (!cred) return { configured: false };
  1219. const plainSecret = decryptToken(cred.appSecret) || '';
  1220. return { configured: true, appId: cred.appId, appSecretHint: plainSecret ? `****${plainSecret.slice(-4)}` : '****' };
  1221. });
  1222. // ─── Meta OAuth Flow ──────────────────────────────────────────────────────────
  1223. // Return the Facebook OAuth URL to redirect the user to
  1224. app.get('/auth/meta/init', async (request, reply) => {
  1225. const cred = await getCredentials('meta_app');
  1226. if (!cred?.appId) {
  1227. return reply.code(400).send({ error: 'Save your Facebook App ID and Secret first' });
  1228. }
  1229. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1230. const scopes = [
  1231. 'pages_manage_posts',
  1232. 'pages_read_engagement',
  1233. 'instagram_basic',
  1234. 'instagram_content_publish',
  1235. 'instagram_manage_insights',
  1236. ].join(',');
  1237. const url = `https://www.facebook.com/v22.0/dialog/oauth?client_id=${cred.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scopes}&response_type=code`;
  1238. return { url };
  1239. });
  1240. // OAuth callback — Facebook redirects here after user authorises
  1241. app.get('/auth/meta/callback', async (request, reply) => {
  1242. const { code, error: oauthError } = request.query;
  1243. if (oauthError) {
  1244. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(oauthError)}`);
  1245. }
  1246. if (!code) {
  1247. return reply.redirect(`${APP_BASE_URL}/settings?meta_error=no_code`);
  1248. }
  1249. try {
  1250. const appCred = await getCredentials('meta_app');
  1251. if (!appCred?.appId) throw new Error('App credentials not configured');
  1252. const appSecret = decryptToken(appCred.appSecret);
  1253. if (!appSecret) throw new Error('Failed to decrypt app secret');
  1254. const redirectUri = `${APP_BASE_URL}/api/auth/meta/callback`;
  1255. // Exchange code for short-lived token
  1256. const shortRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1257. params: {
  1258. client_id: appCred.appId,
  1259. client_secret: appSecret,
  1260. redirect_uri: redirectUri,
  1261. code,
  1262. },
  1263. });
  1264. // Upgrade to long-lived user token (~60 days)
  1265. const longRes = await axios.get(`${GRAPH_API}/oauth/access_token`, {
  1266. params: {
  1267. grant_type: 'fb_exchange_token',
  1268. client_id: appCred.appId,
  1269. client_secret: appSecret,
  1270. fb_exchange_token: shortRes.data.access_token,
  1271. },
  1272. });
  1273. const userToken = longRes.data.access_token;
  1274. // Fetch all managed Facebook Pages
  1275. const pagesRes = await axios.get(`${GRAPH_API}/me/accounts`, {
  1276. params: { access_token: userToken, fields: 'id,name,access_token,picture' },
  1277. });
  1278. const pages = [];
  1279. const igAccounts = [];
  1280. for (const page of pagesRes.data.data || []) {
  1281. pages.push({
  1282. id: page.id,
  1283. name: page.name,
  1284. accessToken: encryptToken(page.access_token),
  1285. picture: page.picture?.data?.url || null,
  1286. selected: false,
  1287. });
  1288. // Check for linked Instagram Business Account
  1289. try {
  1290. const igRes = await axios.get(`${GRAPH_API}/${page.id}`, {
  1291. params: {
  1292. fields: 'instagram_business_account',
  1293. access_token: page.access_token,
  1294. },
  1295. });
  1296. if (igRes.data.instagram_business_account?.id) {
  1297. const igId = igRes.data.instagram_business_account.id;
  1298. // Fetch IG account details
  1299. const igProfile = await axios.get(`${GRAPH_API}/${igId}`, {
  1300. params: {
  1301. fields: 'id,username,name,profile_picture_url',
  1302. access_token: userToken,
  1303. },
  1304. });
  1305. igAccounts.push({
  1306. id: igId,
  1307. username: igProfile.data.username || igProfile.data.name,
  1308. name: igProfile.data.name,
  1309. avatar: igProfile.data.profile_picture_url || null,
  1310. accessToken: encryptToken(userToken),
  1311. pageId: page.id,
  1312. selected: false,
  1313. });
  1314. }
  1315. } catch (_) {
  1316. // Page has no linked Instagram account — skip
  1317. }
  1318. }
  1319. // Store discovery results for the UI to pick from
  1320. await setCredentials('meta_discovery', { pages, igAccounts, discoveredAt: new Date() });
  1321. reply.redirect(`${APP_BASE_URL}/settings?meta_discovery=1`);
  1322. } catch (err) {
  1323. app.log.error({ action: 'meta_oauth_callback', platform: 'meta', outcome: 'failure', err: err.response?.data?.error?.message || err.message });
  1324. reply.redirect(`${APP_BASE_URL}/settings?meta_error=${encodeURIComponent(err.message)}`);
  1325. }
  1326. });
  1327. // Return pending discovery results so the UI can render the page picker
  1328. app.get('/auth/meta/discovered', async () => {
  1329. const discovery = await getCredentials('meta_discovery');
  1330. if (!discovery) return { pages: [], igAccounts: [] };
  1331. return { pages: discovery.pages || [], igAccounts: discovery.igAccounts || [] };
  1332. });
  1333. // User has chosen which pages/accounts to connect
  1334. app.post('/auth/meta/save', async (request, reply) => {
  1335. const { selectedPageIds = [], selectedIgAccountIds = [] } = request.body || {};
  1336. const discovery = await getCredentials('meta_discovery');
  1337. if (!discovery) return reply.code(400).send({ error: 'No discovery data found — reconnect via OAuth' });
  1338. const fbPages = (discovery.pages || []).map((p) => ({
  1339. ...p,
  1340. selected: selectedPageIds.includes(p.id),
  1341. }));
  1342. const igAccounts = (discovery.igAccounts || []).map((a) => ({
  1343. ...a,
  1344. selected: selectedIgAccountIds.includes(a.id),
  1345. }));
  1346. await setCredentials('facebook', { pages: fbPages });
  1347. await setCredentials('instagram', { accounts: igAccounts });
  1348. await deleteCredentials('meta_discovery');
  1349. _tokenExpiryCache = null; // invalidate cache after reconnect
  1350. return { success: true, facebookPages: fbPages.filter((p) => p.selected).length, instagramAccounts: igAccounts.filter((a) => a.selected).length };
  1351. });
  1352. // Disconnect all Meta platforms
  1353. app.delete('/credentials/meta', async () => {
  1354. await deleteCredentials('facebook');
  1355. await deleteCredentials('instagram');
  1356. await deleteCredentials('meta_discovery');
  1357. return { success: true };
  1358. });
  1359. // ─── Pinterest OAuth Flow ─────────────────────────────────────────────────────
  1360. const PINTEREST_API = 'https://api.pinterest.com/v5';
  1361. const PINTEREST_AUTH_URL = 'https://www.pinterest.com/oauth/';
  1362. const PINTEREST_TOKEN_URL = 'https://api.pinterest.com/v5/oauth/token';
  1363. app.post('/credentials/pinterest-app', async (request, reply) => {
  1364. const { clientId, clientSecret } = request.body || {};
  1365. if (!clientId || !clientSecret) {
  1366. return reply.code(400).send({ error: 'clientId and clientSecret are required' });
  1367. }
  1368. await setCredentials('pinterest_app', { clientId, clientSecret: encryptToken(clientSecret) });
  1369. log.info({ action: 'pinterest_app_save', outcome: 'success' });
  1370. return { success: true };
  1371. });
  1372. app.get('/credentials/pinterest-app', async () => {
  1373. const cred = await getCredentials('pinterest_app');
  1374. if (!cred) return { configured: false };
  1375. const plain = decryptToken(cred.clientSecret) || '';
  1376. return { configured: true, clientId: cred.clientId, clientSecretHint: plain ? `****${plain.slice(-4)}` : '****' };
  1377. });
  1378. app.get('/auth/pinterest/init', async (request, reply) => {
  1379. const cred = await getCredentials('pinterest_app');
  1380. if (!cred?.clientId) {
  1381. return reply.code(400).send({ error: 'Save your Pinterest Client ID and Secret first' });
  1382. }
  1383. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1384. const scopes = 'pins:read,pins:write,boards:read,user_accounts:read';
  1385. const url = `${PINTEREST_AUTH_URL}?client_id=${cred.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scopes}`;
  1386. return { url };
  1387. });
  1388. app.get('/auth/pinterest/callback', async (request, reply) => {
  1389. const { code, error: oauthError } = request.query;
  1390. if (oauthError) {
  1391. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(oauthError)}`);
  1392. }
  1393. if (!code) {
  1394. return reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=no_code`);
  1395. }
  1396. try {
  1397. const appCred = await getCredentials('pinterest_app');
  1398. if (!appCred?.clientId) throw new Error('App credentials not configured');
  1399. const clientSecret = decryptToken(appCred.clientSecret);
  1400. if (!clientSecret) throw new Error('Failed to decrypt client secret');
  1401. const redirectUri = `${APP_BASE_URL}/api/auth/pinterest/callback`;
  1402. const basicAuth = Buffer.from(`${appCred.clientId}:${clientSecret}`).toString('base64');
  1403. const tokenRes = await axios.post(
  1404. PINTEREST_TOKEN_URL,
  1405. new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }).toString(),
  1406. {
  1407. headers: {
  1408. Authorization: `Basic ${basicAuth}`,
  1409. 'Content-Type': 'application/x-www-form-urlencoded',
  1410. },
  1411. timeout: 15000,
  1412. }
  1413. );
  1414. const { access_token, refresh_token, expires_in } = tokenRes.data;
  1415. const tokenExpiry = new Date(Date.now() + (expires_in || 30 * 24 * 60 * 60) * 1000).toISOString();
  1416. const [userRes, boardsRes] = await Promise.all([
  1417. axios.get(`${PINTEREST_API}/user_account`, {
  1418. headers: { Authorization: `Bearer ${access_token}` },
  1419. timeout: 10000,
  1420. }),
  1421. axios.get(`${PINTEREST_API}/boards`, {
  1422. headers: { Authorization: `Bearer ${access_token}` },
  1423. params: { page_size: 100 },
  1424. timeout: 15000,
  1425. }),
  1426. ]);
  1427. const boards = (boardsRes.data.items || []).map((b) => ({
  1428. id: b.id,
  1429. name: b.name,
  1430. privacy: b.privacy,
  1431. selected: false,
  1432. }));
  1433. await setCredentials('pinterest', {
  1434. userId: userRes.data.username,
  1435. username: userRes.data.username,
  1436. displayName: userRes.data.business_name || userRes.data.username,
  1437. avatar: userRes.data.profile_image,
  1438. accessToken: encryptToken(access_token),
  1439. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1440. tokenExpiry,
  1441. boards,
  1442. });
  1443. log.info({ action: 'pinterest_oauth_callback', username: userRes.data.username, boards: boards.length, outcome: 'success' });
  1444. reply.redirect(`${APP_BASE_URL}/settings?pinterest_connected=1`);
  1445. } catch (err) {
  1446. const msg = err.response?.data?.message || err.message;
  1447. log.error({ action: 'pinterest_oauth_callback', outcome: 'failure', err: msg });
  1448. reply.redirect(`${APP_BASE_URL}/settings?pinterest_error=${encodeURIComponent(msg)}`);
  1449. }
  1450. });
  1451. app.post('/credentials/pinterest/boards', async (request, reply) => {
  1452. const { selectedBoardIds = [] } = request.body || {};
  1453. const cred = await getCredentials('pinterest');
  1454. if (!cred) return reply.code(400).send({ error: 'Pinterest not connected' });
  1455. const boards = (cred.boards || []).map((b) => ({ ...b, selected: selectedBoardIds.includes(b.id) }));
  1456. await setCredentials('pinterest', { ...cred, boards });
  1457. log.info({ action: 'pinterest_boards_save', selected: boards.filter((b) => b.selected).length, outcome: 'success' });
  1458. return { success: true, selected: boards.filter((b) => b.selected).length };
  1459. });
  1460. app.delete('/credentials/pinterest', async () => {
  1461. await deleteCredentials('pinterest');
  1462. return { success: true };
  1463. });
  1464. // ─── TikTok OAuth ─────────────────────────────────────────────────────────────
  1465. const TIKTOK_AUTH_URL = 'https://www.tiktok.com/v2/auth/authorize/';
  1466. const TIKTOK_TOKEN_URL = 'https://open.tiktokapis.com/v2/oauth/token/';
  1467. const TIKTOK_API = 'https://open.tiktokapis.com/v2';
  1468. app.post('/credentials/tiktok-app', async (request, reply) => {
  1469. const { clientKey, clientSecret } = request.body || {};
  1470. if (!clientKey || !clientSecret) return reply.code(400).send({ error: 'clientKey and clientSecret are required' });
  1471. await setCredentials('tiktok_app', { clientKey, clientSecret: encryptToken(clientSecret) });
  1472. log.info({ action: 'tiktok_app_save', outcome: 'success' });
  1473. return { success: true };
  1474. });
  1475. app.get('/credentials/tiktok-app', async () => {
  1476. const cred = await getCredentials('tiktok_app');
  1477. if (!cred?.clientKey) return { configured: false };
  1478. return { configured: true, clientKey: cred.clientKey, clientSecretHint: `****${decryptToken(cred.clientSecret).slice(-4)}` };
  1479. });
  1480. app.get('/auth/tiktok/init', async (request, reply) => {
  1481. const cred = await getCredentials('tiktok_app');
  1482. if (!cred?.clientKey) return reply.code(400).send({ error: 'Save your TikTok Client Key and Secret first' });
  1483. const codeVerifier = crypto.randomBytes(32).toString('base64url');
  1484. const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1485. const state = crypto.randomBytes(16).toString('hex');
  1486. // Persist PKCE verifier for the callback
  1487. const db = await getDb();
  1488. await db.collection('platform_credentials').updateOne(
  1489. { _id: 'tiktok_pkce' },
  1490. { $set: { codeVerifier, state, createdAt: new Date() } },
  1491. { upsert: true }
  1492. );
  1493. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1494. const scopes = 'user.info.basic,video.list,video.publish';
  1495. const params = new URLSearchParams({
  1496. client_key: cred.clientKey,
  1497. scope: scopes,
  1498. response_type: 'code',
  1499. redirect_uri: redirectUri,
  1500. state,
  1501. code_challenge: codeChallenge,
  1502. code_challenge_method: 'S256',
  1503. });
  1504. return { url: `${TIKTOK_AUTH_URL}?${params.toString()}` };
  1505. });
  1506. app.get('/auth/tiktok/callback', async (request, reply) => {
  1507. const { code, state, error: oauthError, error_description } = request.query;
  1508. if (oauthError) {
  1509. const msg = error_description || oauthError;
  1510. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1511. }
  1512. if (!code) {
  1513. return reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=no_code`);
  1514. }
  1515. try {
  1516. const db = await getDb();
  1517. const pkce = await db.collection('platform_credentials').findOne({ _id: 'tiktok_pkce' });
  1518. if (!pkce?.codeVerifier) throw new Error('PKCE state not found — try connecting again');
  1519. if (state && pkce.state && state !== pkce.state) throw new Error('OAuth state mismatch');
  1520. const appCred = await getCredentials('tiktok_app');
  1521. if (!appCred?.clientKey) throw new Error('App credentials not configured');
  1522. const clientSecret = decryptToken(appCred.clientSecret);
  1523. const redirectUri = `${APP_BASE_URL}/api/auth/tiktok/callback`;
  1524. const tokenRes = await axios.post(
  1525. TIKTOK_TOKEN_URL,
  1526. new URLSearchParams({
  1527. client_key: appCred.clientKey,
  1528. client_secret: clientSecret,
  1529. code,
  1530. grant_type: 'authorization_code',
  1531. redirect_uri: redirectUri,
  1532. code_verifier: pkce.codeVerifier,
  1533. }).toString(),
  1534. { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 15000 }
  1535. );
  1536. const { access_token, refresh_token, expires_in, refresh_expires_in, open_id } = tokenRes.data;
  1537. const tokenExpiry = new Date(Date.now() + (expires_in || 86400) * 1000).toISOString();
  1538. const refreshExpiry = new Date(Date.now() + (refresh_expires_in || 31536000) * 1000).toISOString();
  1539. const userRes = await axios.get(`${TIKTOK_API}/user/info/`, {
  1540. headers: { Authorization: `Bearer ${access_token}` },
  1541. params: { fields: 'open_id,display_name,avatar_url,username' },
  1542. timeout: 10000,
  1543. });
  1544. const user = userRes.data?.data?.user || {};
  1545. await setCredentials('tiktok', {
  1546. openId: open_id || user.open_id,
  1547. username: user.username || user.display_name,
  1548. displayName: user.display_name,
  1549. avatar: user.avatar_url || null,
  1550. accessToken: encryptToken(access_token),
  1551. refreshToken: refresh_token ? encryptToken(refresh_token) : null,
  1552. tokenExpiry,
  1553. refreshExpiry,
  1554. });
  1555. // Clean up PKCE temp state
  1556. await db.collection('platform_credentials').deleteOne({ _id: 'tiktok_pkce' });
  1557. log.info({ action: 'tiktok_oauth_callback', username: user.username || user.display_name, outcome: 'success' });
  1558. reply.redirect(`${APP_BASE_URL}/settings?tiktok_connected=1`);
  1559. } catch (err) {
  1560. const msg = err.response?.data?.error?.message || err.response?.data?.message || err.message;
  1561. log.error({ action: 'tiktok_oauth_callback', outcome: 'failure', err: msg });
  1562. reply.redirect(`${APP_BASE_URL}/settings?tiktok_error=${encodeURIComponent(msg)}`);
  1563. }
  1564. });
  1565. app.delete('/credentials/tiktok', async () => {
  1566. await deleteCredentials('tiktok');
  1567. return { success: true };
  1568. });
  1569. // ─── Credential Status ────────────────────────────────────────────────────────
  1570. // Aggregate connection status for all DB-managed platforms
  1571. app.get('/credentials', async () => {
  1572. const [metaApp, fb, ig, pinterest, tiktok] = await Promise.all([
  1573. getCredentials('meta_app'),
  1574. getCredentials('facebook'),
  1575. getCredentials('instagram'),
  1576. getCredentials('pinterest'),
  1577. getCredentials('tiktok'),
  1578. ]);
  1579. const fbPages = (fb?.pages || []).filter((p) => p.selected);
  1580. const igAccounts = (ig?.accounts || []).filter((a) => a.selected);
  1581. const pinterestBoards = (pinterest?.boards || []).filter((b) => b.selected);
  1582. return {
  1583. metaApp: { configured: !!(metaApp?.appId) },
  1584. facebook: {
  1585. connected: fbPages.length > 0,
  1586. pages: fbPages.map(({ id, name, picture }) => ({ id, name, picture })),
  1587. },
  1588. instagram: {
  1589. connected: igAccounts.length > 0,
  1590. accounts: igAccounts.map(({ id, username, avatar }) => ({ id, username, avatar })),
  1591. },
  1592. pinterest: {
  1593. connected: pinterestBoards.length > 0,
  1594. username: pinterest?.username || null,
  1595. boards: pinterestBoards.map(({ id, name, privacy }) => ({ id, name, privacy })),
  1596. allBoards: (pinterest?.boards || []).map(({ id, name, privacy, selected }) => ({ id, name, privacy, selected })),
  1597. },
  1598. tiktok: {
  1599. connected: !!(tiktok?.accessToken),
  1600. username: tiktok?.username || null,
  1601. displayName: tiktok?.displayName || null,
  1602. avatar: tiktok?.avatar || null,
  1603. },
  1604. };
  1605. });
  1606. // ─── Schedule Suggestions ────────────────────────────────────────────────────
  1607. // [dayOfWeek (0=Sun), hourUTC] pairs — research-based best-practice defaults
  1608. const INDUSTRY_DEFAULTS = {
  1609. facebook: [[2,9],[3,9],[4,9],[2,12],[4,10]],
  1610. instagram: [[1,11],[2,11],[3,11],[2,14],[3,14]],
  1611. twitter: [[2,9],[3,9],[4,9],[2,12],[3,12]],
  1612. linkedin: [[2,8],[3,8],[4,8],[3,12],[4,12]],
  1613. mastodon: [[2,10],[3,10],[4,10],[1,11],[2,11]],
  1614. bluesky: [[1,10],[2,10],[3,10],[1,11],[2,11]],
  1615. reddit: [[1,7],[2,7],[3,7],[4,7],[0,9]],
  1616. youtube: [[4,12],[5,12],[6,12],[4,15],[5,15]],
  1617. pinterest: [[5,12],[6,14],[0,15],[5,20],[6,20]],
  1618. tiktok: [[2,18],[3,18],[4,18],[5,12],[0,14]],
  1619. };
  1620. const DEFAULT_SLOTS = [[2,9],[3,9],[4,9],[2,12],[3,12]];
  1621. // Returns the next UTC Date that falls on `dayOfWeek` at `hourUTC`:00,
  1622. // at least `afterMs` milliseconds in the future.
  1623. function nextOccurrence(dayOfWeek, hourUTC, afterMs) {
  1624. const candidate = new Date(afterMs);
  1625. candidate.setUTCHours(hourUTC, 0, 0, 0);
  1626. const daysAhead = (dayOfWeek - candidate.getUTCDay() + 7) % 7;
  1627. if (daysAhead === 0 && candidate.getTime() <= afterMs) {
  1628. candidate.setUTCDate(candidate.getUTCDate() + 7);
  1629. } else {
  1630. candidate.setUTCDate(candidate.getUTCDate() + daysAhead);
  1631. }
  1632. return candidate;
  1633. }
  1634. const DAY_ABBR = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  1635. app.get('/schedule/suggestions', async (request, reply) => {
  1636. const { platform, accountId } = request.query;
  1637. if (!platform) return reply.code(400).send({ error: 'platform is required' });
  1638. const db = await getDb();
  1639. const query = { platform, ...(accountId && { accountId }) };
  1640. const dataPoints = await db.collection('post_metrics').countDocuments(query);
  1641. let slots;
  1642. let source;
  1643. if (dataPoints >= 10) {
  1644. const agg = await db.collection('post_metrics').aggregate([
  1645. { $match: query },
  1646. { $group: {
  1647. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1648. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1649. count: { $sum: 1 },
  1650. }},
  1651. { $sort: { avgEngagement: -1 } },
  1652. { $limit: 5 },
  1653. ]).toArray();
  1654. slots = agg.map((r) => [r._id.day, r._id.hour]);
  1655. source = 'history';
  1656. } else {
  1657. slots = INDUSTRY_DEFAULTS[platform] || DEFAULT_SLOTS;
  1658. source = 'default';
  1659. }
  1660. // 30-minute lead time so the user has time to finish writing
  1661. const afterMs = Date.now() + 30 * 60 * 1000;
  1662. const suggestions = slots
  1663. .map(([day, hour]) => {
  1664. const dt = nextOccurrence(day, hour, afterMs);
  1665. const h12 = hour % 12 || 12;
  1666. const ampm = hour < 12 ? 'am' : 'pm';
  1667. return {
  1668. utc: dt.toISOString(),
  1669. dayOfWeek: day,
  1670. hour,
  1671. label: `${DAY_ABBR[day]} ${h12}${ampm}`,
  1672. };
  1673. })
  1674. .sort((a, b) => new Date(a.utc) - new Date(b.utc))
  1675. .slice(0, 4);
  1676. app.log.info({ action: 'schedule_suggestions', platform, source, count: suggestions.length });
  1677. return { source, suggestions };
  1678. });
  1679. // ─── Analytics Metrics Crawl ─────────────────────────────────────────────────
  1680. async function crawlFacebookMetrics(db) {
  1681. const fb = await getCredentials('facebook');
  1682. const pages = (fb?.pages || []).filter((p) => p.selected && p.accessToken);
  1683. if (!pages.length) return { count: 0 };
  1684. let count = 0;
  1685. for (const page of pages) {
  1686. const token = decryptToken(page.accessToken);
  1687. if (!token) continue;
  1688. try {
  1689. const res = await axios.get(`${GRAPH_API}/${page.id}/posts`, {
  1690. params: {
  1691. fields: 'id,message,created_time,reactions.summary(total_count),comments.summary(total_count),shares',
  1692. limit: 100,
  1693. access_token: token,
  1694. },
  1695. timeout: 30000,
  1696. });
  1697. for (const post of res.data.data || []) {
  1698. const likes = post.reactions?.summary?.total_count || 0;
  1699. const comments = post.comments?.summary?.total_count || 0;
  1700. const shares = post.shares?.count || 0;
  1701. const publishedAt = new Date(post.created_time);
  1702. await db.collection('post_metrics').updateOne(
  1703. { platform: 'facebook', postId: post.id },
  1704. {
  1705. $set: {
  1706. platform: 'facebook',
  1707. accountId: page.id,
  1708. accountName: page.name,
  1709. postId: post.id,
  1710. content: post.message || null,
  1711. publishedAt,
  1712. metrics: { likes, comments, shares, views: 0, saves: 0, engagementTotal: likes + comments + shares },
  1713. hourOfDay: publishedAt.getUTCHours(),
  1714. dayOfWeek: publishedAt.getUTCDay(),
  1715. fetchedAt: new Date(),
  1716. },
  1717. },
  1718. { upsert: true }
  1719. );
  1720. count++;
  1721. }
  1722. } catch (err) {
  1723. app.log.warn({ action: 'metrics_crawl', platform: 'facebook', pageId: page.id, outcome: 'failure', err: err.message });
  1724. }
  1725. }
  1726. return { count };
  1727. }
  1728. async function crawlInstagramMetrics(db) {
  1729. const ig = await getCredentials('instagram');
  1730. const accounts = (ig?.accounts || []).filter((a) => a.selected && a.accessToken);
  1731. if (!accounts.length) return { count: 0 };
  1732. let count = 0;
  1733. for (const account of accounts) {
  1734. const token = decryptToken(account.accessToken);
  1735. if (!token) continue;
  1736. try {
  1737. const mediaRes = await axios.get(`${GRAPH_API}/${account.id}/media`, {
  1738. params: { fields: 'id,caption,timestamp,like_count,comments_count', limit: 100, access_token: token },
  1739. timeout: 30000,
  1740. });
  1741. for (const media of mediaRes.data.data || []) {
  1742. const likes = media.like_count || 0;
  1743. const comments = media.comments_count || 0;
  1744. const publishedAt = new Date(media.timestamp);
  1745. let views = 0;
  1746. let saves = 0;
  1747. try {
  1748. const insRes = await axios.get(`${GRAPH_API}/${media.id}/insights`, {
  1749. params: { metric: 'reach,saved', access_token: token },
  1750. timeout: 10000,
  1751. });
  1752. for (const ins of insRes.data.data || []) {
  1753. if (ins.name === 'reach') views = ins.values?.[0]?.value || 0;
  1754. if (ins.name === 'saved') saves = ins.values?.[0]?.value || 0;
  1755. }
  1756. } catch (_) {}
  1757. await db.collection('post_metrics').updateOne(
  1758. { platform: 'instagram', postId: media.id },
  1759. {
  1760. $set: {
  1761. platform: 'instagram',
  1762. accountId: account.id,
  1763. accountName: account.username,
  1764. postId: media.id,
  1765. content: media.caption || null,
  1766. publishedAt,
  1767. metrics: { likes, comments, shares: 0, views, saves, engagementTotal: likes + comments },
  1768. hourOfDay: publishedAt.getUTCHours(),
  1769. dayOfWeek: publishedAt.getUTCDay(),
  1770. fetchedAt: new Date(),
  1771. },
  1772. },
  1773. { upsert: true }
  1774. );
  1775. count++;
  1776. }
  1777. } catch (err) {
  1778. app.log.warn({ action: 'metrics_crawl', platform: 'instagram', accountId: account.id, outcome: 'failure', err: err.message });
  1779. }
  1780. }
  1781. return { count };
  1782. }
  1783. app.post('/analytics/crawl', async () => {
  1784. const db = await getDb();
  1785. const results = {};
  1786. for (const [platform, crawler] of [['facebook', crawlFacebookMetrics], ['instagram', crawlInstagramMetrics]]) {
  1787. try {
  1788. results[platform] = await crawler(db);
  1789. } catch (err) {
  1790. app.log.error({ action: 'metrics_crawl', platform, outcome: 'failure', err: err.message });
  1791. results[platform] = { count: 0, error: err.message };
  1792. }
  1793. }
  1794. const total = Object.values(results).reduce((sum, r) => sum + (r.count || 0), 0);
  1795. app.log.info({ action: 'metrics_crawl', outcome: 'complete', total });
  1796. return { success: true, total, byPlatform: results };
  1797. });
  1798. app.get('/analytics/insights', async (request) => {
  1799. const filter = parseAccountFilter(request.query.account);
  1800. const metricsMatch = filter
  1801. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  1802. : {};
  1803. const db = await getDb();
  1804. const total = await db.collection('post_metrics').countDocuments(metricsMatch);
  1805. if (total === 0) return { empty: true };
  1806. const [byHourRaw, byDayRaw, topPosts, platformComparison, heatmapRaw] = await Promise.all([
  1807. db.collection('post_metrics').aggregate([
  1808. { $match: metricsMatch },
  1809. { $group: { _id: '$hourOfDay', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1810. { $sort: { _id: 1 } },
  1811. ]).toArray(),
  1812. db.collection('post_metrics').aggregate([
  1813. { $match: metricsMatch },
  1814. { $group: { _id: '$dayOfWeek', avgEngagement: { $avg: '$metrics.engagementTotal' }, count: { $sum: 1 } } },
  1815. { $sort: { _id: 1 } },
  1816. ]).toArray(),
  1817. db.collection('post_metrics').find(metricsMatch).sort({ 'metrics.engagementTotal': -1 }).limit(5).toArray(),
  1818. db.collection('post_metrics').aggregate([
  1819. { $match: metricsMatch },
  1820. { $group: {
  1821. _id: '$platform',
  1822. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1823. avgLikes: { $avg: '$metrics.likes' },
  1824. avgComments: { $avg: '$metrics.comments' },
  1825. avgShares: { $avg: '$metrics.shares' },
  1826. totalPosts: { $sum: 1 },
  1827. }},
  1828. { $sort: { avgEngagement: -1 } },
  1829. ]).toArray(),
  1830. db.collection('post_metrics').aggregate([
  1831. { $match: metricsMatch },
  1832. { $group: {
  1833. _id: { day: '$dayOfWeek', hour: '$hourOfDay' },
  1834. avgEngagement: { $avg: '$metrics.engagementTotal' },
  1835. count: { $sum: 1 },
  1836. }},
  1837. ]).toArray(),
  1838. ]);
  1839. const byHour = Array.from({ length: 24 }, (_, h) => {
  1840. const e = byHourRaw.find((r) => r._id === h);
  1841. return { hour: h, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1842. });
  1843. const byDay = Array.from({ length: 7 }, (_, d) => {
  1844. const e = byDayRaw.find((r) => r._id === d);
  1845. return { day: d, avgEngagement: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1846. });
  1847. const heatmap = Array.from({ length: 7 * 24 }, (_, i) => {
  1848. const day = Math.floor(i / 24);
  1849. const hour = i % 24;
  1850. const e = heatmapRaw.find((r) => r._id.day === day && r._id.hour === hour);
  1851. return { day, hour, avg: Math.round(e?.avgEngagement || 0), count: e?.count || 0 };
  1852. });
  1853. return {
  1854. empty: false,
  1855. total,
  1856. byHour,
  1857. byDay,
  1858. heatmap,
  1859. topPosts: topPosts.map((p) => ({
  1860. platform: p.platform, accountName: p.accountName, postId: p.postId,
  1861. content: p.content, publishedAt: p.publishedAt, metrics: p.metrics,
  1862. })),
  1863. platformComparison: platformComparison.map((p) => ({
  1864. platform: p._id,
  1865. avgEngagement: Math.round(p.avgEngagement),
  1866. avgLikes: Math.round(p.avgLikes),
  1867. avgComments: Math.round(p.avgComments),
  1868. avgShares: Math.round(p.avgShares),
  1869. totalPosts: p.totalPosts,
  1870. })),
  1871. };
  1872. });
  1873. // ─── Analytics ────────────────────────────────────────────────────────────────
  1874. // Parse "platform" or "platform:accountId" filter strings from the account query param.
  1875. function parseAccountFilter(account) {
  1876. if (!account) return null;
  1877. const idx = account.indexOf(':');
  1878. if (idx === -1) return { platform: account };
  1879. return { platform: account.slice(0, idx), accountId: account.slice(idx + 1) };
  1880. }
  1881. // Build a MongoDB match fragment for scheduled_jobs given an account filter.
  1882. function sjFilter(filter) {
  1883. if (!filter) return {};
  1884. return {
  1885. 'destinations.platform': filter.platform,
  1886. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1887. };
  1888. }
  1889. // Build a MongoDB match fragment for posts (type:immediate) given an account filter.
  1890. function ipFilter(filter) {
  1891. if (!filter) return {};
  1892. return {
  1893. 'destinations.platform': filter.platform,
  1894. ...(filter.accountId && { 'destinations.accountId': filter.accountId }),
  1895. };
  1896. }
  1897. app.get('/analytics/summary', async (request) => {
  1898. const filter = parseAccountFilter(request.query.account);
  1899. const db = await getDb();
  1900. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  1901. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  1902. // Post-unwind filter for scheduled_jobs platform breakdown — re-applies the
  1903. // account filter after $unwind so a job targeting multiple platforms only
  1904. // counts the platform(s) that match the filter.
  1905. const unwindFilter = filter ? [{ $match: sjFilter(filter) }] : [];
  1906. const [
  1907. schedCompleted, schedFailed,
  1908. immPublished, immFailed,
  1909. recentSched, recentImm,
  1910. schedPlatformRaw, immPlatformRaw,
  1911. schedDayRaw, immDayRaw,
  1912. ] = await Promise.all([
  1913. db.collection('scheduled_jobs').countDocuments({ status: 'completed', ...sjFilter(filter) }),
  1914. db.collection('scheduled_jobs').countDocuments({ status: 'failed', ...sjFilter(filter) }),
  1915. db.collection('posts').countDocuments({ type: 'immediate', status: { $in: ['published', 'partial'] }, ...ipFilter(filter) }),
  1916. db.collection('posts').countDocuments({ type: 'immediate', status: 'failed', ...ipFilter(filter) }),
  1917. db.collection('scheduled_jobs').countDocuments({ status: 'completed', completedAt: { $gte: sevenDaysAgo }, ...sjFilter(filter) }),
  1918. db.collection('posts').countDocuments({ type: 'immediate', publishedAt: { $gte: sevenDaysAgo }, ...ipFilter(filter) }),
  1919. // Platform breakdown from scheduled_jobs destinations
  1920. db.collection('scheduled_jobs').aggregate([
  1921. { $match: { status: 'completed', ...sjFilter(filter) } },
  1922. { $unwind: '$destinations' },
  1923. ...unwindFilter,
  1924. { $group: { _id: '$destinations.platform', count: { $sum: 1 } } },
  1925. { $sort: { count: -1 } },
  1926. ]).toArray(),
  1927. // Platform breakdown from immediate posts platformResults
  1928. db.collection('posts').aggregate([
  1929. { $match: { type: 'immediate', ...ipFilter(filter) } },
  1930. { $project: { results: { $objectToArray: { $ifNull: ['$platformResults', {}] } } } },
  1931. { $unwind: '$results' },
  1932. { $match: { 'results.v.success': true } },
  1933. { $project: { platform: { $arrayElemAt: [{ $split: ['$results.k', ':'] }, 0] } } },
  1934. { $group: { _id: '$platform', count: { $sum: 1 } } },
  1935. ]).toArray(),
  1936. // Activity by day from scheduled_jobs (using completedAt)
  1937. db.collection('scheduled_jobs').aggregate([
  1938. { $match: { status: 'completed', completedAt: { $gte: thirtyDaysAgo }, ...sjFilter(filter) } },
  1939. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$completedAt' } }, count: { $sum: 1 } } },
  1940. { $sort: { _id: 1 } },
  1941. ]).toArray(),
  1942. // Activity by day from immediate posts
  1943. db.collection('posts').aggregate([
  1944. { $match: { type: 'immediate', publishedAt: { $gte: thirtyDaysAgo }, ...ipFilter(filter) } },
  1945. { $group: { _id: { $dateToString: { format: '%Y-%m-%d', date: '$publishedAt' } }, count: { $sum: 1 } } },
  1946. { $sort: { _id: 1 } },
  1947. ]).toArray(),
  1948. ]);
  1949. const dayMap = {};
  1950. for (const { _id, count } of [...schedDayRaw, ...immDayRaw]) {
  1951. dayMap[_id] = (dayMap[_id] || 0) + count;
  1952. }
  1953. const byDay = Object.entries(dayMap).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
  1954. const platformMap = {};
  1955. for (const { _id, count } of [...schedPlatformRaw, ...immPlatformRaw]) {
  1956. if (_id) platformMap[_id] = (platformMap[_id] || 0) + count;
  1957. }
  1958. const published = schedCompleted + immPublished;
  1959. const failed = schedFailed + immFailed;
  1960. const total = published + failed;
  1961. const successRate = total > 0 ? Math.round((published / total) * 100) : 0;
  1962. const recentCount = recentSched + recentImm;
  1963. return { total, published, failed, partial: 0, successRate, byPlatform: platformMap, byDay, recentCount };
  1964. });
  1965. app.get('/analytics/posts', async (request) => {
  1966. const limit = Math.min(parseInt(request.query.limit || '20', 10), 100);
  1967. const skip = parseInt(request.query.skip || '0', 10);
  1968. const filter = parseAccountFilter(request.query.account);
  1969. const db = await getDb();
  1970. const sjMatch = { status: { $in: ['completed', 'failed'] }, ...sjFilter(filter) };
  1971. const ipMatch = { type: 'immediate', ...ipFilter(filter) };
  1972. const [scheduledJobs, immediatePosts, schedTotal, immTotal] = await Promise.all([
  1973. db.collection('scheduled_jobs')
  1974. .find(sjMatch)
  1975. .sort({ completedAt: -1, scheduledAt: -1 })
  1976. .skip(skip)
  1977. .limit(limit)
  1978. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  1979. .toArray(),
  1980. db.collection('posts')
  1981. .find(ipMatch)
  1982. .sort({ publishedAt: -1 })
  1983. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  1984. .toArray(),
  1985. db.collection('scheduled_jobs').countDocuments(sjMatch),
  1986. db.collection('posts').countDocuments(ipMatch),
  1987. ]);
  1988. const normalised = [
  1989. ...scheduledJobs.map((j) => ({
  1990. _id: String(j._id),
  1991. type: 'scheduled',
  1992. content: j.content || null,
  1993. destinations: j.destinations || [],
  1994. platformResults: null,
  1995. status: j.status === 'completed' ? 'published' : 'failed',
  1996. publishedAt: j.completedAt || j.scheduledAt,
  1997. })),
  1998. ...immediatePosts.map((p) => ({
  1999. _id: String(p._id),
  2000. type: 'immediate',
  2001. content: p.content || null,
  2002. destinations: p.destinations || [],
  2003. platformResults: p.platformResults || null,
  2004. status: p.status,
  2005. publishedAt: p.publishedAt,
  2006. })),
  2007. ].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  2008. .slice(0, limit);
  2009. return { posts: normalised, total: schedTotal + immTotal };
  2010. });
  2011. // ─── Analytics Export ─────────────────────────────────────────────────────────
  2012. // GET /analytics/export?format=csv&account=&month=YYYY-MM
  2013. // Exports scheduled jobs + immediate posts as a downloadable CSV.
  2014. app.get('/analytics/export', async (request, reply) => {
  2015. const { format = 'csv', account, month } = request.query;
  2016. const filter = parseAccountFilter(account);
  2017. const db = await getDb();
  2018. let dateFilter = {};
  2019. if (month) {
  2020. const start = new Date(`${month}-01T00:00:00.000Z`);
  2021. const end = new Date(start);
  2022. end.setMonth(end.getMonth() + 1);
  2023. dateFilter = { $gte: start, $lt: end };
  2024. }
  2025. const sjMatch = {
  2026. status: { $in: ['completed', 'failed'] },
  2027. ...sjFilter(filter),
  2028. ...(month ? { completedAt: dateFilter } : {}),
  2029. };
  2030. const ipMatch = {
  2031. type: 'immediate',
  2032. ...ipFilter(filter),
  2033. ...(month ? { publishedAt: dateFilter } : {}),
  2034. };
  2035. const [scheduledJobs, immediatePosts] = await Promise.all([
  2036. db.collection('scheduled_jobs')
  2037. .find(sjMatch)
  2038. .sort({ completedAt: -1 })
  2039. .project({ content: 1, destinations: 1, status: 1, completedAt: 1, scheduledAt: 1 })
  2040. .toArray(),
  2041. db.collection('posts')
  2042. .find(ipMatch)
  2043. .sort({ publishedAt: -1 })
  2044. .project({ content: 1, destinations: 1, platformResults: 1, status: 1, publishedAt: 1 })
  2045. .toArray(),
  2046. ]);
  2047. const rows = [
  2048. ...scheduledJobs.map((j) => ({
  2049. type: 'scheduled',
  2050. date: (j.completedAt || j.scheduledAt)?.toISOString()?.slice(0, 10) ?? '',
  2051. time: (j.completedAt || j.scheduledAt)?.toISOString()?.slice(11, 16) ?? '',
  2052. platforms: (j.destinations || []).map((d) => d.platform).join(' | '),
  2053. status: j.status === 'completed' ? 'published' : 'failed',
  2054. content: j.content || '',
  2055. })),
  2056. ...immediatePosts.map((p) => ({
  2057. type: 'immediate',
  2058. date: p.publishedAt?.toISOString()?.slice(0, 10) ?? '',
  2059. time: p.publishedAt?.toISOString()?.slice(11, 16) ?? '',
  2060. platforms: (p.destinations || []).map((d) => d.platform).join(' | '),
  2061. status: p.status,
  2062. content: p.content || '',
  2063. })),
  2064. ].sort((a, b) => b.date.localeCompare(a.date) || b.time.localeCompare(a.time));
  2065. const escape = (v) => `"${String(v).replace(/"/g, '""')}"`;
  2066. const header = ['Date', 'Time (UTC)', 'Type', 'Platforms', 'Status', 'Content'];
  2067. const lines = [
  2068. header.join(','),
  2069. ...rows.map((r) => [r.date, r.time, r.type, r.platforms, r.status, escape(r.content)].join(',')),
  2070. ];
  2071. const filename = `posts-${month || 'all'}.csv`;
  2072. reply.header('Content-Type', 'text/csv; charset=utf-8');
  2073. reply.header('Content-Disposition', `attachment; filename="${filename}"`);
  2074. return reply.send('' + lines.join('\r\n'));
  2075. });
  2076. // ─── Brand / Account Audit ────────────────────────────────────────────────────
  2077. app.post('/analytics/audit', async (request, reply) => {
  2078. const filter = parseAccountFilter(request.query.account);
  2079. const db = await getDb();
  2080. const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
  2081. const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  2082. const recentPosts = await db.collection('posts').find({
  2083. publishedAt: { $gte: thirtyDaysAgo },
  2084. ...ipFilter(filter),
  2085. }, { projection: { content: 1, destinations: 1, publishedAt: 1, status: 1 } }).toArray();
  2086. if (recentPosts.length < 3) {
  2087. return reply.code(400).send({ error: 'Not enough publishing history. Publish at least 3 posts first.' });
  2088. }
  2089. // Posting frequency
  2090. const postsLast30 = recentPosts.length;
  2091. const postsLast7 = recentPosts.filter((p) => new Date(p.publishedAt) >= sevenDaysAgo).length;
  2092. const postsPerWeek = Math.round((postsLast30 / 4) * 10) / 10;
  2093. // Platforms used
  2094. const platforms = [...new Set(recentPosts.flatMap((p) => (p.destinations || []).map((d) => d.platform)).filter(Boolean))];
  2095. // Success rate
  2096. const publishedCount = recentPosts.filter((p) => p.status === 'published').length;
  2097. const successRate = Math.round((publishedCount / postsLast30) * 100);
  2098. // Top hashtags from post content
  2099. const hashtagCounts = {};
  2100. for (const post of recentPosts) {
  2101. const re = /#([a-zA-Z]\w*)/g;
  2102. let m;
  2103. re.lastIndex = 0;
  2104. while ((m = re.exec(post.content || '')) !== null) {
  2105. const tag = `#${m[1].toLowerCase()}`;
  2106. hashtagCounts[tag] = (hashtagCounts[tag] || 0) + 1;
  2107. }
  2108. }
  2109. const topHashtags = Object.entries(hashtagCounts)
  2110. .sort((a, b) => b[1] - a[1])
  2111. .slice(0, 5)
  2112. .map(([tag, count]) => `${tag} (${count}x)`)
  2113. .join(', ');
  2114. // Posting hour distribution — identify peak hours
  2115. const hourCounts = {};
  2116. for (const post of recentPosts) {
  2117. if (post.publishedAt) {
  2118. const h = new Date(post.publishedAt).getUTCHours();
  2119. hourCounts[h] = (hourCounts[h] || 0) + 1;
  2120. }
  2121. }
  2122. const peakHours = Object.entries(hourCounts)
  2123. .sort((a, b) => b[1] - a[1])
  2124. .slice(0, 3)
  2125. .map(([h]) => `${h}:00 UTC`)
  2126. .join(', ');
  2127. // Engagement data from post_metrics
  2128. const metricsFilter = filter
  2129. ? { platform: filter.platform, ...(filter.accountId && { accountId: filter.accountId }) }
  2130. : {};
  2131. const metrics = await db.collection('post_metrics')
  2132. .find({ ...metricsFilter, createdAt: { $gte: thirtyDaysAgo } })
  2133. .toArray();
  2134. const avgEngagement = metrics.length > 0
  2135. ? Math.round((metrics.reduce((s, m) => s + (m.metrics?.engagementTotal || 0), 0) / metrics.length) * 10) / 10
  2136. : 0;
  2137. const statsBlock = [
  2138. `Publishing stats (last 30 days):`,
  2139. `- Total posts: ${postsLast30}`,
  2140. `- Posts this week: ${postsLast7}`,
  2141. `- Posts per week (avg): ${postsPerWeek}`,
  2142. `- Platforms used: ${platforms.join(', ') || 'unknown'}`,
  2143. `- Success rate: ${successRate}%`,
  2144. `- Average engagement per post: ${avgEngagement}`,
  2145. `- Current peak posting hours (UTC): ${peakHours || 'not enough data'}`,
  2146. `- Top hashtags in use: ${topHashtags || 'none detected'}`,
  2147. ].join('\n');
  2148. const system = 'You are a social media performance analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2149. const prompt = `Audit this social media account and return a structured report.
  2150. ${statsBlock}
  2151. Return a JSON object with exactly these fields:
  2152. {
  2153. "score": <overall health score 0-100>,
  2154. "summary": "<2-3 sentence assessment>",
  2155. "postingFrequency": { "score": <0-10>, "assessment": "<one sentence>" },
  2156. "engagement": { "score": <0-10>, "benchmark": "<Excellent|Good|Average|Below Average>", "assessment": "<one sentence>" },
  2157. "contentMix": { "score": <0-10>, "assessment": "<one sentence on variety and platform fit>" },
  2158. "recommendations": ["<specific action 1>", "<specific action 2>", "<specific action 3>"]
  2159. }
  2160. Scoring benchmarks: posting 5+x/week = 8-10, 3-4x = 6-7, 1-2x = 4-5, less = 1-3.
  2161. Engagement benchmarks: >5 avg = Excellent, 3-5 = Good, 1-3 = Average, <1 = Below Average.
  2162. Return ONLY the JSON object.`;
  2163. try {
  2164. const pconf = await getActiveProviderConfig();
  2165. const model = pconf.model;
  2166. let text = '';
  2167. if (pconf.provider === 'ollama') {
  2168. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2169. text = res.data.response;
  2170. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2171. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2172. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2173. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2174. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2175. text = res.data.choices[0]?.message?.content || '';
  2176. } else if (pconf.provider === 'gemini') {
  2177. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2178. const res = await axios.post(
  2179. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2180. { contents: buildGeminiContents(prompt, system) },
  2181. { timeout: 120000 },
  2182. );
  2183. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2184. } else {
  2185. return reply.code(400).send({ error: 'AI not configured' });
  2186. }
  2187. let audit = null;
  2188. try {
  2189. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2190. audit = JSON.parse(jsonStr);
  2191. if (typeof audit.score !== 'number') throw new Error();
  2192. } catch {
  2193. return reply.code(503).send({ error: 'AI returned invalid audit format — try again' });
  2194. }
  2195. log.info({ action: 'analytics_audit', account: request.query.account || 'all', outcome: 'success' });
  2196. return {
  2197. success: true,
  2198. ...audit,
  2199. stats: { postsLast30, postsLast7, postsPerWeek, platforms, successRate, avgEngagement },
  2200. generatedAt: new Date(),
  2201. };
  2202. } catch (err) {
  2203. return reply.code(503).send({ error: 'Audit failed', detail: err.message });
  2204. }
  2205. });
  2206. // ─── Hashtag Groups ───────────────────────────────────────────────────────────
  2207. app.get('/hashtag-groups', async () => {
  2208. const db = await getDb();
  2209. const groups = await db.collection('hashtag_groups').find({}).sort({ name: 1 }).toArray();
  2210. return { groups };
  2211. });
  2212. app.post('/hashtag-groups', async (request, reply) => {
  2213. const { name, hashtags } = request.body || {};
  2214. if (!name?.trim()) return reply.code(400).send({ error: 'name is required' });
  2215. const tags = (hashtags || []).map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2216. const db = await getDb();
  2217. const result = await db.collection('hashtag_groups').insertOne({
  2218. name: name.trim(),
  2219. hashtags: [...new Set(tags)],
  2220. createdAt: new Date(),
  2221. updatedAt: new Date(),
  2222. });
  2223. return { success: true, _id: result.insertedId };
  2224. });
  2225. app.put('/hashtag-groups/:id', async (request, reply) => {
  2226. const { id } = request.params;
  2227. const { name, hashtags } = request.body || {};
  2228. const update = { updatedAt: new Date() };
  2229. if (name?.trim()) update.name = name.trim();
  2230. if (hashtags) {
  2231. const tags = hashtags.map((t) => (t.startsWith('#') ? t : `#${t}`).toLowerCase()).filter(Boolean);
  2232. update.hashtags = [...new Set(tags)];
  2233. }
  2234. const db = await getDb();
  2235. let oid;
  2236. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2237. await db.collection('hashtag_groups').updateOne({ _id: oid }, { $set: update });
  2238. return { success: true };
  2239. });
  2240. app.delete('/hashtag-groups/:id', async (request, reply) => {
  2241. const { id } = request.params;
  2242. const db = await getDb();
  2243. let oid;
  2244. try { oid = new ObjectId(id); } catch { return reply.code(400).send({ error: 'Invalid id' }); }
  2245. await db.collection('hashtag_groups').deleteOne({ _id: oid });
  2246. return { success: true };
  2247. });
  2248. // ─── Hashtag Stats & Scraper ──────────────────────────────────────────────────
  2249. const HASHTAG_RE = /#([a-zA-Z]\w*)/g;
  2250. function extractHashtags(text) {
  2251. if (!text) return [];
  2252. const tags = [];
  2253. let m;
  2254. HASHTAG_RE.lastIndex = 0;
  2255. while ((m = HASHTAG_RE.exec(text)) !== null) tags.push(`#${m[1].toLowerCase()}`);
  2256. return tags;
  2257. }
  2258. function gradeHashtag(count, avgEngagement) {
  2259. if (count >= 5 && avgEngagement >= 10) return 'A';
  2260. if (count >= 3 && avgEngagement >= 3) return 'B';
  2261. if (count >= 2) return 'C';
  2262. return 'D';
  2263. }
  2264. // POST /hashtags/scrape — scan YOUR published posts per-account.
  2265. // Body: { accountKey?: string } — omit to scan all accounts at once.
  2266. app.post('/hashtags/scrape', async (request) => {
  2267. const { accountKey: filterAccount } = request.body || {};
  2268. const db = await getDb();
  2269. // tagMap key: `${accountKey}||${hashtag}`
  2270. const tagMap = {};
  2271. function touch(tag, accountKey, platform, engagement) {
  2272. const key = `${accountKey}||${tag}`;
  2273. if (!tagMap[key]) tagMap[key] = { tag, accountKey, count: 0, totalEngagement: 0, platforms: new Set() };
  2274. tagMap[key].count++;
  2275. tagMap[key].totalEngagement += engagement;
  2276. tagMap[key].platforms.add(platform);
  2277. }
  2278. // Engagement lookup keyed by content fingerprint
  2279. const postMetrics = await db.collection('post_metrics').find({}).toArray();
  2280. const metricsByContent = {};
  2281. for (const m of postMetrics) {
  2282. if (m.content) {
  2283. const key = m.content.slice(0, 100).toLowerCase().trim();
  2284. metricsByContent[key] = (metricsByContent[key] || 0) + (m.metrics?.engagementTotal || 0);
  2285. }
  2286. }
  2287. // Scan YOUR published posts only — feeds are others' content, not your performance
  2288. const posts = await db.collection('posts').find({}, { projection: { content: 1, destinations: 1 } }).toArray();
  2289. for (const post of posts) {
  2290. const tags = extractHashtags(post.content || '');
  2291. if (!tags.length) continue;
  2292. const engagement = post.content
  2293. ? (metricsByContent[post.content.slice(0, 100).toLowerCase().trim()] || 0)
  2294. : 0;
  2295. const destinations = post.destinations?.length ? post.destinations : [{ platform: 'unknown' }];
  2296. for (const dest of destinations) {
  2297. const acctKey = dest.accountId ? `${dest.platform}:${dest.accountId}` : dest.platform;
  2298. if (filterAccount && acctKey !== filterAccount) continue;
  2299. for (const tag of tags) {
  2300. touch(tag, acctKey, dest.platform, engagement / Math.max(tags.length, 1));
  2301. }
  2302. }
  2303. }
  2304. let scraped = 0;
  2305. for (const [compoundKey, data] of Object.entries(tagMap)) {
  2306. const avgEngagement = data.count > 0 ? data.totalEngagement / data.count : 0;
  2307. await db.collection('hashtag_stats').updateOne(
  2308. { _id: compoundKey },
  2309. {
  2310. $set: {
  2311. hashtag: data.tag,
  2312. accountKey: data.accountKey,
  2313. count: data.count,
  2314. avgEngagement: Math.round(avgEngagement * 10) / 10,
  2315. grade: gradeHashtag(data.count, avgEngagement),
  2316. platforms: [...data.platforms],
  2317. lastScraped: new Date(),
  2318. },
  2319. },
  2320. { upsert: true }
  2321. );
  2322. scraped++;
  2323. }
  2324. log.info({ action: 'hashtag_scrape', accountKey: filterAccount || 'all', outcome: 'success', scraped });
  2325. return { success: true, scraped };
  2326. });
  2327. app.get('/hashtags/stats', async (request) => {
  2328. const { sort, accountKey } = request.query;
  2329. const db = await getDb();
  2330. const sortField = sort === 'engagement' ? 'avgEngagement' : 'count';
  2331. if (accountKey) {
  2332. // Per-account view
  2333. const stats = await db.collection('hashtag_stats')
  2334. .find({ accountKey })
  2335. .sort({ [sortField]: -1 })
  2336. .limit(200)
  2337. .toArray();
  2338. return { stats };
  2339. }
  2340. // Aggregate view: group by hashtag across all accounts
  2341. const allStats = await db.collection('hashtag_stats').find({ accountKey: { $exists: true } }).toArray();
  2342. const grouped = new Map();
  2343. for (const s of allStats) {
  2344. if (!s.hashtag) continue;
  2345. if (!grouped.has(s.hashtag)) {
  2346. grouped.set(s.hashtag, { count: 0, totalEngagement: 0, totalCount: 0, platforms: new Set(), lastScraped: null });
  2347. }
  2348. const g = grouped.get(s.hashtag);
  2349. g.count += s.count;
  2350. g.totalEngagement += s.avgEngagement * s.count;
  2351. g.totalCount += s.count;
  2352. for (const p of (s.platforms || [])) g.platforms.add(p);
  2353. if (!g.lastScraped || (s.lastScraped && new Date(s.lastScraped) > new Date(g.lastScraped))) g.lastScraped = s.lastScraped;
  2354. }
  2355. const stats = [...grouped.entries()]
  2356. .map(([tag, g]) => {
  2357. const avgEngagement = g.totalCount > 0 ? Math.round((g.totalEngagement / g.totalCount) * 10) / 10 : 0;
  2358. return {
  2359. _id: tag,
  2360. hashtag: tag,
  2361. accountKey: null,
  2362. count: g.count,
  2363. avgEngagement,
  2364. grade: gradeHashtag(g.count, avgEngagement),
  2365. platforms: [...g.platforms],
  2366. lastScraped: g.lastScraped,
  2367. };
  2368. })
  2369. .sort((a, b) => b[sortField] - a[sortField])
  2370. .slice(0, 200);
  2371. return { stats };
  2372. });
  2373. app.post('/hashtags/ai-suggest', async (request, reply) => {
  2374. const { accountKey, topTags = [], count = 20 } = request.body || {};
  2375. let profileCtx = '';
  2376. if (accountKey) {
  2377. try {
  2378. const db = await getDb();
  2379. const profile = await db.collection('account_profiles').findOne({ _id: accountKey });
  2380. if (profile) {
  2381. const parts = [];
  2382. if (profile.businessName) parts.push(`Business: ${profile.businessName}`);
  2383. if (profile.description) parts.push(`Description: ${profile.description}`);
  2384. if (profile.industry) parts.push(`Industry: ${profile.industry}`);
  2385. if (profile.targetAudience) parts.push(`Target audience: ${profile.targetAudience}`);
  2386. if (profile.keywords) parts.push(`Existing keywords: ${profile.keywords}`);
  2387. if (profile.hashtags) parts.push(`Current hashtags: ${profile.hashtags}`);
  2388. profileCtx = parts.join('\n');
  2389. }
  2390. } catch (_) {}
  2391. }
  2392. const topTagList = topTags.slice(0, 15).map((t) => t._id || t).join(', ');
  2393. const system = 'You are a social media hashtag strategist. Return ONLY hashtags, space-separated, no explanations.';
  2394. const prompt = [
  2395. `Suggest ${count} high-performing hashtags for a social media account.`,
  2396. profileCtx ? `\nACCOUNT CONTEXT:\n${profileCtx}` : '',
  2397. topTagList ? `\nCURRENT TOP HASHTAGS (by usage):\n${topTagList}` : '',
  2398. `\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`,
  2399. ].filter(Boolean).join('');
  2400. try {
  2401. const pconf = await getActiveProviderConfig();
  2402. const model = pconf.model;
  2403. let text = '';
  2404. if (pconf.provider === 'ollama') {
  2405. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 60000 });
  2406. text = res.data.response;
  2407. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2408. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2409. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2410. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2411. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 60000 });
  2412. text = res.data.choices[0]?.message?.content || '';
  2413. } else if (pconf.provider === 'gemini') {
  2414. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2415. const res = await axios.post(
  2416. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2417. { contents: buildGeminiContents(prompt, system) },
  2418. { timeout: 60000 },
  2419. );
  2420. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2421. } else {
  2422. return reply.code(400).send({ error: 'AI not configured' });
  2423. }
  2424. const tags = [...new Set((text.match(/#[a-zA-Z]\w*/g) || []).map((t) => t.toLowerCase()))].slice(0, count);
  2425. return { success: true, hashtags: tags };
  2426. } catch (err) {
  2427. return reply.code(503).send({ error: 'AI suggestion failed', detail: err.message });
  2428. }
  2429. });
  2430. // ─── Competitor Intelligence ──────────────────────────────────────────────────
  2431. async function extractTextFromUrl(url) {
  2432. try {
  2433. const res = await axios.get(url, { timeout: 15000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SocialManager/1.0)' } });
  2434. const html = res.data || '';
  2435. const title = (html.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || '';
  2436. const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || '';
  2437. const headings = [...html.matchAll(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/gi)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter(Boolean).slice(0, 8);
  2438. const paras = [...html.matchAll(/<p[^>]*>(.*?)<\/p>/gis)].map((m) => m[1].replace(/<[^>]+>/g, '').trim()).filter((t) => t.length > 40).slice(0, 5);
  2439. return [title, desc, ...headings, ...paras].filter(Boolean).join('\n').slice(0, 3000);
  2440. } catch {
  2441. return '';
  2442. }
  2443. }
  2444. async function scrapeBluesky(profileUrl) {
  2445. try {
  2446. const handle = profileUrl.replace(/^https?:\/\/bsky\.app\/profile\//i, '').replace(/\/$/, '');
  2447. if (!handle) return '';
  2448. const res = await axios.get(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(handle)}&limit=10`, { timeout: 10000 });
  2449. const posts = (res.data.feed || []).map((f) => f.post?.record?.text || '').filter(Boolean);
  2450. return posts.join('\n').slice(0, 3000);
  2451. } catch {
  2452. return '';
  2453. }
  2454. }
  2455. async function scrapeMastodon(profileUrl) {
  2456. try {
  2457. const m = profileUrl.match(/^https?:\/\/([^/]+)\/@(.+)$/);
  2458. if (!m) return '';
  2459. const [, instance, username] = m;
  2460. const lookupRes = await axios.get(`https://${instance}/api/v1/accounts/lookup?acct=${encodeURIComponent(username)}`, { timeout: 10000 });
  2461. const accountId = lookupRes.data?.id;
  2462. if (!accountId) return '';
  2463. const statusRes = await axios.get(`https://${instance}/api/v1/accounts/${accountId}/statuses?limit=10&exclude_replies=true`, { timeout: 10000 });
  2464. const posts = (statusRes.data || []).map((s) => s.content?.replace(/<[^>]+>/g, '').trim() || '').filter(Boolean);
  2465. return posts.join('\n').slice(0, 3000);
  2466. } catch {
  2467. return '';
  2468. }
  2469. }
  2470. async function runCompetitorScrape(competitorId) {
  2471. const db = await getDb();
  2472. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(competitorId) });
  2473. if (!competitor) return { ok: false, message: 'Not found', sources: 0 };
  2474. const newItems = [];
  2475. if (competitor.websiteUrl) {
  2476. const text = await extractTextFromUrl(competitor.websiteUrl);
  2477. if (text) newItems.push({ source: 'website', url: competitor.websiteUrl, text, scrapedAt: new Date() });
  2478. }
  2479. const socialEntries = Object.entries(competitor.socialUrls || {});
  2480. for (const [platform, url] of socialEntries) {
  2481. if (!url) continue;
  2482. let text = '';
  2483. if (platform === 'bluesky') text = await scrapeBluesky(url);
  2484. else if (platform === 'mastodon') text = await scrapeMastodon(url);
  2485. else text = await extractTextFromUrl(url);
  2486. if (text) newItems.push({ source: platform, url, text, scrapedAt: new Date() });
  2487. }
  2488. const existing = competitor.scrapedContent || [];
  2489. // Detect whether any newly scraped content differs from what was previously stored
  2490. const existingFingerprints = new Set(existing.map((s) => s.url + '||' + s.text.slice(0, 200)));
  2491. const contentChanged = newItems.some((item) => !existingFingerprints.has(item.url + '||' + item.text.slice(0, 200)));
  2492. const combined = [...newItems, ...existing].slice(0, 20);
  2493. await db.collection('competitors').updateOne(
  2494. { _id: new ObjectId(competitorId) },
  2495. { $set: { scrapedContent: combined, contentChanged, lastScraped: new Date(), updatedAt: new Date() } },
  2496. );
  2497. return { ok: true, sources: newItems.length, message: newItems.length ? `Scraped ${newItems.length} source(s)` : 'No content found' };
  2498. }
  2499. async function buildCompetitorSystemSuffix() {
  2500. try {
  2501. const db = await getDb();
  2502. const competitors = await db.collection('competitors').find({
  2503. $or: [{ 'aiAnalysis.positioning': { $nin: ['', null] } }, { aiSummary: { $nin: ['', null] } }],
  2504. }).toArray();
  2505. if (!competitors.length) return '';
  2506. const lines = competitors.map((c) => {
  2507. if (c.aiAnalysis?.positioning) {
  2508. const a = c.aiAnalysis;
  2509. const parts = [`- ${c.name}:`];
  2510. if (a.positioning) parts.push(` Positioning: ${a.positioning}`);
  2511. if (a.gaps?.length) parts.push(` Weaknesses/gaps: ${a.gaps.join('; ')}`);
  2512. if (a.themes?.length) parts.push(` Key themes: ${a.themes.join(', ')}`);
  2513. return parts.join('\n');
  2514. }
  2515. return `- ${c.name}: ${c.aiSummary}`;
  2516. }).join('\n');
  2517. return `\n\nCOMPETITOR CONTEXT (for differentiation — do not copy, use to contrast):\n${lines}\nEmphasise what makes this brand unique compared to the above.`;
  2518. } catch {
  2519. return '';
  2520. }
  2521. }
  2522. // Save Google Places API key (used for local competitor discovery)
  2523. app.post('/credentials/google-places', async (request, reply) => {
  2524. const { apiKey } = request.body || {};
  2525. if (!apiKey?.trim()) return reply.code(400).send({ error: 'apiKey is required' });
  2526. const db = await getDb();
  2527. await db.collection('platform_credentials').updateOne(
  2528. { _id: 'google_places' },
  2529. { $set: { apiKey: apiKey.trim(), updatedAt: new Date() } },
  2530. { upsert: true },
  2531. );
  2532. return { success: true };
  2533. });
  2534. app.get('/credentials/google-places', async () => {
  2535. const db = await getDb();
  2536. const cred = await db.collection('platform_credentials').findOne({ _id: 'google_places' });
  2537. return { configured: !!cred?.apiKey, keyHint: cred?.apiKey ? `****${cred.apiKey.slice(-4)}` : null };
  2538. });
  2539. app.delete('/credentials/google-places', async () => {
  2540. const db = await getDb();
  2541. await db.collection('platform_credentials').deleteOne({ _id: 'google_places' });
  2542. return { success: true };
  2543. });
  2544. // Discover local competitors via Google Places API
  2545. app.post('/competitors/discover-local', async (request, reply) => {
  2546. const { location, businessType, radiusMeters = 5000 } = request.body || {};
  2547. if (!location) return reply.code(400).send({ error: 'location is required' });
  2548. const db = await getDb();
  2549. const cred = await db.collection('platform_credentials').findOne({ _id: 'google_places' });
  2550. if (!cred?.apiKey) return reply.code(400).send({ error: 'Google Places API key not configured — add it in Settings.' });
  2551. // Step 1: Geocode the location string to coordinates
  2552. let lat, lng;
  2553. try {
  2554. const geoRes = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
  2555. params: { address: location, key: cred.apiKey },
  2556. timeout: 10000,
  2557. });
  2558. const loc = geoRes.data.results?.[0]?.geometry?.location;
  2559. if (!loc) return reply.code(400).send({ error: `Could not geocode location: "${location}"` });
  2560. lat = loc.lat;
  2561. lng = loc.lng;
  2562. } catch (err) {
  2563. return reply.code(503).send({ error: 'Geocoding failed', detail: err.message });
  2564. }
  2565. // Step 2: Text Search for nearby businesses of the given type
  2566. try {
  2567. const query = businessType ? `${businessType} near ${location}` : location;
  2568. const searchRes = await axios.get('https://maps.googleapis.com/maps/api/place/textsearch/json', {
  2569. params: {
  2570. query,
  2571. location: `${lat},${lng}`,
  2572. radius: Math.min(radiusMeters, 50000),
  2573. key: cred.apiKey,
  2574. },
  2575. timeout: 10000,
  2576. });
  2577. const places = (searchRes.data.results || []).slice(0, 10);
  2578. if (!places.length) return { success: true, suggestions: [] };
  2579. // Step 3: Fetch website URLs for places that have them
  2580. const suggestions = [];
  2581. for (const place of places.slice(0, 8)) {
  2582. try {
  2583. const detailRes = await axios.get('https://maps.googleapis.com/maps/api/place/details/json', {
  2584. params: { place_id: place.place_id, fields: 'name,website,formatted_address,rating', key: cred.apiKey },
  2585. timeout: 8000,
  2586. });
  2587. const detail = detailRes.data.result || {};
  2588. suggestions.push({
  2589. name: detail.name || place.name,
  2590. websiteUrl: detail.website || null,
  2591. address: detail.formatted_address || '',
  2592. rating: detail.rating || null,
  2593. reason: `Local ${businessType || 'business'} near ${location}${detail.rating ? ` · ${detail.rating}★` : ''}`,
  2594. });
  2595. } catch {
  2596. suggestions.push({ name: place.name, websiteUrl: null, address: '', rating: null, reason: `Local ${businessType || 'business'} near ${location}` });
  2597. }
  2598. }
  2599. log.info({ action: 'discover_local_competitors', location, count: suggestions.length, outcome: 'success' });
  2600. return { success: true, suggestions };
  2601. } catch (err) {
  2602. return reply.code(503).send({ error: 'Google Places search failed', detail: err.message });
  2603. }
  2604. });
  2605. // Discover competitors automatically using AI + account profile context
  2606. app.post('/competitors/discover', async (request, reply) => {
  2607. const db = await getDb();
  2608. // Use the first account profile for business context
  2609. const profile = await db.collection('account_profiles').findOne({});
  2610. const contextParts = [];
  2611. if (profile) {
  2612. if (profile.businessName) contextParts.push(`Business: ${profile.businessName}`);
  2613. if (profile.description) contextParts.push(`Description: ${profile.description}`);
  2614. if (profile.industry) contextParts.push(`Industry: ${profile.industry}`);
  2615. if (profile.websiteUrl) contextParts.push(`Website: ${profile.websiteUrl}`);
  2616. if (profile.targetAudience) contextParts.push(`Target audience: ${profile.targetAudience}`);
  2617. }
  2618. if (!contextParts.length) {
  2619. return reply.code(400).send({ error: 'Set up at least one Account Profile in Settings before discovering competitors.' });
  2620. }
  2621. const system = 'You are a market research analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2622. const prompt = `Based on the following business profile, identify the top 5 direct competitors.
  2623. ${contextParts.join('\n')}
  2624. Return ONLY a JSON array of objects, e.g.:
  2625. [{"name":"Competitor Name","websiteUrl":"https://example.com","reason":"One sentence on why they compete directly"}]
  2626. Rules:
  2627. - Return real, existing businesses only.
  2628. - Include only direct competitors (same product/service category, same target audience).
  2629. - websiteUrl must be a valid https URL to the competitor's main website.
  2630. - No explanation outside the JSON array.`;
  2631. try {
  2632. const pconf = await getActiveProviderConfig();
  2633. const model = pconf.model;
  2634. let text = '';
  2635. if (pconf.provider === 'ollama') {
  2636. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2637. text = res.data.response;
  2638. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2639. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2640. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2641. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2642. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2643. text = res.data.choices[0]?.message?.content || '';
  2644. } else if (pconf.provider === 'gemini') {
  2645. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2646. const res = await axios.post(
  2647. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2648. { contents: buildGeminiContents(prompt, system) },
  2649. { timeout: 120000 },
  2650. );
  2651. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2652. } else {
  2653. return reply.code(400).send({ error: 'AI not configured' });
  2654. }
  2655. let suggestions = [];
  2656. try {
  2657. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2658. const parsed = JSON.parse(jsonStr);
  2659. if (!Array.isArray(parsed)) throw new Error();
  2660. suggestions = parsed
  2661. .filter((s) => s && typeof s.name === 'string' && typeof s.websiteUrl === 'string')
  2662. .slice(0, 5)
  2663. .map((s) => ({
  2664. name: s.name.trim(),
  2665. websiteUrl: s.websiteUrl.trim(),
  2666. reason: typeof s.reason === 'string' ? s.reason.trim() : '',
  2667. }));
  2668. } catch {
  2669. return reply.code(503).send({ error: 'AI returned invalid format — try again' });
  2670. }
  2671. log.info({ action: 'competitor_discover', count: suggestions.length, outcome: 'success' });
  2672. return { success: true, suggestions };
  2673. } catch (err) {
  2674. return reply.code(503).send({ error: 'Discovery failed', detail: err.message });
  2675. }
  2676. });
  2677. // List competitors
  2678. app.get('/competitors', async (request, reply) => {
  2679. const db = await getDb();
  2680. const list = await db.collection('competitors').find({}).sort({ createdAt: 1 }).toArray();
  2681. return list;
  2682. });
  2683. // Add competitor (max 2)
  2684. app.post('/competitors', async (request, reply) => {
  2685. const db = await getDb();
  2686. const count = await db.collection('competitors').countDocuments();
  2687. if (count >= 5) return reply.code(400).send({ error: 'Maximum 5 competitors allowed' });
  2688. const { name, websiteUrl, socialUrls = {} } = request.body || {};
  2689. if (!name || !websiteUrl) return reply.code(400).send({ error: 'name and websiteUrl are required' });
  2690. const now = new Date();
  2691. const result = await db.collection('competitors').insertOne({
  2692. name, websiteUrl, socialUrls, scrapedContent: [], aiSummary: '', keywords: [], lastScraped: null, createdAt: now, updatedAt: now,
  2693. });
  2694. const doc = await db.collection('competitors').findOne({ _id: result.insertedId });
  2695. return doc;
  2696. });
  2697. // Update competitor
  2698. app.put('/competitors/:id', async (request, reply) => {
  2699. const db = await getDb();
  2700. const { name, websiteUrl, socialUrls } = request.body || {};
  2701. const updates = { updatedAt: new Date() };
  2702. if (name !== undefined) updates.name = name;
  2703. if (websiteUrl !== undefined) updates.websiteUrl = websiteUrl;
  2704. if (socialUrls !== undefined) updates.socialUrls = socialUrls;
  2705. await db.collection('competitors').updateOne({ _id: new ObjectId(request.params.id) }, { $set: updates });
  2706. const doc = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2707. return doc;
  2708. });
  2709. // Delete competitor
  2710. app.delete('/competitors/:id', async (request, reply) => {
  2711. const db = await getDb();
  2712. await db.collection('competitors').deleteOne({ _id: new ObjectId(request.params.id) });
  2713. return { success: true };
  2714. });
  2715. // Scrape one competitor — returns jobId immediately, runs in background
  2716. app.post('/competitors/:id/scrape', async (request, reply) => {
  2717. const jobId = new ObjectId().toString();
  2718. activeScrapeJobs.set(jobId, { status: 'running', sources: 0, message: '' });
  2719. (async () => {
  2720. try {
  2721. const result = await runCompetitorScrape(request.params.id);
  2722. activeScrapeJobs.set(jobId, {
  2723. status: result.ok ? 'done' : 'failed',
  2724. sources: result.sources,
  2725. message: result.message,
  2726. });
  2727. } catch (err) {
  2728. activeScrapeJobs.set(jobId, { status: 'failed', sources: 0, message: err.message });
  2729. }
  2730. })();
  2731. return reply.code(202).send({ jobId });
  2732. });
  2733. // Poll scrape job status
  2734. app.get('/competitors/:id/scrape-status/:jobId', async (request, reply) => {
  2735. const job = activeScrapeJobs.get(request.params.jobId);
  2736. if (!job) return reply.code(404).send({ error: 'Job not found or expired' });
  2737. return job;
  2738. });
  2739. // Scrape all competitors (called by scheduler)
  2740. app.post('/competitors/scrape-all', async (request, reply) => {
  2741. const db = await getDb();
  2742. const all = await db.collection('competitors').find({}).toArray();
  2743. const results = [];
  2744. for (const c of all) {
  2745. const r = await runCompetitorScrape(c._id.toString());
  2746. results.push({ id: c._id.toString(), name: c.name, ...r });
  2747. }
  2748. return { success: true, results };
  2749. });
  2750. // Summarize competitor content with AI — returns structured analysis
  2751. app.post('/competitors/:id/summarize', async (request, reply) => {
  2752. const db = await getDb();
  2753. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2754. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2755. const content = (competitor.scrapedContent || []).map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 6000);
  2756. if (!content) return reply.code(400).send({ error: 'No scraped content to summarize' });
  2757. const system = 'You are a competitive intelligence analyst. Return only valid JSON with no explanation, no markdown code blocks.';
  2758. const prompt = `Analyse the following content from "${competitor.name}" and return a JSON object with exactly these fields:
  2759. {
  2760. "themes": ["3-5 main content topics or pillars they focus on"],
  2761. "tone": "one sentence describing their voice and communication style",
  2762. "positioning": "one sentence on how they position themselves in the market",
  2763. "gaps": ["2-3 topics or angles they ignore or handle poorly — opportunities for you"],
  2764. "moves": ["3 specific content angles you could use to stand out against them"],
  2765. "profile": {
  2766. "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)",
  2767. "keyFeatures": ["3-5 core product or service features they emphasise"],
  2768. "marketingChannels": ["2-4 social/marketing channels they actively use based on content"],
  2769. "targetCustomer": "one sentence describing their apparent ideal customer"
  2770. },
  2771. "prediction": {
  2772. "satisfiedWithPosition": <true if they appear content with their current position, false if they seem to be pushing for growth>,
  2773. "likelyNextMoves": ["2-3 strategic moves they will probably make based on current trajectory"],
  2774. "vulnerabilities": ["2-3 specific weaknesses or blind spots visible in their content"],
  2775. "retaliationTriggers": ["1-2 moves by a competitor that would most likely provoke a strong response from them"]
  2776. }
  2777. }
  2778. Content:
  2779. ${content}
  2780. Return ONLY the JSON object. No explanation, no markdown.`;
  2781. try {
  2782. const pconf = await getActiveProviderConfig();
  2783. const model = pconf.model;
  2784. let text = '';
  2785. if (pconf.provider === 'ollama') {
  2786. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 180000 });
  2787. text = res.data.response;
  2788. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2789. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2790. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2791. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2792. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 180000 });
  2793. text = res.data.choices[0]?.message?.content || '';
  2794. } else if (pconf.provider === 'gemini') {
  2795. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2796. const res = await axios.post(
  2797. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2798. { contents: buildGeminiContents(prompt, system) },
  2799. { timeout: 180000 },
  2800. );
  2801. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2802. } else {
  2803. return reply.code(400).send({ error: 'AI not configured' });
  2804. }
  2805. let aiAnalysis = null;
  2806. try {
  2807. const jsonStr = (text.match(/\{[\s\S]*\}/) || ['{}'])[0];
  2808. aiAnalysis = JSON.parse(jsonStr);
  2809. if (!Array.isArray(aiAnalysis.themes)) aiAnalysis.themes = [];
  2810. if (typeof aiAnalysis.tone !== 'string') aiAnalysis.tone = '';
  2811. if (typeof aiAnalysis.positioning !== 'string') aiAnalysis.positioning = '';
  2812. if (!Array.isArray(aiAnalysis.gaps)) aiAnalysis.gaps = [];
  2813. if (!Array.isArray(aiAnalysis.moves)) aiAnalysis.moves = [];
  2814. // Validate profile block
  2815. if (!aiAnalysis.profile || typeof aiAnalysis.profile !== 'object') aiAnalysis.profile = {};
  2816. if (typeof aiAnalysis.profile.pricing !== 'string') aiAnalysis.profile.pricing = '';
  2817. if (!Array.isArray(aiAnalysis.profile.keyFeatures)) aiAnalysis.profile.keyFeatures = [];
  2818. if (!Array.isArray(aiAnalysis.profile.marketingChannels)) aiAnalysis.profile.marketingChannels = [];
  2819. if (typeof aiAnalysis.profile.targetCustomer !== 'string') aiAnalysis.profile.targetCustomer = '';
  2820. // Validate prediction block
  2821. if (!aiAnalysis.prediction || typeof aiAnalysis.prediction !== 'object') aiAnalysis.prediction = {};
  2822. if (typeof aiAnalysis.prediction.satisfiedWithPosition !== 'boolean') aiAnalysis.prediction.satisfiedWithPosition = true;
  2823. if (!Array.isArray(aiAnalysis.prediction.likelyNextMoves)) aiAnalysis.prediction.likelyNextMoves = [];
  2824. if (!Array.isArray(aiAnalysis.prediction.vulnerabilities)) aiAnalysis.prediction.vulnerabilities = [];
  2825. if (!Array.isArray(aiAnalysis.prediction.retaliationTriggers)) aiAnalysis.prediction.retaliationTriggers = [];
  2826. } catch {
  2827. aiAnalysis = null;
  2828. }
  2829. if (!aiAnalysis) return reply.code(503).send({ error: 'AI returned invalid analysis format — try again' });
  2830. await db.collection('competitors').updateOne(
  2831. { _id: new ObjectId(request.params.id) },
  2832. { $set: { aiAnalysis, aiSummary: '', updatedAt: new Date() } },
  2833. );
  2834. return { success: true, aiAnalysis };
  2835. } catch (err) {
  2836. return reply.code(503).send({ error: 'Summarization failed', detail: err.message });
  2837. }
  2838. });
  2839. // Extract keywords from scraped content using AI (item 34)
  2840. app.post('/competitors/:id/extract-keywords', async (request, reply) => {
  2841. const db = await getDb();
  2842. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2843. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2844. const content = (competitor.scrapedContent || []).map((s) => s.text).join('\n\n').slice(0, 6000);
  2845. if (!content) return reply.code(400).send({ error: 'No scraped content to extract keywords from' });
  2846. const system = 'You are an SEO and content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  2847. 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:
  2848. - informational: user wants to learn ("how to", "what is", "guide", "tips")
  2849. - commercial: user is evaluating options ("best", "vs", "review", "top", "alternative")
  2850. - transactional: user is ready to act ("buy", "free", "pricing", "download", "get started")
  2851. - navigational: user is searching for a specific brand or tool by name
  2852. Content:
  2853. ${content}
  2854. Return ONLY a JSON array, e.g.:
  2855. [{"term": "project management software", "intent": "commercial"}, {"term": "how to manage tasks", "intent": "informational"}]
  2856. No explanation, no markdown.`;
  2857. try {
  2858. const pconf = await getActiveProviderConfig();
  2859. const model = pconf.model;
  2860. let text = '';
  2861. if (pconf.provider === 'ollama') {
  2862. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2863. text = res.data.response;
  2864. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2865. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2866. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2867. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2868. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2869. text = res.data.choices[0]?.message?.content || '';
  2870. } else if (pconf.provider === 'gemini') {
  2871. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2872. const res = await axios.post(
  2873. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2874. { contents: buildGeminiContents(prompt, system) },
  2875. { timeout: 120000 },
  2876. );
  2877. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2878. } else {
  2879. return reply.code(400).send({ error: 'AI not configured' });
  2880. }
  2881. const VALID_INTENTS = new Set(['informational', 'commercial', 'transactional', 'navigational']);
  2882. let keywords = [];
  2883. try {
  2884. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  2885. const parsed = JSON.parse(jsonStr);
  2886. if (!Array.isArray(parsed)) throw new Error();
  2887. const now = new Date();
  2888. keywords = parsed
  2889. .filter((k) => k && typeof k.term === 'string' && k.term.trim())
  2890. .slice(0, 20)
  2891. .map((k) => ({
  2892. term: k.term.trim(),
  2893. intent: VALID_INTENTS.has(k.intent) ? k.intent : 'informational',
  2894. extractedAt: now,
  2895. }));
  2896. } catch {
  2897. keywords = [];
  2898. }
  2899. await db.collection('competitors').updateOne(
  2900. { _id: new ObjectId(request.params.id) },
  2901. { $set: { keywords, updatedAt: new Date() } },
  2902. );
  2903. return { success: true, keywords };
  2904. } catch (err) {
  2905. return reply.code(503).send({ error: 'Keyword extraction failed', detail: err.message });
  2906. }
  2907. });
  2908. // Analyse content gaps — compare competitor keywords against user's hashtag_stats
  2909. app.post('/competitors/:id/analyze-gaps', async (request, reply) => {
  2910. const db = await getDb();
  2911. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2912. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2913. const keywords = (competitor.keywords || []);
  2914. if (!keywords.length) return reply.code(400).send({ error: 'Extract keywords first before analysing gaps' });
  2915. const hashtagDocs = await db.collection('hashtag_stats')
  2916. .find({ accountKey: { $exists: true } }, { projection: { _id: 0, hashtag: 1 } })
  2917. .toArray();
  2918. const hashtagStatsEmpty = hashtagDocs.length === 0;
  2919. // Deduplicate across accounts — same hashtag used by any account counts as covered
  2920. const uniqueTags = [...new Set(hashtagDocs.map((h) => h.hashtag).filter(Boolean))];
  2921. const hashtagTexts = uniqueTags.map((tag) => ({ id: tag, text: tag.replace(/^#/, '').toLowerCase() }));
  2922. const INTENT_ORDER = { transactional: 0, commercial: 1, informational: 2, navigational: 3 };
  2923. function findMatchingHashtags(term) {
  2924. const words = term.toLowerCase().split(/\s+/).filter((w) => w.length >= 4);
  2925. return hashtagTexts
  2926. .filter(({ text }) => words.some((w) => text.includes(w)))
  2927. .map(({ id }) => id);
  2928. }
  2929. const gaps = [];
  2930. const covered = [];
  2931. for (const kw of keywords) {
  2932. const term = typeof kw === 'string' ? kw : kw.term;
  2933. const intent = typeof kw === 'string' ? 'informational' : (kw.intent || 'informational');
  2934. const matched = findMatchingHashtags(term);
  2935. if (matched.length) {
  2936. covered.push({ term, intent, matchedHashtags: matched.slice(0, 4) });
  2937. } else {
  2938. gaps.push({ term, intent });
  2939. }
  2940. }
  2941. gaps.sort((a, b) => (INTENT_ORDER[a.intent] ?? 99) - (INTENT_ORDER[b.intent] ?? 99));
  2942. const gapAnalysis = { gaps, covered, totalKeywords: keywords.length, hashtagStatsEmpty, lastAnalyzed: new Date() };
  2943. await db.collection('competitors').updateOne(
  2944. { _id: new ObjectId(request.params.id) },
  2945. { $set: { gapAnalysis, updatedAt: new Date() } },
  2946. );
  2947. return { success: true, ...gapAnalysis };
  2948. });
  2949. // Detect and classify market signals from latest scraped content
  2950. app.post('/competitors/:id/detect-signals', async (request, reply) => {
  2951. const db = await getDb();
  2952. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  2953. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  2954. const recentContent = (competitor.scrapedContent || []).slice(0, 10);
  2955. if (!recentContent.length) return reply.code(400).send({ error: 'Scrape first before detecting signals' });
  2956. const contentText = recentContent.map((s) => `[${s.source}] ${s.text}`).join('\n\n').slice(0, 4000);
  2957. const baseline = competitor.aiAnalysis
  2958. ? `Previous profile — Themes: ${(competitor.aiAnalysis.themes || []).join(', ')}. Tone: ${competitor.aiAnalysis.tone || 'unknown'}.`
  2959. : 'No prior analysis available.';
  2960. const system = 'You are a competitive intelligence analyst specialising in market signal detection. Return only valid JSON with no explanation, no markdown.';
  2961. const prompt = `Analyse the latest content from competitor "${competitor.name}" and detect any notable changes or strategic signals.
  2962. Baseline context:
  2963. ${baseline}
  2964. Latest scraped content:
  2965. ${contentText}
  2966. Classify any changes you detect. Use these signal types:
  2967. - topic_expansion: new content themes or topics not previously seen
  2968. - tone_shift: measurable change in communication style or voice
  2969. - campaign_launch: evidence of a new marketing campaign or product promotion
  2970. - pricing_change: any mention of new pricing, offers, or discounts
  2971. - market_entry: signs of entering a new platform, audience, or geography
  2972. - competitive_aggression: direct competitor comparisons, attack marketing, or poaching language
  2973. - frequency_change: evidence of significantly more or less content activity
  2974. Return ONLY a JSON array (empty array [] if no significant signals):
  2975. [{"type":"<type>","description":"<one sentence describing the specific change>","severity":"<low|medium|high>"}]
  2976. Severity guide: high = major strategic shift, medium = notable change worth monitoring, low = minor or uncertain change.`;
  2977. try {
  2978. const pconf = await getActiveProviderConfig();
  2979. const model = pconf.model;
  2980. let text = '';
  2981. if (pconf.provider === 'ollama') {
  2982. const res = await axios.post(`${pconf.endpoint}/api/generate`, { model, prompt, system, stream: false }, { timeout: 120000 });
  2983. text = res.data.response;
  2984. } else if (pconf.provider === 'openai' || pconf.provider === 'groq') {
  2985. if (!pconf.apiKey) return reply.code(503).send({ error: `${pconf.provider} API key not configured` });
  2986. const res = await axios.post(`${pconf.baseUrl}/chat/completions`, {
  2987. model, messages: buildOpenAIMessages(prompt, system), stream: false,
  2988. }, { headers: { Authorization: `Bearer ${pconf.apiKey}` }, timeout: 120000 });
  2989. text = res.data.choices[0]?.message?.content || '';
  2990. } else if (pconf.provider === 'gemini') {
  2991. if (!pconf.apiKey) return reply.code(503).send({ error: 'Gemini API key not configured' });
  2992. const res = await axios.post(
  2993. `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${pconf.apiKey}`,
  2994. { contents: buildGeminiContents(prompt, system) },
  2995. { timeout: 120000 },
  2996. );
  2997. text = res.data.candidates?.[0]?.content?.parts?.[0]?.text || '';
  2998. } else {
  2999. return reply.code(400).send({ error: 'AI not configured' });
  3000. }
  3001. const VALID_TYPES = new Set(['topic_expansion', 'tone_shift', 'campaign_launch', 'pricing_change', 'market_entry', 'competitive_aggression', 'frequency_change']);
  3002. const VALID_SEVERITIES = new Set(['low', 'medium', 'high']);
  3003. let signals = [];
  3004. try {
  3005. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3006. const parsed = JSON.parse(jsonStr);
  3007. if (!Array.isArray(parsed)) throw new Error();
  3008. const now = new Date();
  3009. signals = parsed
  3010. .filter((s) => s && VALID_TYPES.has(s.type) && typeof s.description === 'string')
  3011. .slice(0, 8)
  3012. .map((s) => ({
  3013. type: s.type,
  3014. description: s.description.trim(),
  3015. severity: VALID_SEVERITIES.has(s.severity) ? s.severity : 'medium',
  3016. detectedAt: now,
  3017. }));
  3018. } catch {
  3019. signals = [];
  3020. }
  3021. await db.collection('competitors').updateOne(
  3022. { _id: new ObjectId(request.params.id) },
  3023. { $set: { signals, contentChanged: false, updatedAt: new Date() } },
  3024. );
  3025. log.info({ action: 'detect_signals', competitorId: request.params.id, count: signals.length, outcome: 'success' });
  3026. return { success: true, signals };
  3027. } catch (err) {
  3028. return reply.code(503).send({ error: 'Signal detection failed', detail: err.message });
  3029. }
  3030. });
  3031. // Generate a 5-post content roadmap from competitor keywords and gaps
  3032. app.post('/competitors/:id/content-roadmap', async (request, reply) => {
  3033. const db = await getDb();
  3034. const competitor = await db.collection('competitors').findOne({ _id: new ObjectId(request.params.id) });
  3035. if (!competitor) return reply.code(404).send({ error: 'Competitor not found' });
  3036. const keywords = (competitor.keywords || []);
  3037. const hasKeywords = keywords.length > 0;
  3038. const hasContent = (competitor.scrapedContent || []).length > 0;
  3039. if (!hasKeywords && !hasContent) return reply.code(400).send({ error: 'Extract keywords first before generating a roadmap' });
  3040. const kwList = hasKeywords
  3041. ? keywords.map((k) => (typeof k === 'string' ? k : k.term)).join(', ')
  3042. : '';
  3043. const gaps = competitor.aiAnalysis?.gaps || [];
  3044. const moves = competitor.aiAnalysis?.moves || [];
  3045. const gapsSection = gaps.length ? `\nCompetitor gaps/weaknesses:\n${gaps.map((g) => `- ${g}`).join('\n')}` : '';
  3046. const movesSection = moves.length ? `\nSuggested differentiation angles:\n${moves.map((m) => `- ${m}`).join('\n')}` : '';
  3047. const kwSection = kwList ? `\nCompetitor's keywords: ${kwList}` : '';
  3048. const system = 'You are a content strategist. Return only valid JSON with no explanation, no markdown code blocks.';
  3049. const prompt = `Create a 5-post content roadmap to compete against "${competitor.name}".
  3050. ${kwSection}${gapsSection}${movesSection}
  3051. Generate 5 post ideas that exploit their weaknesses and differentiate clearly. For each post return:
  3052. - topic: short topic name, max 8 words
  3053. - headline: an engaging opening line or hook ready to use as post content (1-2 sentences)
  3054. - keywords: array of 2-3 keywords from the competitor's list to target (use exact terms where available)
  3055. - rationale: one sentence on why this post wins against ${competitor.name}
  3056. Return ONLY a JSON array:
  3057. [{"topic":"...","headline":"...","keywords":["..."],"rationale":"..."}]
  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: 180000 });
  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: 180000 });
  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: 180000 },
  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. let roadmap = [];
  3084. try {
  3085. const jsonStr = (text.match(/\[[\s\S]*\]/) || ['[]'])[0];
  3086. const parsed = JSON.parse(jsonStr);
  3087. if (!Array.isArray(parsed)) throw new Error();
  3088. roadmap = parsed
  3089. .filter((p) => p && typeof p.topic === 'string' && typeof p.headline === 'string')
  3090. .slice(0, 5)
  3091. .map((p) => ({
  3092. topic: p.topic.trim(),
  3093. headline: p.headline.trim(),
  3094. keywords: Array.isArray(p.keywords) ? p.keywords.filter((k) => typeof k === 'string').slice(0, 3) : [],
  3095. rationale: typeof p.rationale === 'string' ? p.rationale.trim() : '',
  3096. }));
  3097. } catch {
  3098. roadmap = [];
  3099. }
  3100. if (!roadmap.length) return reply.code(503).send({ error: 'AI returned invalid roadmap format — try again' });
  3101. await db.collection('competitors').updateOne(
  3102. { _id: new ObjectId(request.params.id) },
  3103. { $set: { contentRoadmap: roadmap, updatedAt: new Date() } },
  3104. );
  3105. return { success: true, contentRoadmap: roadmap };
  3106. } catch (err) {
  3107. return reply.code(503).send({ error: 'Roadmap generation failed', detail: err.message });
  3108. }
  3109. });
  3110. module.exports = app;