Compare commits

..

4 Commits

Author SHA1 Message Date
9190840c48 fix(wa-service): use correct API endpoint wa.wibudev.com with GET method
- Change API URL from otp.wibudev.com to wa.wibudev.com
  - otp.wibudev.com is dashboard UI, not API endpoint
  - wa.wibudev.com/code is the correct API endpoint

- Change method from POST to GET
  - API expects GET request with query params
  - Add Authorization header with Bearer token
  - API returns { status: 'success', id: '...' }

- Update .env.local:
  - WIBU_WA_API_URL=https://wa.wibudev.com

Tested with curl:
✓ GET https://wa.wibudev.com/code?nom=...&text=...
✓ Authorization: Bearer <API_KEY>
✓ Response: {"status":"success","id":"..."}

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-03-05 12:12:59 +08:00
781d125d4c feat(auth): migrate WhatsApp OTP to otp.wibudev.com with API Key authentication
- Create new wa-service.ts helper library
  - sendWhatsAppOtp(): Send OTP via otp.wibudev.com with Bearer token auth
  - sendWhatsAppOtpLegacy(): Deprecated legacy function for backward compat
  - Proper error handling and response validation

- Update all auth routes to use new WA service:
  - login/route.ts: Use sendWhatsAppOtp for login OTP
  - register/route.ts: Use sendWhatsAppOtp for registration OTP
  - resend/route.ts: Use sendWhatsAppOtp for resend OTP
  - send-otp-register/route.ts: Use sendWhatsAppOtp for registration

- Add environment variables to .env.local:
  - WIBU_WA_API_KEY: JWT token for authentication
  - WIBU_WA_API_URL: https://otp.wibudev.com

Benefits:
✓ Secure authentication with JWT API Key
✓ Centralized WA service for all OTP sending
✓ Better error handling and logging
✓ Consistent API response format
✓ Easy to maintain and extend

API Key Info:
- Name: website-desa-darmasaba
- Description: untuk website desa darmasaba
- Expiration: Feb 12, 2116
- Issued: Mar 05, 2026

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-03-05 12:07:58 +08:00
144ac37e12 fix(public-apbdes): fix realisasi display on public APBDes page
- Fix types.ts transformAPBDesData to map totalRealisasi → realisasi
  - Backend returns totalRealisasi, frontend expects realisasi
  - Add fallback to use item.realisasi if totalRealisasi not available

- Fix grafikRealisasi.tsx to use realisasi field
  - Update Summary component to use i.realisasi || i.totalRealisasi
  - Update total calculation to use realisasi field

- Fix apbDesaTable.tsx to use realisasi field
  - Update total calculation to use item.realisasi

- Fix apbDesaProgress.tsx to use realisasi field
  - Update calcTotal to use item.realisasi with fallback

Root cause: Backend Prisma schema uses 'totalRealisasi' field, but public
page components were expecting 'realisasi' field.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-03-05 11:27:28 +08:00
f90477ed63 fix(apbdes-edit): preserve realisasi data when editing APBDes
- Fix backend updt.ts to preserve realisasiItems from old items
  - Load existing items with realisasiItems before delete
  - Re-create realisasiItems for new items based on kode match
  - Recalculate totalRealisasi, selisih, persentase after restore

- Update frontend state to handle realisasi fields
  - Add realisasi, selisih, persentase to ApbdesItemSchema
  - Fix edit.load() to map totalRealisasi → realisasi
  - Fix edit.update() to omit calculated fields when sending to backend

- Update edit page.tsx to display realisasi data
  - Fix load data to use item.totalRealisasi (not item.realisasi)
  - Add Realisasi, Selisih, % columns to items table
  - Update handleAddItem and handleReset to preserve realisasi fields

Root cause: Backend was resetting totalRealisasi=0 for all items on update,
and frontend was accessing wrong field name (realisasi vs totalRealisasi)

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-03-05 11:20:45 +08:00
12 changed files with 331 additions and 70 deletions

View File

@@ -5,13 +5,17 @@ import { toast } from "react-toastify";
import { proxy } from "valtio";
import { z } from "zod";
// --- Zod Schema untuk APBDes Item (tanpa field kalkulasi) ---
// --- Zod Schema untuk APBDes Item (dengan field kalkulasi) ---
const ApbdesItemSchema = z.object({
kode: z.string().min(1, "Kode wajib diisi"),
uraian: z.string().min(1, "Uraian wajib diisi"),
anggaran: z.number().min(0, "Anggaran tidak boleh negatif"),
level: z.number().int().min(1).max(3),
tipe: z.enum(['pendapatan', 'belanja', 'pembiayaan']).nullable().optional(),
// Field kalkulasi dari realisasiItems (auto-calculated di backend)
realisasi: z.number().min(0).default(0),
selisih: z.number().default(0),
persentase: z.number().default(0),
});
const ApbdesFormSchema = z.object({
@@ -35,7 +39,7 @@ const defaultApbdesForm = {
items: [] as z.infer<typeof ApbdesItemSchema>[],
};
// --- Helper: Normalize item (tanpa kalkulasi, backend yang hitung) ---
// --- Helper: Normalize item (dengan field kalkulasi) ---
function normalizeItem(item: Partial<z.infer<typeof ApbdesItemSchema>>): z.infer<typeof ApbdesItemSchema> {
return {
kode: item.kode || "",
@@ -43,6 +47,9 @@ function normalizeItem(item: Partial<z.infer<typeof ApbdesItemSchema>>): z.infer
anggaran: item.anggaran ?? 0,
level: item.level || 1,
tipe: item.tipe ?? null,
realisasi: item.realisasi ?? 0,
selisih: item.selisih ?? 0,
persentase: item.persentase ?? 0,
};
}
@@ -248,6 +255,9 @@ const apbdes = proxy({
kode: item.kode,
uraian: item.uraian,
anggaran: item.anggaran,
realisasi: item.totalRealisasi || 0,
selisih: item.selisih || 0,
persentase: item.persentase || 0,
level: item.level,
tipe: item.tipe || 'pendapatan',
})),
@@ -275,11 +285,24 @@ const apbdes = proxy({
try {
this.loading = true;
// Include the ID in the request body
// Omit realisasi, selisih, persentase karena itu calculated fields di backend
const requestData = {
...parsed.data,
id: this.id, // Add the ID to the request body
tahun: parsed.data.tahun,
name: parsed.data.name,
deskripsi: parsed.data.deskripsi,
jumlah: parsed.data.jumlah,
imageId: parsed.data.imageId,
fileId: parsed.data.fileId,
id: this.id,
items: parsed.data.items.map(item => ({
kode: item.kode,
uraian: item.uraian,
anggaran: item.anggaran,
level: item.level,
tipe: item.tipe ?? null,
})),
};
const res = await (ApiFetch.api.landingpage.apbdes as any)[this.id].put(requestData);
if (res.data?.success) {

View File

@@ -44,6 +44,9 @@ type ItemForm = {
anggaran: number;
level: number;
tipe: 'pendapatan' | 'belanja' | 'pembiayaan';
realisasi?: number;
selisih?: number;
persentase?: number;
};
function EditAPBDes() {
@@ -72,6 +75,9 @@ function EditAPBDes() {
anggaran: 0,
level: 1,
tipe: 'pendapatan',
realisasi: 0,
selisih: 0,
persentase: 0,
});
// Simpan data original untuk reset form
@@ -125,9 +131,9 @@ function EditAPBDes() {
kode: item.kode,
uraian: item.uraian,
anggaran: item.anggaran,
realisasi: item.realisasi,
selisih: item.selisih,
persentase: item.persentase,
realisasi: item.totalRealisasi || 0,
selisih: item.selisih || 0,
persentase: item.persentase || 0,
level: item.level,
tipe: item.tipe || 'pendapatan',
})),
@@ -155,7 +161,7 @@ function EditAPBDes() {
};
const handleAddItem = () => {
const { kode, uraian, anggaran, level, tipe } = newItem;
const { kode, uraian, anggaran, level, tipe, realisasi, selisih, persentase } = newItem;
if (!kode || !uraian) {
return toast.warn('Kode dan uraian wajib diisi');
}
@@ -166,6 +172,9 @@ function EditAPBDes() {
kode,
uraian,
anggaran,
realisasi: realisasi || 0,
selisih: selisih || 0,
persentase: persentase || 0,
level,
tipe: finalTipe,
});
@@ -176,6 +185,9 @@ function EditAPBDes() {
anggaran: 0,
level: 1,
tipe: 'pendapatan',
realisasi: 0,
selisih: 0,
persentase: 0,
});
};
@@ -264,6 +276,9 @@ function EditAPBDes() {
anggaran: 0,
level: 1,
tipe: 'pendapatan',
realisasi: 0,
selisih: 0,
persentase: 0,
});
toast.info('Form dikembalikan ke data awal');
@@ -527,6 +542,9 @@ function EditAPBDes() {
<th>Kode</th>
<th>Uraian</th>
<th>Anggaran</th>
<th>Realisasi</th>
<th>Selisih</th>
<th>%</th>
<th>Level</th>
<th>Tipe</th>
<th style={{ width: '50px' }}>Aksi</th>
@@ -542,6 +560,11 @@ function EditAPBDes() {
</td>
<td>{item.uraian}</td>
<td>{item.anggaran.toLocaleString('id-ID')}</td>
<td>{item.realisasi?.toLocaleString('id-ID') || '0'}</td>
<td style={{ color: item.selisih && item.selisih > 0 ? 'red' : 'green' }}>
{item.selisih?.toLocaleString('id-ID') || '0'}
</td>
<td>{item.persentase?.toFixed(2) || '0'}%</td>
<td>
<Badge size="sm" color={item.level === 1 ? 'blue' : item.level === 2 ? 'green' : 'grape'}>
L{item.level}

View File

@@ -28,6 +28,16 @@ export default async function apbdesUpdate(context: Context) {
// 1. Pastikan APBDes ada
const existing = await prisma.aPBDes.findUnique({
where: { id },
include: {
items: {
where: { isActive: true },
include: {
realisasiItems: {
where: { isActive: true },
},
},
},
},
});
if (!existing) {
@@ -38,17 +48,35 @@ export default async function apbdesUpdate(context: Context) {
};
}
// 2. Hapus semua item lama (cascade akan menghapus realisasiItems juga)
// 2. Build map untuk preserve realisasiItems berdasarkan kode
const existingItemsMap = new Map<string, {
id: string;
realisasiItems: any[];
}>();
existing.items.forEach(item => {
existingItemsMap.set(item.kode, {
id: item.id,
realisasiItems: item.realisasiItems,
});
});
// 3. Hapus semua item lama (cascade akan menghapus realisasiItems juga)
// TAPI kita sudah save realisasiItems di map atas
await prisma.aPBDesItem.deleteMany({
where: { apbdesId: id },
});
// 3. Buat item baru dengan auto-calculate fields
// 4. Buat item baru dengan preserve realisasiItems
await prisma.aPBDesItem.createMany({
data: body.items.map((item) => {
data: await Promise.all(body.items.map(async (item) => {
const anggaran = item.anggaran;
const totalRealisasi = 0; // Reset karena items baru
const selisih = anggaran - totalRealisasi; // Sisa anggaran (positif = belum digunakan)
// Check apakah item ini punya realisasiItems lama
const existingItem = existingItemsMap.get(item.kode);
const realisasiItemsData = existingItem?.realisasiItems || [];
const totalRealisasi = realisasiItemsData.reduce((sum, r) => sum + r.jumlah, 0);
const selisih = anggaran - totalRealisasi;
const persentase = anggaran > 0 ? (totalRealisasi / anggaran) * 100 : 0;
return {
@@ -63,16 +91,68 @@ export default async function apbdesUpdate(context: Context) {
persentase,
isActive: true,
};
}),
})),
});
// 4. Dapatkan semua item yang baru dibuat untuk mendapatkan ID-nya
// 5. Dapatkan semua item yang baru dibuat untuk mendapatkan ID-nya
const allItems = await prisma.aPBDesItem.findMany({
where: { apbdesId: id },
select: { id: true, kode: true },
});
// 5. Update parentId untuk setiap item
// 6. Build map baru untuk item IDs
const newItemIdsMap = new Map<string, string>();
allItems.forEach(item => {
newItemIdsMap.set(item.kode, item.id);
});
// 7. Re-create realisasiItems dengan link ke item IDs yang baru
for (const [oldKode, oldItemData] of existingItemsMap.entries()) {
if (oldItemData.realisasiItems.length > 0) {
const newItemId = newItemIdsMap.get(oldKode);
if (newItemId) {
// Re-create realisasiItems untuk item ini
await prisma.realisasiItem.createMany({
data: oldItemData.realisasiItems.map(r => ({
apbdesItemId: newItemId,
kode: r.kode,
jumlah: r.jumlah,
tanggal: r.tanggal,
keterangan: r.keterangan,
buktiFileId: r.buktiFileId,
isActive: true,
})),
});
}
}
}
// 8. Recalculate totalRealisasi setelah re-create realisasiItems
for (const [kode, _] of existingItemsMap.entries()) {
const newItemId = newItemIdsMap.get(kode);
if (newItemId) {
const realisasiItems = await prisma.realisasiItem.findMany({
where: { apbdesItemId: newItemId, isActive: true },
});
const totalRealisasi = realisasiItems.reduce((sum, r) => sum + r.jumlah, 0);
const item = await prisma.aPBDesItem.findUnique({
where: { id: newItemId },
});
if (item) {
const selisih = item.anggaran - totalRealisasi;
const persentase = item.anggaran > 0 ? (totalRealisasi / item.anggaran) * 100 : 0;
await prisma.aPBDesItem.update({
where: { id: newItemId },
data: { totalRealisasi, selisih, persentase },
});
}
}
}
// 9. Update parentId untuk setiap item
const itemsForParentUpdate = allItems.map(item => ({
id: item.id,
kode: item.kode,
@@ -80,7 +160,7 @@ export default async function apbdesUpdate(context: Context) {
await assignParentIdsToApbdesItems(itemsForParentUpdate);
// 6. Update data APBDes
// 10. Update data APBDes
await prisma.aPBDes.update({
where: { id },
data: {
@@ -93,7 +173,7 @@ export default async function apbdesUpdate(context: Context) {
},
});
// 7. Ambil data lengkap untuk response (include realisasiItems)
// 11. Ambil data lengkap untuk response (include realisasiItems)
const result = await prisma.aPBDes.findUnique({
where: { id },
include: {

View File

@@ -3,6 +3,7 @@ import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
import { randomOTP } from "../_lib/randomOTP";
import { cookies } from "next/headers";
import { sendWhatsAppOtp } from "@/lib/wa-service";
export async function POST(req: Request) {
if (req.method !== "POST") {
@@ -34,31 +35,22 @@ export async function POST(req: Request) {
const otpNumber = Number(codeOtp);
const waMessage = `Website Desa Darmasaba - Kode ini bersifat RAHASIA dan JANGAN DI BAGIKAN KEPADA SIAPAPUN, termasuk anggota ataupun Admin lainnya.\n\n>> Kode OTP anda: ${codeOtp}.`;
const waUrl = `https://wa.wibudev.com/code?nom=${encodeURIComponent(nomor)}&text=${encodeURIComponent(waMessage)}`;
console.log("🔍 Debug WA URL:", waUrl);
try {
const res = await fetch(waUrl);
const sendWa = await res.json();
console.log("📱 WA Response:", sendWa);
if (sendWa.status !== "success") {
console.error("❌ WA Service Error:", sendWa);
return NextResponse.json(
{
success: false,
message: "Gagal mengirim OTP via WhatsApp",
debug: sendWa
},
{ status: 400 }
);
}
} catch (waError) {
console.error("❌ Fetch WA Error:", waError);
// Send OTP via WhatsApp using authenticated API
const waResult = await sendWhatsAppOtp({
nomor,
message: waMessage,
});
if (!waResult.success) {
console.error("❌ WA Service Error:", waResult);
return NextResponse.json(
{ success: false, message: "Terjadi kesalahan saat mengirim WA" },
{ status: 500 }
{
success: false,
message: waResult.message || "Gagal mengirim OTP via WhatsApp",
debug: waResult.data
},
{ status: 400 }
);
}

View File

@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import prisma from '@/lib/prisma';
import { randomOTP } from '../_lib/randomOTP';
import { sendWhatsAppOtp } from '@/lib/wa-service';
export async function POST(req: Request) {
try {
@@ -24,12 +25,18 @@ export async function POST(req: Request) {
const otpNumber = Number(codeOtp);
const waMessage = `Website Desa Darmasaba - Kode verifikasi Anda: ${codeOtp}`;
const waUrl = `https://wa.wibudev.com/code?nom=${encodeURIComponent(nomor)}&text=${encodeURIComponent(waMessage)}`;
const waRes = await fetch(waUrl);
const waData = await waRes.json();
if (waData.status !== "success") {
return NextResponse.json({ success: false, message: 'Gagal mengirim OTP via WhatsApp' }, { status: 400 });
// Send OTP via WhatsApp using authenticated API
const waResult = await sendWhatsAppOtp({
nomor,
message: waMessage,
});
if (!waResult.success) {
return NextResponse.json(
{ success: false, message: waResult.message || 'Gagal mengirim OTP via WhatsApp', debug: waResult.data },
{ status: 400 }
);
}
// ✅ Simpan OTP ke database

View File

@@ -3,6 +3,7 @@ import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
import { randomOTP } from "../_lib/randomOTP";
import { sendWhatsAppOtp } from "@/lib/wa-service";
export async function POST(req: Request) {
try {
@@ -18,15 +19,17 @@ export async function POST(req: Request) {
const codeOtp = randomOTP();
const otpNumber = Number(codeOtp);
// Kirim OTP via WhatsApp
// Kirim OTP via WhatsApp menggunakan API terautentikasi
const waMessage = `Website Desa Darmasaba - Kode ini bersifat RAHASIA dan JANGAN DI BAGIKAN KEPADA SIAPAPUN, termasuk anggota ataupun Admin lainnya.\n\n>> Kode OTP anda: ${codeOtp}.`;
const waUrl = `https://wa.wibudev.com/code?nom=${encodeURIComponent(nomor)}&text=${encodeURIComponent(waMessage)}`;
const waRes = await fetch(waUrl);
const waData = await waRes.json();
if (waData.status !== "success") {
const waResult = await sendWhatsAppOtp({
nomor,
message: waMessage,
});
if (!waResult.success) {
return NextResponse.json(
{ success: false, message: "Gagal mengirim OTP via WhatsApp" },
{ success: false, message: waResult.message || "Gagal mengirim OTP via WhatsApp", debug: waResult.data },
{ status: 400 }
);
}

View File

@@ -1,6 +1,7 @@
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
import { randomOTP } from "../_lib/randomOTP";
import { sendWhatsAppOtp } from "@/lib/wa-service";
export async function POST(req: Request) {
try {
@@ -22,13 +23,18 @@ export async function POST(req: Request) {
const codeOtp = randomOTP();
const otpNumber = Number(codeOtp);
// Kirim WA
const waUrl = `https://wa.wibudev.com/code?nom=${encodeURIComponent(nomor)}&text=Website Desa Darmasaba - Kode verifikasi Anda: ${codeOtp}`;
const res = await fetch(waUrl);
const sendWa = await res.json();
// Kirim WA menggunakan API terautentikasi
const waMessage = `Website Desa Darmasaba - Kode verifikasi Anda: ${codeOtp}`;
const waResult = await sendWhatsAppOtp({
nomor,
message: waMessage,
});
if (sendWa.status !== "success") {
return NextResponse.json({ success: false, message: 'Gagal mengirim OTP' }, { status: 400 });
if (!waResult.success) {
return NextResponse.json(
{ success: false, message: waResult.message || 'Gagal mengirim OTP', debug: waResult.data },
{ status: 400 }
);
}
// Simpan OTP

View File

@@ -78,7 +78,8 @@ function APBDesProgress({ apbdesData }: APBDesProgressProps) {
// Hitung total per kategori
const calcTotal = (items: { anggaran: number; realisasi: number }[]) => {
const anggaran = items.reduce((sum, item) => sum + item.anggaran, 0);
const realisasi = items.reduce((sum, item) => sum + item.realisasi, 0);
// Use realisasi field (already mapped from totalRealisasi in transformAPBDesData)
const realisasi = items.reduce((sum, item) => sum + (item.realisasi || 0), 0);
const persen = anggaran > 0 ? (realisasi / anggaran) * 100 : 0;
return { anggaran, realisasi, persen };
};

View File

@@ -68,6 +68,7 @@ function APBDesTable({ apbdesData }: APBDesTableProps) {
// Calculate totals
const totalAnggaran = items.reduce((sum, item) => sum + (item.anggaran || 0), 0);
// Use realisasi field (already mapped from totalRealisasi in transformAPBDesData)
const totalRealisasi = items.reduce((sum, item) => sum + (item.realisasi || 0), 0);
const totalSelisih = totalAnggaran - totalRealisasi;
const totalPersentase = totalAnggaran > 0 ? (totalRealisasi / totalAnggaran) * 100 : 0;

View File

@@ -51,7 +51,8 @@ export function transformAPBDesData(data: any): APBDesData {
kode: item.kode || '',
uraian: item.uraian || '',
anggaran: typeof item.anggaran === 'number' ? item.anggaran : 0,
realisasi: typeof item.realisasi === 'number' ? item.realisasi : 0,
// Map totalRealisasi from backend to realisasi field
realisasi: typeof item.totalRealisasi === 'number' ? item.totalRealisasi : (typeof item.realisasi === 'number' ? item.realisasi : 0),
selisih: typeof item.selisih === 'number' ? item.selisih : 0,
persentase: typeof item.persentase === 'number' ? item.persentase : 0,
level: typeof item.level === 'number' ? item.level : 1,

View File

@@ -5,7 +5,8 @@ function Summary({ title, data }: any) {
if (!data || data.length === 0) return null;
const totalAnggaran = data.reduce((s: number, i: any) => s + i.anggaran, 0);
const totalRealisasi = data.reduce((s: number, i: any) => s + i.totalRealisasi, 0);
// Use realisasi field (already mapped from totalRealisasi in transformAPBDesData)
const totalRealisasi = data.reduce((s: number, i: any) => s + (i.realisasi || i.totalRealisasi || 0), 0);
const persen =
totalAnggaran > 0 ? (totalRealisasi / totalAnggaran) * 100 : 0;
@@ -87,7 +88,8 @@ export default function GrafikRealisasi({ apbdesData }: any) {
// Hitung total keseluruhan
const totalAnggaranSemua = items.reduce((s: number, i: any) => s + i.anggaran, 0);
const totalRealisasiSemua = items.reduce((s: number, i: any) => s + i.totalRealisasi, 0);
// Use realisasi field (already mapped from totalRealisasi in transformAPBDesData)
const totalRealisasiSemua = items.reduce((s: number, i: any) => s + (i.realisasi || i.totalRealisasi || 0), 0);
const persenSemua = totalAnggaranSemua > 0 ? (totalRealisasiSemua / totalAnggaranSemua) * 100 : 0;
const formatRupiah = (angka: number) => {
@@ -105,8 +107,14 @@ export default function GrafikRealisasi({ apbdesData }: any) {
GRAFIK REALISASI APBDes {tahun}
</Title>
<Stack gap="lg" mb="lg">
<Summary title="💰 Pendapatan" data={pendapatan} />
<Summary title="💸 Belanja" data={belanja} />
<Summary title="📊 Pembiayaan" data={pembiayaan} />
</Stack>
{/* Summary Total Keseluruhan */}
<Box mb="lg" p="md" bg="gray.0">
<Box p="md" bg="gray.0">
<>
<Group justify="space-between" mb="xs">
<Text fw={700} fz="lg">TOTAL KESELURUHAN</Text>
@@ -125,12 +133,6 @@ export default function GrafikRealisasi({ apbdesData }: any) {
/>
</>
</Box>
<Stack gap="lg">
<Summary title="💰 Pendapatan" data={pendapatan} />
<Summary title="💸 Belanja" data={belanja} />
<Summary title="📊 Pembiayaan" data={pembiayaan} />
</Stack>
</Paper>
);
}

122
src/lib/wa-service.ts Normal file
View File

@@ -0,0 +1,122 @@
/**
* WhatsApp Service - Send OTP via WhatsApp using otp.wibudev.com API
* Uses API Key authentication for secure access
*/
interface SendWaOtpParams {
nomor: string;
message: string;
}
interface SendWaOtpResponse {
success: boolean;
message?: string;
data?: any;
}
/**
* Send WhatsApp message using wibudev.com API with authentication
* @param params - { nomor: string, message: string }
* @returns Promise<SendWaOtpResponse>
*/
export async function sendWhatsAppOtp({
nomor,
message,
}: SendWaOtpParams): Promise<SendWaOtpResponse> {
const apiKey = process.env.WIBU_WA_API_KEY;
const waApiUrl = process.env.WIBU_WA_API_URL || 'https://wa.wibudev.com';
if (!apiKey) {
console.error('❌ WIBU_WA_API_KEY is not configured');
return {
success: false,
message: 'WhatsApp API key not configured',
};
}
try {
// Using the API endpoint with authentication
// Format: GET https://wa.wibudev.com/code?nom=...&text=...
// With Authorization header for API key
const url = `${waApiUrl}/code?nom=${encodeURIComponent(nomor)}&text=${encodeURIComponent(message)}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'X-API-Key': apiKey,
},
});
const result = await response.json();
if (!response.ok) {
console.error('❌ WA API Error:', result);
return {
success: false,
message: result.message || 'Failed to send WhatsApp message',
data: result,
};
}
// Check if response has success status
if (result.status !== 'success') {
console.error('❌ WA API Status Error:', result);
return {
success: false,
message: result.message || 'Failed to send WhatsApp message',
data: result,
};
}
console.log('✅ WA Response:', result);
return {
success: true,
message: 'WhatsApp sent successfully',
data: result,
};
} catch (error) {
console.error('❌ Fetch WA API Error:', error);
return {
success: false,
message: error instanceof Error ? error.message : 'Unknown error occurred',
};
}
}
/**
* Legacy function for backward compatibility (deprecated)
* @deprecated Use sendWhatsAppOtp instead
*/
export async function sendWhatsAppOtpLegacy({
nomor,
message,
}: SendWaOtpParams): Promise<SendWaOtpResponse> {
const waUrl = `https://wa.wibudev.com/code?nom=${encodeURIComponent(nomor)}&text=${encodeURIComponent(message)}`;
try {
const res = await fetch(waUrl);
const result = await res.json();
if (result.status !== 'success') {
console.error('❌ WA Legacy Error:', result);
return {
success: false,
message: result.message || 'Failed to send WhatsApp message',
data: result,
};
}
return {
success: true,
message: 'WhatsApp sent successfully',
data: result,
};
} catch (error) {
console.error('❌ Fetch WA Legacy Error:', error);
return {
success: false,
message: error instanceof Error ? error.message : 'Unknown error occurred',
};
}
}