[9/12/2026 10:08 AM] Arun Roy: /** * AXCIMA SMART YIELD PLATFORM - SERVER.JS */ import express from "express"; import path from "path"; import fs from "fs"; import crypto from "crypto"; import dotenv from "dotenv"; import { getApps, initializeApp } from "firebase-admin/app"; import { getAuth } from "firebase-admin/auth"; import { drizzle } from "drizzle-orm/node-postgres"; import { eq, relations } from "drizzle-orm"; import { pgTable, serial, text, integer, decimal, timestamp, boolean, jsonb } from "drizzle-orm/pg-core"; import pg from "pg"; const { Pool } = pg; dotenv.config(); if (fs.existsSync(path.join(process.cwd(), ".env"))) { dotenv.config({ path: path.join(process.cwd(), ".env") }); } // 1. FIREBASE CONFIGURATION let firebaseConfig = { projectId: "folkloric-sun-gsx2c", appId: "1:1085997961879:web:ba7bbd805be761cfe50fd2", apiKey: "AIzaSyBIKd3wiLhgbWQsJyWlFpJ0wvCiJIFVhAc", authDomain: "folkloric-sun-gsx2c.firebaseapp.com", firestoreDatabaseId: "ai-studio-eb8831e2-c7e0-4e30-9967-ccf31f09c485", storageBucket: "folkloric-sun-gsx2c.firebasestorage.app", messagingSenderId: "1085997961879", oAuthClientId: "1085997961879-2tj99r9fnk8vdfoe4v6mj6sle7dpcq6p.apps.googleusercontent.com" }; try { const configPath = path.join(process.cwd(), "firebase-applet-config.json"); if (fs.existsSync(configPath)) { const rawData = fs.readFileSync(configPath, "utf-8"); firebaseConfig = { ...firebaseConfig, ...JSON.parse(rawData) }; } } catch (e) { console.log("[Firebase] Notice: Using built-in configuration profile"); } if (!getApps().length) { initializeApp({ projectId: firebaseConfig.projectId, }); } const adminAuth = getAuth(); // 2. DATABASE SCHEMA & CONNECTION (POSTGRESQL / DRIZZLE) export const users = pgTable("users", { id: serial("id").primaryKey(), uid: text("uid").notNull().unique(), email: text("email").notNull().unique(), phone: text("phone"), fullName: text("full_name"), nickname: text("nickname"), role: text("role").default("USER").notNull(), referralCode: text("referral_code").unique(), referredById: integer("referred_by_id"), status: text("status").default("ACTIVE").notNull(), createdAt: timestamp("created_at").defaultNow(), updatedAt: timestamp("updated_at").defaultNow(), }); export const investmentPlans = pgTable("investment_plans", { id: serial("id").primaryKey(), name: text("name").notNull(), description: text("description"), minAmount: decimal("min_amount").notNull(), maxAmount: decimal("max_amount"), durationDays: integer("duration_days").notNull(), riskLevel: text("risk_level").default("MEDIUM").notNull(), feesPercent: decimal("fees_percent").default("0").notNull(), projectedReturn: text("projected_return"), status: text("status").default("ACTIVE").notNull(), createdAt: timestamp("created_at").defaultNow(), }); let poolInstance = null; const createDbPool = () => { if (!poolInstance) { const connectionString = process.env.DATABASE_URL || process.env.POSTGRES_URL; if (connectionString) { const isLocal = connectionString.includes("localhost") || connectionString.includes("127.0.0.1"); const requiresSsl = !isLocal connectionString.includes("sslmode=require") process.env.PGSSLMODE === "require"; poolInstance = new Pool({ connectionString, max: 10, connectionTimeoutMillis: 15000, ssl: requiresSsl ? { rejectUnauthorized: false } : undefined, }); } else { poolInstance = new Pool({ host: process.env.SQL_HOST || "localhost", user: process.env.SQL_USER || "postgres", password: process.env.SQL_PASSWORD || "", database: process.env.SQL_DB_NAME || "postgres", port: process.env.SQL_PORT ? Number(process.env.SQL_PORT) : 5432, max: 10, connectionTimeoutMillis: 15000, }); } poolInstance.on("error", (err) => { console.log("[DB] Notice:", err.message); }); } return poolInstance; }; const pool = createDbPool(); export const db = drizzle(pool, { schema: { users, investmentPlans } }); [9/12/2026 10:08 AM] Arun Roy: // 3. BREVO TRANSACTIONAL EMAIL SERVICE export function getBrevoApiKey() { return process.env.BREVO_API_KEY; } export function getDefaultSender() { return { email: process.env.BREVO_SENDER_EMAIL || "noreply@axcima.com", name: process.env.BREVO_SENDER_NAME || "AXCIMA VIP System" }; } export async function checkBrevoStatus() { const apiKey = getBrevoApiKey(); const defaultSender = getDefaultSender(); if (!apiKey apiKey.trim() === "" apiKey === "MY_BREVO_API_KEY") { return { configured: false, senderEmail: defaultSender.email, senderName: defaultSender.name, liveMode: false, message: "BREVO_API_KEY is not configured. Running in simulation mode." }; } try { const res = await fetch("https://api.brevo.com/v3/account", { headers: { "api-key": apiKey, "Accept": "application/json" } }); if (res.ok) { const data = await res.json(); return { configured: true, senderEmail: defaultSender.email, senderName: defaultSender.name, account: { email: data.email, firstName: data.firstName, lastName: data.lastName, companyName: data.companyName, plan: data.plan }, liveMode: true, message: Connected successfully to Brevo account: ${data.email} }; } else { const err = await res.json().catch(() => ({})); return { configured: false, senderEmail: defaultSender.email, senderName: defaultSender.name, liveMode: false, message: err.message || Brevo API HTTP Error ${res.status} }; } } catch (err) { return { configured: false, senderEmail: defaultSender.email, senderName: defaultSender.name, liveMode: false, message: err.message || "Network error checking Brevo account" }; } } export async function sendBrevoEmail(options) { const apiKey = getBrevoApiKey(); const defaultSender = getDefaultSender(); let recipients = []; if (typeof options.to === "string") { recipients = [{ email: options.to }]; } else if (Array.isArray(options.to)) { recipients = options.to.map(r => typeof r === "string" ? { email: r } : r); } else { recipients = [options.to]; } const sender = { email: options.senderEmail || defaultSender.email, name: options.senderName || defaultSender.name }; const payload = { sender, to: recipients, subject: options.subject, htmlContent: options.htmlContent, ...(options.textContent ? { textContent: options.textContent } : {}), ...(options.replyTo ? { replyTo: options.replyTo } : {}), ...(options.tags ? { tags: options.tags } : {}) }; if (!apiKey apiKey.trim() === "" apiKey === "MY_BREVO_API_KEY") { console.log([Brevo Simulation] Email to ${recipients.map(r => r.email).join(", ")} | Subject: ${options.subject}); return { success: true, messageId: , message: "Email simulated successfully (BREVO_API_KEY not configured)" }; } const response = await fetch("https://api.brevo.com/v3/smtp/email", { method: "POST", headers: { "api-key": apiKey, "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify(payload) }); const data = await response.json(); if (!response.ok) { throw new Error(data.message || Brevo email sending failed: ${response.status}); } return { success: true, messageId: data.messageId, message: "Email sent successfully via Brevo" }; } export function buildOtpEmailHtml(otpCode, purpose, userName) { return `
[9/12/2026 10:08 AM] Arun Roy:

AXCIMA

Security & Verification Service

Hello ${userName || "Valued Member"},

Your one-time security code for ${purpose || "Account Verification"} is:

${otpCode}

This code will expire in 10 minutes. For your security, never share this OTP with anyone, including AXCIMA staff.

; } export function buildWelcomeEmailHtml(userName, uid, email) { return

Welcome to AXCIMA

Your High-Yield Smart Wealth Journey Begins

Dear ${userName || "Investor"},

Congratulations on creating your AXCIMA portfolio account! You now have access to verified daily yield investments, instant deposit channels, and automated compounding returns.

Member UID: ${uid || "AX-VIP"}
Registered Email: ${email}
; } export function buildDepositEmailHtml(userName, amount, channel, utrRef) { return

Deposit Approved & Credited

Dear ${userName || "Investor"},

Your deposit of ₹${Number(amount).toLocaleString("en-IN")} via ${channel || "UPI"} has been verified and added to your wallet balance.

Reference / UTR: ${utrRef || "REF-" + Date.now()}

; } export function buildWithdrawalEmailHtml(userName, amount, netReceive, bankInfo, txnId) { return
[9/12/2026 10:08 AM] Arun Roy:

Payout Dispatched to Bank

Dear ${userName || "Investor"},

Your withdrawal of ₹${Number(netReceive || amount).toLocaleString("en-IN")} has been processed to your bank: ${bankInfo}.

Transaction Ref: ${txnId || "TXN-" + Date.now()}

`; } // 4. MAIN EXPRESS SERVER async function startServer() { const app = express(); const isCloudRunDev = Boolean(process.env.K_SERVICE || process.env.DISABLE_HMR); const PORT = (!isCloudRunDev && process.env.PORT) ? process.env.PORT : 3000; app.use(express.json()); const requireAuth = async (req, res, next) => { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith("Bearer ")) { return res.status(401).json({ error: "Unauthorized: Missing token" }); } const token = authHeader.split("Bearer ")[1]; try { const decodedToken = await adminAuth.verifyIdToken(token); req.user = decodedToken; next(); } catch (error) { console.error("[Auth] Firebase token validation error:", error.message); return res.status(401).json({ error: "Unauthorized: Invalid token" }); } }; app.get("/api/health", (req, res) => { res.json({ status: "ok", server: "AXCIMA Smart Yield Platform", uptime: process.uptime(), timestamp: new Date().toISOString() }); }); app.get("/api/details", async (req, res) => { const brevoInfo = await checkBrevoStatus().catch(e => ({ configured: false, error: e.message })); res.json({ application: "AXCIMA Smart Yield Platform", file: "server.js", mode: process.env.NODE_ENV || "development", port: PORT, firebase: { projectId: firebaseConfig.projectId, authDomain: firebaseConfig.authDomain, storageBucket: firebaseConfig.storageBucket, initialized: getApps().length > 0 }, brevo: brevoInfo, database: { type: "PostgreSQL", configured: Boolean(process.env.DATABASE_URL process.env.POSTGRES_URL process.env.SQL_HOST) } }); }); app.get("/api/user/profile", requireAuth, async (req, res) => { try { let userList = await db.select().from(users).where(eq(users.uid, req.user.uid)); if (userList.length === 0) { const newUser = await db.insert(users).values({ uid: req.user.uid, email: req.user.email || "", fullName: req.user.name || "User", }).returning(); return res.json(newUser[0]); } return res.json(userList[0]); } catch (e) { console.error("[DB Error] user/profile:", e.message); res.status(500).json({ error: "Database Error", details: e.message }); } }); app.get("/api/investments/plans", async (req, res) => { try { const plans = await db.select().from(investmentPlans); res.json(plans); } catch (e) { res.status(500).json({ error: "Database Error", details: e.message }); } }); app.get("/api/brevo/status", async (req, res) => { try { const status = await checkBrevoStatus(); res.json(status); } catch (err) { res.status(500).json({ configured: false, error: err?.message }); } }); app.post("/api/brevo/send-email", async (req, res) => { try { const { to, toName, subject, htmlContent, textContent, senderName, senderEmail, replyTo, tags } = req.body; if (!to !subject !htmlContent) { [9/12/2026 10:08 AM] Arun Roy: return res.status(400).json({ error: "Missing required fields" }); } const result = await sendBrevoEmail({ to: typeof to === "string" ? { email: to, name: toName || "Investor" } : to, subject, htmlContent, textContent, senderName, senderEmail, replyTo, tags }); res.json(result); } catch (err) { res.status(500).json({ success: false, error: err?.message }); } }); app.post("/api/brevo/send-otp", async (req, res) => { try { const { email, otpCode, purpose, userName } = req.body; if (!email || !otpCode) { return res.status(400).json({ error: "Email and otpCode are required" }); } const htmlContent = buildOtpEmailHtml(otpCode, purpose, userName); const subject = [AXCIMA] Security Code: ${otpCode} - ${purpose || "Verification"}; const result = await sendBrevoEmail({ to: { email, name: userName || "Valued Member" }, subject, htmlContent, tags: ["otp", "security"] }); res.json(result); } catch (err) { res.status(500).json({ success: false, error: err?.message }); } }); app.post("/api/brevo/send-welcome", async (req, res) => { try { const { email, userName, uid } = req.body; if (!email) return res.status(400).json({ error: "Email is required" }); const htmlContent = buildWelcomeEmailHtml(userName "Investor", uid "AX-VIP", email); const subject = "Welcome to AXCIMA Smart Yield Platform!"; const result = await sendBrevoEmail({ to: { email, name: userName || "Investor" }, subject, htmlContent, tags: ["welcome", "onboarding"] }); res.json(result); } catch (err) { res.status(500).json({ success: false, error: err?.message }); } }); app.post("/api/brevo/send-deposit-alert", async (req, res) => { try { const { email, userName, amount, channel, utrRef } = req.body; if (!email || !amount) return res.status(400).json({ error: "Email and amount are required" }); const htmlContent = buildDepositEmailHtml(userName, amount, channel, utrRef); const subject = [AXCIMA] Deposit of ₹${Number(amount).toLocaleString("en-IN")} Approved & Credited!; const result = await sendBrevoEmail({ to: { email, name: userName || "Investor" }, subject, htmlContent, tags: ["deposit", "transaction"] }); res.json(result); } catch (err) { res.status(500).json({ success: false, error: err?.message }); } }); app.post("/api/brevo/send-withdrawal-alert", async (req, res) => { try { const { email, userName, amount, netReceive, bankInfo, txnId } = req.body; if (!email || !amount) return res.status(400).json({ error: "Email and amount are required" }); const htmlContent = buildWithdrawalEmailHtml(userName, amount, netReceive, bankInfo, txnId); const subject = [AXCIMA] Payout of ₹${Number(netReceive || amount).toLocaleString("en-IN")} Dispatched to Bank; const result = await sendBrevoEmail({ to: { email, name: userName || "Investor" }, subject, htmlContent, tags: ["withdrawal", "payout"] }); res.json(result); } catch (err) { res.status(500).json({ success: false, error: err?.message }); } }); const serveStaticFiles = () => { let distPath = path.join(process.cwd(), "dist"); if (fs.existsSync(distPath)) { app.use(express.static(distPath)); app.get("*", (req, res) => { const indexPath = path.join(distPath, "index.html"); if (fs.existsSync(indexPath)) { res.sendFile(indexPath); } else { res.status(404).send("Application index.html not found. Please run 'npm run build'."); } }); } else { app.get("*", (req, res) => { res.status(503).send("

AXCIMA Server Online

Frontend assets not found.

"); }); } }; [9/12/2026 10:08 AM] Arun Roy: const isProduction = process.env.NODE_ENV === "production" || Boolean(process.env.PASSENGER_APP_ENV); if (!isProduction) { try { const { createServer: createViteServer } = await import("vite"); const vite = await createViteServer({ server: { middlewareMode: true }, appType: "s Comments for Axcima Invest https://axcima.com Sat, 12 Sep 2026 02:42:29 +0000 hourly 1 https://wordpress.org/?v=7.1.2 Comment on Hello world! by A WordPress Commenter https://axcima.com/hello-world/#comment-1 Sat, 12 Sep 2026 02:42:29 +0000 https://axcima.com/?p=1#comment-1 Hi, this is a comment.
To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
Commenter avatars come from Gravatar.

]]>