Created
April 29, 2015 18:19
-
-
Save mshanemc/7abd286aa38248ab4f01 to your computer and use it in GitHub Desktop.
Customer Depreciation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public with sharing class DepreciationCalc { | |
public static void deleteCurrentDepreciation(list<Asset__c> assets){ | |
delete [select id from Depreciation__c where Asset__c in:assets]; | |
} | |
public static void makeDepreciations(list<Asset__c> assets){ | |
list<Depreciation__c> output = new list<Depreciation__c>(); | |
//loop through the assets | |
for (Asset__c a:assets){ | |
//sanity check | |
if (a.Depreciation_Method__c == null || a.Depreciation_Asset_Life__c == null || a.Planned_Completion__c == null || a.Acquisition_Value__c == null){ | |
continue; | |
} | |
//still here? then we'll do some depreciation | |
decimal bookValueBalance = a.Acquisition_Value__c; | |
decimal accDep = 0; | |
integer Year = 1; | |
//get list of decimals, create a depreciation year for each one. | |
for (decimal DepPct:calcDepreciationPercents(a.Depreciation_Method__c, integer.valueOf(a.Depreciation_Asset_Life__c))) { | |
system.debug('percent this year is ' + DepPct); | |
Depreciation__c d = new Depreciation__c(); | |
d.Name = a.Name + ' Year ' + Year; | |
d.Asset__c = a.Id; | |
d.Asset_Value_at_Beginning_of_Year__c = bookValueBalance; | |
d.Depreciation__c = a.Acquisition_Value__c * DepPct; | |
d.Asset_Value_End_of_Year__c = d.Asset_Value_at_Beginning_of_Year__c - d.Depreciation__c; | |
d.Accumulated_Depreciation__c = accDep + d.Depreciation__c; | |
d.Depreciation_Year_Begins__c = a.Planned_Completion__c.addYears(Year - 1); | |
accDep = accDep + d.Depreciation__c; | |
bookValueBalance = d.Asset_Value_End_of_Year__c; | |
Year = Year +1; | |
output.add(d); | |
} | |
} | |
insert output; | |
} | |
public static list<decimal> calcDepreciationPercents(string deptype, integer years){ | |
list<Decimal> output = new list<Decimal>(); | |
if (deptype=='Straight Line'){ | |
for (integer x=0; x<years; x++){ | |
output.add(1/decimal.valueof(years)); | |
} | |
} | |
if (deptype=='Double Declining Balance'){ | |
decimal decliningBalance = 1; | |
for (integer x=0; x<years; x++){ | |
//calculate the current | |
if (x-1!=years){ | |
output.add(decliningBalance/decimal.valueOf(years)*2); //not final year | |
decliningBalance = decliningBalance - output[x]; //reduce the declining balance | |
} else{ | |
output.add(decliningBalance); //final year: take it all | |
} | |
} | |
} | |
system.debug(output); | |
return output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment