Work TRX gz notifikasi

by โ˜˜๏ธ

17
Raw
case 'y': {
    const nomor = sender.split("@")[0];
    if (!global.pendingTransactions || !global.pendingTransactions[nomor]) {
        return m.reply(`Tidak ada transaksi yang menunggu konfirmasi.`);
    }
    
    const transaction = global.pendingTransactions[nomor];
    delete global.pendingTransactions[nomor];
    const { 
        product, 
        customer_no, 
        customer_zone, 
        adjustedPrice, 
        userSaldo, 
        userData,
        nickInfo
    } = transaction;

    const saldoAwal = userSaldo.saldo;
    
    let modalPrice = product.harga || 0;
    if (!userSaldo.saldo || userSaldo.saldo < adjustedPrice) {
        return m.reply(`Total saldo kamu (${rupiah(userSaldo.saldo || 0)}) tidak cukup untuk transaksi senilai ${rupiah(adjustedPrice)}.\n\nSilakan isi saldo terlebih dahulu.`);
    } else {
        userSaldo.saldo -= adjustedPrice;
        fs.writeFileSync('./db/users.json', JSON.stringify(userData, null, 2));
        await processGZStoreTransaction();
    }
    
    async function processGZStoreTransaction() {
        const ref_id = Invoice(); 
        const apikey = global.GriezSt;
        
        try {
            let invo = `*โ”€โ”€ ใ€Œ TRANSAKSI PROSES ใ€ โ”€โ”€*\n\n`;
            invo += `> *Produk :* ${product.nama_layanan}\n`;
            invo += `> *Kategori :* ${product.kategori}\n`;
            invo += `> *Tujuan :* ${customer_no}${customer_zone ? ' ' + customer_zone : ''}\n`;
            
            if (nickInfo && nickInfo.success) {
                invo += `> *Nickname :* ${nickInfo.data.nickname}\n`;
                if (nickInfo.data.region) {
                    invo += `> *Region :* ${nickInfo.data.region}\n`;
                }
            }
            
            invo += `> *Harga :*  ${rupiah(adjustedPrice)}\n`;
            invo += `> *Invoice :* ${ref_id}\n\n`; 
            invo += `> *Saldo Awal :* ${rupiah(saldoAwal)}\n`;
            invo += `> *Saldo Akhir :* ${rupiah(userSaldo.saldo)}\n`;
            await xstbot.sendText(m.chat, invo, m);

            const requestBody = {
                api_key: apikey,
                user_id: customer_no,
                zone: customer_zone || '',
                service: product.kode,
                quantity: "1",
                kontak: "6285380779466" 
            };

            const orderResponse = await axios.post(
                'https://gzstore.id/api/v1/Order',
                requestBody,
                { headers: { 'Content-Type': 'application/json' } }
            );
            
            console.log("GZ Store Order Response:", orderResponse.data);

            if (!orderResponse.data || !orderResponse.data.status || !orderResponse.data.data || !orderResponse.data.data.id) {
                userSaldo.saldo += adjustedPrice;
                fs.writeFileSync('./db/users.json', JSON.stringify(userData, null, 2));
                return m.reply(orderResponse.data?.message || "Gagal memproses pesanan");
            }
            
            const orderId = orderResponse.data.data.id;
            const gzInvoice = orderResponse.data.data.invoice || orderId;
            let transactionCompleted = false;
            while (!transactionCompleted) {
                await new Promise(resolve => setTimeout(resolve, 5000)); 
                
                try {
                    const statusResponse = await axios.post(
                        'https://gzstore.id/api/v1/status',
                        {
                            api_key: apikey,
                            order_id: orderId
                        },
                        { headers: { 'Content-Type': 'application/json' } }
                    );
                    
                    console.log("GZ Store Status Response:", statusResponse.data);

                    if (!statusResponse.data || !statusResponse.data.status || !statusResponse.data.data) { 
                        continue; // Lanjutkan polling jika respons tidak valid
                    }
                    
                    const statusData = statusResponse.data.data;

                    if (statusData && statusData.status) {
                        // Transaksi sukses
                        if (statusData.status === 'Success') {
                            let responseMsg = `*โ”€โ”€ ใ€Œ TRANSAKSI SUKSES ใ€ โ”€โ”€*\n\n`;
                            responseMsg += `*ยป Produk :* ${statusData.layanan || product.nama_layanan}\n`;
                            responseMsg += `*ยป Kategori :* ${product.kategori}\n`;
                            responseMsg += `*ยป Tujuan :* ${statusData.user_id || customer_no}${statusData.zone ? ' ' + statusData.zone : (customer_zone ? ' ' + customer_zone : '')}\n`;

                            const displayUsername = (statusData.username && statusData.username !== '-') ? 
                                statusData.username : (nickInfo && nickInfo.success ? nickInfo.data.nickname : "");
                                
                            if (displayUsername) {
                                responseMsg += `*ยป Nickname :* ${displayUsername}\n`;

                                if (nickInfo && nickInfo.success && nickInfo.data.region) {
                                    responseMsg += `*ยป Region :* ${nickInfo.data.region}\n`;
                                }
                            }
                            
                            responseMsg += `*ยป Harga :* ${rupiah(adjustedPrice)}\n`;
                            responseMsg += `*ยป Invoice :* ${ref_id}\n`;
                            
                            if (statusData.keterangan) {
                                responseMsg += `*ยป Info :* ${statusData.keterangan}\n\n`;
                            }
                            responseMsg += `> *ยป Saldo Awal :* ${rupiah(saldoAwal)}\n`;
                            responseMsg += `> *ยป Saldo Akhir :* ${rupiah(userSaldo.saldo)}\n`;
                            
                            await xstbot.sendMessage(m.chat, { text: responseMsg }, { quoted: m });
                            
                            // Kirim notifikasi ke owner
                            sendTransactionNotificationToOwner(
                                "SUKSES",
                                nomor,
                                statusData.layanan || product.nama_layanan, 
                                statusData.user_id || customer_no,
                                statusData.zone || customer_zone || "",
                                displayUsername,
                                adjustedPrice,
                                ref_id,
                                saldoAwal,
                                userSaldo.saldo,
                                gzInvoice
                            );
                            
                            // Simpan transaksi sukses
                            saveTransaction(
                                nomor, 
                                "Berhasil", 
                                ref_id,
                                gzInvoice,
                                statusData.layanan || product.nama_layanan,
                                product.kategori,
                                "00", 
                                statusData.user_id || customer_no, 
                                statusData.zone || customer_zone || "", 
                                displayUsername,
                                adjustedPrice, 
                                product.harga,
                                nickInfo && nickInfo.success ? nickInfo.data.region : null,
                                saldoAwal,
                                userSaldo.saldo
                            );
                            
                            transactionCompleted = true;
                            break;
                        } 
                        // Status gagal
                        else if (
                            statusData.status === 'Batal' || 
                            statusData.status === 'batal' || 
                            statusData.status === 'Gagal' || 
                            statusData.status === 'gagal'
                        ) {
                            const failedInvoice = Invoice();
                            userSaldo.saldo += adjustedPrice;
                            fs.writeFileSync('./db/users.json', JSON.stringify(userData, null, 2));
                            
                            let responseMsg = `*โ”€โ”€ ใ€Œ TRANSAKSI GAGAL ใ€ โ”€โ”€*\n\n`;
                            responseMsg += `*ยป Produk :* ${statusData.layanan || product.nama_layanan}\n`;
                            responseMsg += `*ยป Kategori :* ${product.kategori}\n`;
                            responseMsg += `*ยป Tujuan :* ${statusData.user_id || customer_no}${statusData.zone ? ' ' + statusData.zone : (customer_zone ? ' ' + customer_zone : '')}\n`;
                            const displayUsername = (statusData.username && statusData.username !== '-') ? 
                                statusData.username : (nickInfo && nickInfo.success ? nickInfo.data.nickname : "");
                                
                            if (displayUsername) {
                                responseMsg += `*ยป Nickname :* ${displayUsername}\n`;
                                if (nickInfo && nickInfo.success && nickInfo.data.region) {
                                    responseMsg += `*ยป Region :* ${nickInfo.data.region}\n`;
                                }
                            }
                            
                            responseMsg += `*ยป Harga :* ${rupiah(adjustedPrice)}\n`;
                            responseMsg += `*ยป Invoice :* ${failedInvoice}\n`;
                            
                            if (statusData.keterangan) {
                                responseMsg += `*ยป Info :* ${statusData.keterangan}\n\n`;
                            }
                            responseMsg += `> *ยป Saldo Awal :* ${rupiah(saldoAwal)}\n`;
                            responseMsg += `> *ยป Saldo Akhir :* ${rupiah(userSaldo.saldo)}\n`;
                            
                            await xstbot.sendMessage(m.chat, { text: responseMsg }, { quoted: m });
                            
                            // Kirim notifikasi ke owner
                            sendTransactionNotificationToOwner(
                                "GAGAL",
                                nomor,
                                statusData.layanan || product.nama_layanan, 
                                statusData.user_id || customer_no,
                                statusData.zone || customer_zone || "",
                                displayUsername,
                                adjustedPrice,
                                failedInvoice,
                                saldoAwal,
                                userSaldo.saldo,
                                gzInvoice
                            );
                            
                            // Simpan transaksi gagal
                            saveTransaction(
                                nomor, 
                                "Gagal", 
                                failedInvoice,
                                gzInvoice,
                                statusData.layanan || product.nama_layanan,
                                product.kategori,
                                "99", 
                                statusData.user_id || customer_no, 
                                statusData.zone || customer_zone || "", 
                                displayUsername, 
                                adjustedPrice, 
                                product.harga,
                                nickInfo && nickInfo.success ? nickInfo.data.region : null,
                                saldoAwal,
                                userSaldo.saldo
                            );
                            
                            transactionCompleted = true;
                            break;
                        }
                        else if (statusData.status === 'Pending' || statusData.status === 'Processing') {
                            console.log(`Order ${orderId} masih ${statusData.status}. Menunggu perubahan status...`);
                            continue;
                        }
                        else {
                            console.log(`Status tidak dikenali: ${statusData.status}. Menunggu perubahan status...`);
                            continue;
                        }
                    }
                } catch (error) {
                    console.log("Error checking order status:", error);
                    await new Promise(resolve => setTimeout(resolve, 10000)); 
                }
            }
        } catch (error) { 
            console.log("Transaction processing error:", error);
            m.reply("Terjadi kesalahan saat memproses transaksi. Silakan coba lagi nanti.");
            userSaldo.saldo += adjustedPrice;
            fs.writeFileSync('./db/users.json', JSON.stringify(userData, null, 2));
        }
    }
    
    function sendTransactionNotificationToOwner(status, nomor, layanan, tujuan, zone, nickname, harga, invoice, saldoAwal, saldoAkhir, gzInvoice) {
        const targetNumber = "6285380779466@s.whatsapp.net"; // Ganti nomor owner 
        let notifMsg = `*NOTIFIKASI TRANSAKSI ${status}*\n\n`;
        notifMsg += `*ยป Nomor:* ${nomor}\n\n`;
        notifMsg += `*ยป Produk:* ${layanan}\n`;
        notifMsg += `*ยป Tujuan:* ${tujuan}${zone ? ' ' + zone : ''}\n`;
        
        if (nickname) {
            notifMsg += `*ยป Nickname:* ${nickname}\n`;
        }
        
        notifMsg += `*ยป Harga:* ${rupiah(harga)}\n`;
        notifMsg += `*ยป Saldo Awal:* ${rupiah(saldoAwal)}\n`;
        notifMsg += `*ยป Saldo Akhir:* ${rupiah(saldoAkhir)}\n`;
        notifMsg += `*ยป Pembeli:* ${nomor}\n\n`;
        notifMsg += `*ยป BOT-Invoice:* ${invoice}\n`;
        if (gzInvoice) {
            notifMsg += `*ยป GZ-Invoice:* ${gzInvoice}\n`;
        }
        notifMsg += `*ยป Waktu:* ${time1} | ${hariini}`;
        
        xstbot.sendMessage(targetNumber, { text: notifMsg });
    }
    
    function saveTransaction(nomor, status, invoice, gzInvoice, item, category, rc, tujuan, zone, username, harga, harga_modal, region = null, saldoAwal, saldoAkhir) {
        try {
            let transactions = [];
            if (fs.existsSync("./db/trx.json")) {
                const rawData = fs.readFileSync("./db/trx.json", "utf8");
                transactions = JSON.parse(rawData);
            }
            
            const newTransaction = {
                nomor: nomor,
                status: status,
                invoice: invoice,
                gzInvoice: gzInvoice,
                item: item,
                category: category, 
                rc: rc,
                tujuan: `${tujuan}${zone ? ' ' + zone : ''}`,
                username: username,
                region: region,
                harga: harga,
                harga_modal: harga_modal,
                saldoAwal: saldoAwal,
                saldoAkhir: saldoAkhir,
                waktu: `${time1} | ${hariini}`
            };
            
            transactions.push(newTransaction);
            fs.writeFileSync("./db/trx.json", JSON.stringify(transactions, null, 2));
            return true;
        } catch (error) {
            console.error("Error saving transaction:", error);
            return false;
        }
    }
}
break;