tylerzika
3/20/2017 - 5:41 PM

commission.java

/***********************************
Touchpoint Solutions
author: Tyler Zika
link: http://www.touchpointcrm.com
email: support@touchpointcrm.com
date: 03/10/17
description:
***********************************/
global class CalculateCommission
{
    webservice static String excute(String paymentId)
    {
        String result = 'success';

		// Get all Payment_Invoice__c associated with current Payments_Received__c
		// Make sure Payment_Invoice__c are not of type 'T&E' aka Time and Expense
        List<Payment_Invoice__c> nonTEInvoices =
            [SELECT Id, Amount__c,
             Invoice__c,
             Invoice__r.Invoice_Type__c, 
             Invoice__r.Name,
             Invoice__r.Opportunity__c,
             Invoice__r.Opportunity__r.Name,
             Payment__c
             FROM Payment_Invoice__c
             WHERE Payment__c = :paymentId
             AND Invoice__r.Invoice_Type__c != 'T&E'];
        System.debug('nonTEInvoices');
        System.debug(nonTEInvoices);
        
        
        Set<Id> nonTEOppIds = new Set<Id>();        
        for(Payment_Invoice__c oppId: nonTEInvoices)
        {
            nonTEOppIds.add(oppId.Invoice__r.Opportunity__c);
        }
        // Check there is at least one invoice line item found that is related
        // to one of the TEInvoices, which are realted to the current Payment Recieved

        List<Commission__c> commissionTeamNonTE = new List<Commission__c>();

        for(Commission__c teamMember: [SELECT Id, Opportunity_del__c, Overall_Pct__c, Sales_Rep__c FROM Commission__c WHERE Opportunity_del__c in :nonTEOppIds]) {
          commissionTeamNonTE.add(teamMember);
        }
//		System.debug('comissionTeam NonTE');
//      System.debug(commissionTeamNonTE);

        // Validate that there is at least one Commission Team per
        // Invoice_Line_Item__r.Project__r.Opportunity__r

        for(Payment_Invoice__c nonTEInvoice : nonTEInvoices)
        {
        	List<String> checkList = new List<String>();  
            
            for(Commission__c teamMember : commissionTeamNonTE) {
                if(nonTEInvoice.Invoice__r.Opportunity__c == teamMember.Opportunity_del__c)
                {
                    //return 'There is no Commission Team for Invoice: ' +  invoiceLineItem.Invoice__r.Name + ', Project: ' + invoiceLineItem.Project__r.Name + ', Opportunity: ' + invoiceLineItem.Project__r.Opportunity__r.Name;
                    checkList.add('match');
                }                
                  
            }
			// Make sure each nonTEInvoice has an Opportunity associated.
			// Make sure each associated Opportunity has a comission team            
			if(checkList.size() == 0) {
            	return 'There is no Commission Team for Invoice: '  + nonTEInvoice.Invoice__r.Name + ', Opportunity: ' + nonTEInvoice.Invoice__r.Opportunity__r.Name;
            }
        }
        

		// Get all Payment_Invoice__c associated with current Payments_Received__c
		// Make sure Payment_Invoice__c are of type 'T&E' aka Time and Expense
        List<Payment_Invoice__c> TEInvoices =
            [SELECT Id, Amount__c,
             Invoice__c,
             Invoice__r.Invoice_Type__c,
             Payment__c
             FROM Payment_Invoice__c
             WHERE Payment__c = :paymentId
             AND Invoice__r.Invoice_Type__c = 'T&E'];

//             System.debug('TEInvoices');
//             System.debug(TEInvoices);
        // Put all queried TEInvoice ids in a set
        Set<Id> TEInvoiceIds = new Set<Id>();
        Map<Id, Payment_Invoice__c> paymentInvoiceMap = new Map<Id, Payment_Invoice__c>();
        for(Payment_Invoice__c paymentInv : TEInvoices)
        {
            paymentInvoiceMap.put(paymentInv.Invoice__c, paymentInv);
            TEInvoiceIds.add(paymentInv.Invoice__c);
        }

		// Get all line items where time billable is true
		// and associated Invoice is the current invoice.
		// Get each project assocaited with a line item.
		// Get each opportunity associated with the project.
		// Get each comission team associated with an opportunity
        List<Invoice_Line_Item__c> invoiceLineItems =
            [SELECT Id, 
             Rollup_Amount__c,
             Invoice__c,
             Invoice__r.Name,
             
             Project__r.Name,
             
             Project__r.Opportunity__r.Id,
             Project__r.Opportunity__r.Name,
             Time_Billable__c
             FROM Invoice_Line_Item__c
             WHERE Time_Billable__c = true
             AND Invoice__c in :TEInvoiceIds];

//          System.debug('invoiceLineItems');
//          System.debug(invoiceLineItems[0].Project__r.Opportunity__r.Id);
        Set<Id> OppIds = new Set<Id>();        
        for(Invoice_Line_Item__c oppId: invoiceLineItems)
        {
            OppIds.add(oppId.Project__r.Opportunity__r.Id);
        }
        // Check there is at least one invoice line item found that is related
        // to one of the TEInvoices, which are realted to the current Payment Recieved
        if(invoiceLineItems.size() == 0)
        {
            return 'No invoice line items found related to a T&E Invoice and the current Payment.';
        }

        List<Commission__c> commissionTeam = new List<Commission__c>();
		System.debug('TeamMembers');
        for(Commission__c teamMember: [SELECT Id, Opportunity_del__c, Overall_Pct__c, Sales_Rep__c FROM Commission__c WHERE Opportunity_del__c in :OppIds]) {
          System.debug(teamMember);
          commissionTeam.add(teamMember);
        }


        // Validate that there is at least one Commission Team per
        // Invoice_Line_Item__r.Project__r.Opportunity__r

        for(Invoice_Line_Item__c invoiceLineItem : invoiceLineItems)
        {
        	List<String> checkList = new List<String>();  
            
            for(Commission__c teamMember : commissionTeam) {
                if(invoiceLineItem.Project__r.Opportunity__c == teamMember.Opportunity_del__c)
                {
                    //return 'There is no Commission Team for Invoice: ' +  invoiceLineItem.Invoice__r.Name + ', Project: ' + invoiceLineItem.Project__r.Name + ', Opportunity: ' + invoiceLineItem.Project__r.Opportunity__r.Name;
                    checkList.add('match');
                }                
                  
            }
			if(checkList.size() == 0) {
            	return 'There is no Commission Team for Invoice: ' +  invoiceLineItem.Invoice__r.Name + ', Project: ' + invoiceLineItem.Project__r.Name + ', Opportunity: ' + invoiceLineItem.Project__r.Opportunity__r.Name;                
            }
        }

        // Creates the commission payment records
        List<CommissionPayment__c> commissionPayments = new List<CommissionPayment__c>();

        // First create commision payment record associated
        // with invoices that are of type != T&E

        for(Payment_Invoice__c commissionPayment : nonTEInvoices)
        {
            for(Commission__c teamMember: commissionTeamNonTE) {
                if(commissionPayment.Invoice__r.Opportunity__c == teamMember.Opportunity_del__c) {
                    commissionPayments.add(new CommissionPayment__c(
                        Employee__c = teamMember.Sales_Rep__c,
                        Invoice__c = commissionPayment.Invoice__c,
                        Opportunity__c = commissionPayment.Invoice__r.Opportunity__c,
                        Payment_Amount__c = commissionPayment.Amount__c,
                        CommissionPercent__c = teamMember.Overall_Pct__c,
                        Payment__c = paymentId,
                        Commission_Amount__c = ((commissionPayment.Amount__c/100) * teamMember.Overall_Pct__c)
                        )
                    );                     
                }
               
            }

        }

        // Next create commision payment record associated
        // with invoices that are of type == T&E
        for(Invoice_Line_Item__c project : invoiceLineItems)
        {
            Payment_Invoice__c paymentInv = paymentInvoiceMap.get(project.Invoice__c);
            for(Commission__c teamMember: commissionTeam) {
                if(project.Project__r.Opportunity__r.Id == teamMember.Opportunity_del__c) {
                    commissionPayments.add(new CommissionPayment__c(
                    Employee__c = teamMember.Sales_Rep__c, 
                    Invoice__c = paymentInv.Invoice__c, 
                    Opportunity__c = project.Project__r.Opportunity__c, 
                    Payment_Amount__c = project.Rollup_Amount__c, 
                    CommissionPercent__c = teamMember.Overall_Pct__c, 
                    Payment__c = paymentId,                        
                    Commission_Amount__c = ((project.Rollup_Amount__c/100) * teamMember.Overall_Pct__c)));
                }
            }
        }


        try
        {
            insert commissionPayments;
        }
        catch(Exception ex)
        {
            result = ex.getMessage();
        }
        return result;
    }
}