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/private_html/scripts/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

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

const prisma = new PrismaClient();

async function seedClientLawyerRelationships() {
  console.log('šŸ›ļø Seeding client-lawyer relationships...');

  try {
    // Get existing users
    const users = await prisma.user.findMany({
      include: {
        casesAsLead: true,
        registrations: true
      }
    });
    
    const lawyers = users.filter(u => u.role === 'LAWYER' || u.role === 'ADMIN');
    const clients = users.filter(u => u.role === 'USER');
    
    console.log(`Found ${lawyers.length} lawyers and ${clients.length} clients`);
    
    if (lawyers.length === 0 || clients.length === 0) {
      console.log('Need both lawyers and clients to create relationships');
      return;
    }
    
    // Get existing cases
    const cases = await prisma.legalCase.findMany();
    
    // Create sample relationships
    const relationships = [
      // Successful criminal defense case
      {
        clientId: clients[0]?.id,
        lawyerId: lawyers[0]?.id,
        caseId: cases[0]?.id,
        relationshipType: 'PLATFORM_MATCH',
        caseStatus: 'WON',
        outcomeDescription: 'All charges dropped after successful motion to suppress evidence',
        totalHoursWorked: 45.5,
        totalFeePaid: 9100.0,
        feeStructure: 'HOURLY',
        clientSatisfaction: 5,
        wouldRecommend: true,
        impactLevel: 'LIFE_CHANGING',
        clientReview: 'Sarah Chen literally saved my life. The police violated my rights during the search, and she fought tirelessly to get the evidence thrown out. Professional, compassionate, and incredibly skilled.',
        publicTestimonial: 'I was facing serious criminal charges that could have ruined my career and family. Sarah fought for me every step of the way and got all charges dropped. I cannot thank her enough.',
        isTestimonialPublic: true,
        endDate: new Date('2024-03-15')
      },
      // Pro bono family law case
      {
        clientId: clients[1]?.id || clients[0]?.id,
        lawyerId: lawyers[1]?.id || lawyers[0]?.id,
        relationshipType: 'PRO_BONO',
        caseStatus: 'SETTLED',
        outcomeDescription: 'Secured full custody and child support agreement',
        totalHoursWorked: 28.0,
        totalFeePaid: 0.0,
        feeStructure: 'PRO_BONO',
        clientSatisfaction: 5,
        wouldRecommend: true,
        impactLevel: 'LIFE_CHANGING',
        clientReview: 'David took my case pro bono when I had nowhere else to turn. He helped me get full custody of my children and ensured they would be safe. He is a true champion of justice.',
        publicTestimonial: 'When I was a single mother with no resources, David Justice stepped up and fought for my children pro bono. We won full custody and my kids are now safe.',
        isTestimonialPublic: true,
        endDate: new Date('2024-02-20')
      },
      // Personal injury settlement
      {
        clientId: clients[2]?.id || clients[0]?.id,
        lawyerId: lawyers[2]?.id || lawyers[0]?.id,
        relationshipType: 'DIRECT_HIRE',
        caseStatus: 'SETTLED',
        outcomeDescription: 'Secured $150,000 settlement for workplace injury',
        settlementAmount: 150000,
        totalHoursWorked: 67.0,
        totalFeePaid: 50000.0, // 33% contingency
        feeStructure: 'CONTINGENCY',
        clientSatisfaction: 4,
        wouldRecommend: true,
        impactLevel: 'SIGNIFICANT',
        clientReview: 'Excellent negotiation skills. Got me far more than I expected and handled all the insurance company headaches.',
        endDate: new Date('2024-01-10')
      }
    ];
    
    const createdRelationships = [];
    
    for (const relationship of relationships) {
      if (relationship.clientId && relationship.lawyerId) {
        try {
          const created = await prisma.clientLawyerRelationship.create({
            data: relationship,
            include: {
              client: true,
              lawyer: true,
              case: true
            }
          });
          createdRelationships.push(created);
          console.log(`āœ… Created relationship: ${created.client.name} ↔ ${created.lawyer.name}`);
        } catch (error) {
          console.log(`āš ļø Skipping duplicate relationship: ${error}`);
        }
      }
    }
    
    // Create relationship milestones
    console.log('\nšŸ“‹ Creating relationship milestones...');
    
    for (const relationship of createdRelationships) {
      const milestones = [
        {
          relationshipId: relationship.id,
          milestoneType: 'CASE_STARTED',
          title: 'Initial consultation completed',
          description: 'First meeting with client to discuss case details and strategy',
          date: new Date(relationship.startDate.getTime() + 24 * 60 * 60 * 1000), // 1 day after start
          isPublic: true
        },
        {
          relationshipId: relationship.id,
          milestoneType: 'COURT_APPEARANCE',
          title: 'First court hearing',
          description: 'Appeared in court for initial hearing and case management',
          date: new Date(relationship.startDate.getTime() + 30 * 24 * 60 * 60 * 1000), // 30 days after
          isPublic: true
        }
      ];
      
      // Add case resolution milestone if case is closed
      if (relationship.caseStatus !== 'ONGOING') {
        milestones.push({
          relationshipId: relationship.id,
          milestoneType: 'CASE_RESOLVED',
          title: `Case ${relationship.caseStatus?.toLowerCase()}`,
          description: relationship.outcomeDescription || 'Case concluded successfully',
          date: relationship.endDate || new Date(),
          isPublic: true
        });
      }
      
      for (const milestone of milestones) {
        try {
          await prisma.relationshipMilestone.create({
            data: milestone
          });
          console.log(`  šŸ“ Added milestone: ${milestone.title}`);
        } catch (error) {
          console.log(`  āš ļø Skipping milestone: ${error}`);
        }
      }
    }
    
    // Create testimonials
    console.log('\n⭐ Creating client testimonials...');
    
    const testimonials = [
      {
        clientId: createdRelationships[0]?.clientId,
        lawyerId: createdRelationships[0]?.lawyerId,
        relationshipId: createdRelationships[0]?.id,
        caseId: createdRelationships[0]?.caseId,
        title: 'How Sarah Chen Saved My Future',
        content: 'I was facing serious criminal charges that could have destroyed my career and family. Sarah Chen took my case and immediately got to work. She discovered that the police had violated my constitutional rights during the search of my property. Her meticulous attention to detail and aggressive defense strategy led to all charges being dropped. Sarah is not just a lawyer - she is a fighter for justice.',
        beforeSituation: 'Facing multiple felony charges with potential 10+ year sentence',
        afterSituation: 'All charges dropped, record cleared, career and family intact',
        category: 'CRIMINAL_DEFENSE',
        impactLevel: 'LIFE_CHANGING',
        isPublic: true,
        isFeatured: true
      },
      {
        clientId: createdRelationships[1]?.clientId,
        lawyerId: createdRelationships[1]?.lawyerId,
        relationshipId: createdRelationships[1]?.id,
        title: 'Pro Bono Hero - David Justice',
        content: 'As a single mother with limited resources, I thought I would never be able to afford a good lawyer to help me get custody of my children. David Justice took my case pro bono and fought as hard as if I was paying him millions. He secured full custody and child support, ensuring my children would be safe and provided for. David truly lives up to his name - he is justice personified.',
        beforeSituation: 'Single mother unable to afford legal help, children in unsafe situation',
        afterSituation: 'Full custody secured, children safe, child support established',
        category: 'FAMILY_LAW',
        impactLevel: 'LIFE_CHANGING',
        isPublic: true,
        isFeatured: true
      }
    ];
    
    for (const testimonial of testimonials) {
      if (testimonial.clientId && testimonial.lawyerId) {
        try {
          const created = await prisma.clientTestimonial.create({
            data: testimonial,
            include: {
              client: true,
              lawyer: true
            }
          });
          console.log(`āœ… Created testimonial: "${created.title}"`);
        } catch (error) {
          console.log(`āš ļø Skipping testimonial: ${error}`);
        }
      }
    }
    
    // Update lawyer stats
    console.log('\nšŸ“Š Updating lawyer statistics...');
    
    for (const lawyer of lawyers) {
      const relationships = await prisma.clientLawyerRelationship.findMany({
        where: { lawyerId: lawyer.id }
      });
      
      const testimonials = await prisma.clientTestimonial.findMany({
        where: { lawyerId: lawyer.id }
      });
      
      const totalClients = relationships.length;
      const activeClients = relationships.filter(r => r.isActive).length;
      const casesWon = relationships.filter(r => r.caseStatus === 'WON').length;
      const casesLost = relationships.filter(r => r.caseStatus === 'LOST').length;
      const casesSettled = relationships.filter(r => r.caseStatus === 'SETTLED').length;
      const casesDismissed = relationships.filter(r => r.caseStatus === 'DISMISSED').length;
      
      const totalCasesCompleted = casesWon + casesLost + casesSettled + casesDismissed;
      const winRate = totalCasesCompleted > 0 ? ((casesWon + casesSettled) / totalCasesCompleted) * 100 : 0;
      
      const totalRevenue = relationships
        .filter(r => r.totalFeePaid)
        .reduce((sum, r) => sum + (r.totalFeePaid || 0), 0);
      
      const totalProBonoHours = relationships
        .filter(r => r.feeStructure === 'PRO_BONO')
        .reduce((sum, r) => sum + (r.totalHoursWorked || 0), 0);
      
      const satisfactionRatings = relationships
        .filter(r => r.clientSatisfaction)
        .map(r => r.clientSatisfaction!);
      
      const averageSatisfaction = satisfactionRatings.length > 0 
        ? satisfactionRatings.reduce((sum, rating) => sum + rating, 0) / satisfactionRatings.length 
        : 0;
      
      const recommendationCount = relationships.filter(r => r.wouldRecommend === true).length;
      const recommendationRate = relationships.length > 0 ? (recommendationCount / relationships.length) * 100 : 0;
      
      const lifeChangingCases = relationships.filter(r => r.impactLevel === 'LIFE_CHANGING').length;
      
      const totalSettlementValue = relationships
        .filter(r => r.settlementAmount)
        .reduce((sum, r) => sum + (r.settlementAmount || 0), 0);
      
      try {
        await prisma.lawyerStats.upsert({
          where: { lawyerId: lawyer.id },
          update: {
            totalClients,
            activeClients,
            casesWon,
            casesLost,
            casesSettled,
            casesDismissed,
            winRate,
            totalRevenue,
            totalProBonoHours,
            totalProBonoValue: totalProBonoHours * 200, // Estimate $200/hour value
            averageSatisfaction,
            recommendationRate,
            totalTestimonials: testimonials.length,
            lifeChangingCases,
            totalSettlementValue,
            lastCalculated: new Date()
          },
          create: {
            lawyerId: lawyer.id,
            totalClients,
            activeClients,
            casesWon,
            casesLost,
            casesSettled,
            casesDismissed,
            winRate,
            totalRevenue,
            totalProBonoHours,
            totalProBonoValue: totalProBonoHours * 200,
            averageSatisfaction,
            recommendationRate,
            totalTestimonials: testimonials.length,
            lifeChangingCases,
            totalSettlementValue,
            lastCalculated: new Date()
          }
        });
        
        console.log(`šŸ“Š Updated stats for ${lawyer.name}: ${totalClients} clients, ${winRate.toFixed(1)}% win rate`);
      } catch (error) {
        console.log(`āš ļø Error updating stats for ${lawyer.name}: ${error}`);
      }
    }
    
    console.log('\nšŸŽ‰ Client-lawyer relationship seeding completed!');
    
  } catch (error) {
    console.error('Error seeding relationships:', error);
  }
}

async function main() {
  await seedClientLawyerRelationships();
  await prisma.$disconnect();
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
}); 

CasperSecurity Mini