+ Start a Discussion
Mike DeMilleMike DeMille 

Help with Visual Flow or Apex Trigger

I have a pretty interesting problem to solve here.  It involves duplicating products on that are added to an opportunity when it is a mulit-year contract.  The goal would be to get a line item for each year of the contract.  When adding products to an opportunity, If the 'initial term' field = 24 months, I would like to duplicate or create another line item for each product added to the opportunity that is of the 'type' = recurring (product type).  If the term = 36 months, I would like to add 2 more duplicate products of 'type' = recurring, for a total of 3.  If it's 48 months, then I would like to have a total of 4 of the same line items and so on..  If the initial term is 12 months, then no additional products would be needed.  

I could do this with process builder, but I need this to assess anytime products are added OR taken away.., so it wouldn't work to evaluate this if items were deleted.   I would like this to fire each time the 'initial term' field is changed.  I will also add an 'override' field that is a checkbox for situations that are rare and need overwritten.  The end goal is that I'm trying to get a line item for each year of a contract for multi year contracts, and it is taking my sales guys a while to add these.  They also get confused from time to time.  

This could get a bit complicated, but here my thoughts on it.

You could have an after insert/update trigger on the opportunity, and on the OLI (I think?  If an update to the OLI fires the opportunity trigger - then just on the opportunity is fine.)

In the trigger(s), collect the opportunity IDs that need to have products added/removed.  Pass these Ids to a handler class to do the actual work. (That way - the handler class can be called form either of the trigger's).

In the handler class, get the Opportunity, and OLIs (use a sub-soql for the OLIs).  Then process each opportunity, using logic to get the "Number" of product sets required. (basically Term / 12).  Inside the opportunity loop - loop  on the OLIs and figure out how many sets of products you have. While in this loop - keep a counter for the "product set" you're on.  If you're past the number of product sets required, then start building a set of OLI IDs that should be deleted. After you've looped through the OLIs, and you have a count of how many sets are actually there, and how many are needed, then loop through the OLIs a second time - building a list of OLIs to insert. 

There might be some other ways to accomplish this - but that's one idea that would probably work for you.