T.ME/BIBIL_0DAY
CasperSecurity


Server : Apache/2
System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64
User : gositeme ( 1004)
PHP Version : 8.2.29
Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname
Directory :  /home/gositeme/domains/lavocat.quebec/public_html/scripts/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/gositeme/domains/lavocat.quebec/public_html/scripts/seed-payment-system.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('šŸ—ļø Seeding Payment System (Phase 3A)...');

  try {
    // 1. Create Society Pricing Tiers
    console.log('Creating society pricing tiers...');
    
    const blueLodgeTier = await prisma.societyPricingTier.upsert({
      where: { name: 'Blue Lodge' },
      update: {},
      create: {
        name: 'Blue Lodge',
        track: 'BOTH',
        minDegreeNumber: 1,
        minXP: 0,
        minLevel: 1,
        platformFeeDiscount: 0.02, // 2% discount
        prioritySupport: false,
        advancedFeatures: JSON.stringify([
          'Basic payment processing',
          'Standard escrow protection',
          'Basic analytics'
        ]),
        customBranding: false,
        baseCommissionRate: 0.10,
        discountedRate: 0.08,
        description: 'Entry-level society membership with basic benefits',
        benefits: JSON.stringify([
          'Basic payment processing',
          '2% platform fee discount',
          'Standard support',
          'Basic analytics'
        ])
      }
    });

    const redLodgeTier = await prisma.societyPricingTier.upsert({
      where: { name: 'Red Lodge' },
      update: {},
      create: {
        name: 'Red Lodge',
        track: 'BOTH',
        minDegreeNumber: 4,
        minXP: 1000,
        minLevel: 5,
        platformFeeDiscount: 0.05, // 5% discount
        prioritySupport: true,
        advancedFeatures: JSON.stringify([
          'Priority payment processing',
          'Advanced escrow features',
          'Enhanced analytics',
          'Custom payment schedules'
        ]),
        customBranding: true,
        baseCommissionRate: 0.10,
        discountedRate: 0.05,
        description: 'Advanced society membership with enhanced benefits',
        benefits: JSON.stringify([
          'Priority payment processing',
          '5% platform fee discount',
          'Priority support',
          'Advanced analytics',
          'Custom branding options'
        ])
      }
    });

    const blackLodgeTier = await prisma.societyPricingTier.upsert({
      where: { name: 'Black Lodge' },
      update: {},
      create: {
        name: 'Black Lodge',
        track: 'BOTH',
        minDegreeNumber: 30,
        minXP: 50000,
        minLevel: 20,
        platformFeeDiscount: 0.08, // 8% discount
        prioritySupport: true,
        advancedFeatures: JSON.stringify([
          'Premium payment processing',
          'Full escrow management',
          'Complete analytics suite',
          'White-label options',
          'API access',
          'Custom integrations'
        ]),
        customBranding: true,
        baseCommissionRate: 0.10,
        discountedRate: 0.02,
        description: 'Elite society membership with premium benefits',
        benefits: JSON.stringify([
          'Premium payment processing',
          '8% platform fee discount',
          'Dedicated support',
          'Full analytics suite',
          'Custom branding',
          'Early feature access',
          'Fee waiver for pro bono cases'
        ])
      }
    });

    console.log('āœ… Created pricing tiers:', {
      blueLodge: blueLodgeTier.id,
      redLodge: redLodgeTier.id,
      blackLodge: blackLodgeTier.id
    });

    // 2. Create Financial Summaries for Existing Users
    console.log('Creating financial summaries for existing users...');
    
    const users = await prisma.user.findMany({
      include: {
        degrees: {
          include: {
            degree: true
          }
        }
      }
    });

    for (const user of users) {
      const existingSummary = await prisma.financialSummary.findUnique({
        where: { userId: user.id }
      });

      if (!existingSummary) {
        await prisma.financialSummary.create({
          data: {
            userId: user.id,
            totalEarnings: 0,
            thisMonthEarnings: 0,
            pendingPayouts: 0,
            totalCaseFees: 0,
            totalSpent: 0,
            thisMonthSpent: 0,
            escrowBalance: 0,
            totalCommissionPaid: 0,
            societyDiscountsSaved: 0,
            currentTier: user.degrees.length > 0 ? 'Blue Lodge' : null,
            nextTierProgress: 0,
            paymentCount: 0,
            refundCount: 0,
            disputeCount: 0
          }
        });
      }
    }

    console.log(`āœ… Created financial summaries for ${users.length} users`);

    // 3. Create Sample Test Payments (Demo Data)
    console.log('Creating sample payment data...');

    // Get some users and cases for test data
    const lawyers = await prisma.user.findMany({
      where: { role: { in: ['LAWYER', 'ADMIN', 'SUPERADMIN', 'SUPERADMIN'] } },
      take: 3
    });

    const clients = await prisma.user.findMany({
      where: { role: 'USER' },
      take: 3
    });

    const cases = await prisma.legalCase.findMany({
      where: { isPublic: true },
      take: 3
    });

    if (lawyers.length > 0 && clients.length > 0 && cases.length > 0) {
      // Create some test payments
      const testPayments = [
        {
          clientId: clients[0]?.id,
          lawyerId: lawyers[0]?.id,
          caseId: cases[0]?.id,
          amount: 1500,
          type: 'CASE_FEE',
          description: 'Initial consultation and case setup',
          societyDiscount: 0.02,
          platformFeeAmount: 120,
          lawyerPayoutAmount: 1380,
          xpEarned: 150
        },
        {
          clientId: clients[1]?.id,
          lawyerId: lawyers[1]?.id,
          caseId: cases[1]?.id,
          amount: 2500,
          type: 'CASE_FEE',
          description: 'Legal representation fee',
          societyDiscount: 0.05,
          platformFeeAmount: 125,
          lawyerPayoutAmount: 2375,
          xpEarned: 250
        },
        {
          clientId: clients[2]?.id,
          lawyerId: lawyers[2]?.id,
          caseId: cases[2]?.id,
          amount: 5000,
          type: 'CASE_FEE',
          description: 'Complex litigation fee',
          societyDiscount: 0.08,
          platformFeeAmount: 100,
          lawyerPayoutAmount: 4900,
          xpEarned: 500
        }
      ];

      let createdPayments = 0;
      for (const paymentData of testPayments) {
        if (paymentData.clientId && paymentData.lawyerId && paymentData.caseId) {
          // Create payment
          const payment = await prisma.payment.create({
            data: {
              userId: paymentData.clientId,
              amount: paymentData.amount,
              currency: 'CAD',
              type: paymentData.type,
              description: paymentData.description,
              paymentMethod: 'STRIPE',
              status: 'COMPLETED',
              caseId: paymentData.caseId,
              societyDiscount: paymentData.societyDiscount,
              platformFeeAmount: paymentData.platformFeeAmount,
              lawyerPayoutAmount: paymentData.lawyerPayoutAmount,
              xpEarned: paymentData.xpEarned,
              paymentDate: new Date(),
              metadata: JSON.stringify({
                demo: true,
                testPayment: true
              })
            }
          });

          // Create escrow account
          const escrow = await prisma.escrowAccount.create({
            data: {
              caseId: paymentData.caseId,
              clientId: paymentData.clientId,
              lawyerId: paymentData.lawyerId,
              totalAmount: paymentData.amount,
              availableAmount: paymentData.amount * 0.5, // 50% available
              heldAmount: paymentData.amount * 0.5, // 50% held
              releasedAmount: 0,
              societyFeeDiscount: paymentData.societyDiscount,
              status: 'ACTIVE',
              milestoneReleases: JSON.stringify([
                {
                  milestone: 1,
                  percentage: 0.5,
                  description: 'Case initiation completed'
                },
                {
                  milestone: 2,
                  percentage: 0.5,
                  description: 'Case completion'
                }
              ])
            }
          });

          // Update payment with escrow ID
          await prisma.payment.update({
            where: { id: payment.id },
            data: { escrowId: escrow.id }
          });

          // Create transaction record
          await prisma.transaction.create({
            data: {
              paymentId: payment.id,
              userId: paymentData.clientId,
              type: 'PAYMENT',
              amount: paymentData.amount,
              currency: 'CAD',
              direction: 'DEBIT',
              referenceId: `demo_${payment.id}`,
              referenceType: 'DEMO_PAYMENT',
              description: paymentData.description,
              balanceAfter: 0
            }
          });

          // Award XP to client
          await prisma.user.update({
            where: { id: paymentData.clientId },
            data: {
              xpPoints: { increment: paymentData.xpEarned }
            }
          });

          createdPayments++;
        }
      }

      console.log(`āœ… Created ${createdPayments} test payments with escrow accounts`);

      // 4. Update Financial Summaries with Test Data
      console.log('Updating financial summaries with test data...');

      for (const user of [...clients, ...lawyers]) {
        const userPayments = await prisma.payment.findMany({
          where: { 
            OR: [
              { userId: user.id },
              { case: { leadLawyerId: user.id } }
            ],
            status: 'COMPLETED'
          }
        });

        const clientPayments = userPayments.filter(p => p.userId === user.id);
        const lawyerPayments = await prisma.payment.findMany({
          where: {
            case: { leadLawyerId: user.id },
            status: 'COMPLETED'
          }
        });

        const totalSpent = clientPayments.reduce((sum, p) => sum + p.amount, 0);
        const totalEarnings = lawyerPayments.reduce((sum, p) => sum + p.lawyerPayoutAmount, 0);
        const totalCommissionPaid = lawyerPayments.reduce((sum, p) => sum + p.platformFeeAmount, 0);
        const societyDiscountsSaved = [...clientPayments, ...lawyerPayments]
          .reduce((sum, p) => sum + (p.amount * p.societyDiscount), 0);

        await prisma.financialSummary.update({
          where: { userId: user.id },
          data: {
            totalSpent,
            totalEarnings,
            totalCommissionPaid,
            societyDiscountsSaved,
            paymentCount: clientPayments.length,
            lastCalculated: new Date()
          }
        });
      }

      console.log('āœ… Updated financial summaries with calculated data');
    }

    console.log('\nšŸŽ‰ Payment System Seeding Complete!');
    console.log('\nšŸ“Š Summary:');
    console.log(`āœ… 3 Society pricing tiers created`);
    console.log(`āœ… ${users.length} Financial summaries initialized`);
    console.log(`āœ… Test payment data created`);
    console.log(`āœ… Escrow accounts established`);
    console.log(`āœ… Transaction history generated`);
    
    console.log('\nšŸš€ Ready to test:');
    console.log('1. Visit /payment-demo to test payments');
    console.log('2. Check financial dashboard for analytics');
    console.log('3. Test society member discounts');
    console.log('4. Explore escrow management');

  } catch (error) {
    console.error('āŒ Error seeding payment system:', error);
    throw error;
  }
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  }); 

CasperSecurity Mini