Apex trigger to default field values when adding opportunity line - salesforce

I'm not a developer, but I'm attempting to learn since I've reached a point where I need code to customize and automate further. I've created a custom "Sales Price" field for Opportunity Products that I am using to replace the standard Sales Price field. I want the custom field to default with the price book entry list price (unitprice) value as does the standard Sales Price field. Then I have the standard Sales Price field getting updated to equal the custom Sales Price times the number of month terms (custom field that will be updated at Opportunity level and automatically populated in reflective custom field on Opportunity Products via trigger). I've created triggers for both the Sales Price value to default and the Month Terms to default, but neither seems to be working now. Below is the trigger for the Sales Price value when creating a new opportunity line item. Not sure how to get the price to default when adding a new product line item? It should only default when adding new since I don't want it to override any amount that they put in and save. But it also needs to work if they go back into the opp and add additional items later. Any input on this is greatly appreciated. I've spent hours searching posts and other documentation, but I don't have that natural developer brain, and I'm banging my head!
trigger SalesPricecustom on OpportunityLineItem (before insert) {
Set<Id> pbeIds = new Set<Id>();
for (OpportunityLineItem oli : Trigger.new)
pbeIds.add(oli.pricebookentryid);
Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>(
[select UnitPrice from pricebookentry
where id in :pbeIds]);
for (OpportunityLineItem oli :trigger.new){
if(pricebookentry.unitprice <> null && oli.sales_price__c == null){
oli.sales_price__c = entries.get(oli.pricebookEntryId).UnitPrice;
}
}}
Thanks!

Could you describe your problem in other words? If you want to recalculate sales price field when old data is updated (not only inserted new lines), you should used "before update" event for this trigger, as here:
trigger SalesPricecustom on OpportunityLineItem (before insert, before update){
//Here is your code
}
Also, you can check, which fields was changed, it will help you not to execute once again trigger logic, if other fields have been updated(use for this trigger context variables - Trigger.new, Trigger.old, Trigger.newMap, Trigger.oldMap).

Related

Apex/Salesforce/flow: Be able to increase price and clone/update product automatically

I asked a similar question before but I am still struggling and was not able to do what I was required to do and am coming back to this community for help.
I am trying to increase the price of the products on a quote in salesforce CPQ/Billing based on a field and to do this automatically.
The Setup
In Salesforce CPQ, If you go to account -> Contract -> Sales Service: There is a field called Price Increase %(PROD_Price_Increase__c)
A contract can have multiple quotes
What I want to do
When a quote has reached the final step a contract is created. In the contract I have the option to click a button called Amend. Which allows me to take the products in the existing quotes and amend it.
I want to create a batch job that does the following:
The Contract has these fields: Start Date (PROD_Start_Date__c), Price increase Date (PROD_Increase_Date__c), End Date (PROD_End_Date__c).
-- If the Price Increase Date is 12 months after the start date, these are the contracts that will need to be updated
-- For example, If the start date is 15 Feb 2023, Price increase is 1 Jan 2024, end date is 15 Feb 2025. Since the increase date is not 12 months, these contract should be ignored.
Main Task
When products who have a price increase 12 months after the start date, the contract should be able to 'amend' and update the quantity of the products and clone the products.
In the contract, the action buttons on top have "Amend". once clicked, it shows all the subscriptions products, you click next then it comes into the edit quote page.
Once here it shows all the products that were part of the contract and its quote. The net price filed for the original products will be '0'. These products will need to be cloned and the quantity for these to be applied to the cloned products. Once the quantity has been copied over, the original products quantity should change to 0.
After these products have a quantity of 0, the clone products should have the price increase. The value I mentioned from earlier Price Increase % (ROD_Price_Increase__c) value should be added to the Discount filed in the quote but as a minus value since we are doing an increase of price.
Once this has been done, we can submit/order the quote. This creates a new quote. Once the new quote has been created, I want to be able to update a filed in the quote - a checkbox that says order. I want to be able to check the value on it.
This all should be done automatically like though Apex and Flows.
Sorry for this long text and request. I apologise and know some of the information not be out of box or confusing. Its one of these challenges I have been facing with trying to automate this.

Salesforce Get a list of all opportunities which are new, updated or deleted since a given date using api

I am trying to receive a list of all opportunities that are created/updated/deleted since a given date. When I run query: SELECT Id FROM Opportunity WHERE SystemModStamp >= '2022-09-20' AND isDeleted = TRUE ALL ROWS I get a response stating "message": "ALL ROWS not allowed in this context", "errorCode": "MALFORMED_QUERY".
Going over the salesforce documentation I found out using queryAll() api method we can also get the opportunities which are created/updated/deleted. But I am not able to find an example of how to use this api. Any help in this direction would be highly appreciated.
Salesforce queryAll documentation: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_queryall.htm
Have you tried using queryAll instead of query? Start with
/services/data/v54.0/queryAll?q=SELECT+Id,+Name,+isDeleted,+StageName+FROM+Opportunity+ORDER+BY+isDeleted+DESC+LIMIT+20
and experiment, remove the ORDER BY, put filter by date...
SELECT Id, Name, isDeleted
FROM Opportunity
WHERE LastModifiedDate >2022-09-01T00:00:00Z
There's also dedicated "data replication API" which you can use to get opportunities updated / deleted in given time window (imagine an oppty that's edited 3 times in September, once in October - the last modified date will happily say October, how would you retrieve the fact it was touched in September too?). It'll give you just the IDs, you'd have to collect them and send the query for actual data - but it's something.

Salesforce How to update a roll-up summary field on parent table from inside method that gets triggered when child is persisted

I created a Commission object with field called commission_amount__c, This object has a master detail relationship with Contact. Contact Has a sum up field called Total_Commission__c which sums up all commission amounts from Commissions related to each Contact. I've put a trigger on Commission which calls the method updatePrimary. I want to get each persons total commission but when I query this inside updatePrimary I get the old value in the sumup field(total_commission) and not the new value with the new commission amount added. it hasn't summed up yet. Some help would be very much appreciated if possible.
trigger UpdatePrimaryTrigger on Commission__c (after insert, after update) {
for(Commission__c c : Trigger.New) {
ContactHandler.updatePrimary(c);
}
}
public class ContactHandler {
public static void updatePrimary(Commission__c comIn){
Contact receiverOfCommission = [Select Name, Total_commission__c
FROM Contact
Where Id = :comIn.Contact__c];
}
You're at the wrong position in the save order of execution.
Roll-up summary fields are updated on the parent object at Step 18. after triggers are executed at Step 8.
If you want to take action upon the update of your roll-up summary field, you will need to write a trigger on the parent object. However, if I understand your requirement correctly, you may be able to simply place a formula field on the Commission object referencing the roll-up summary field on the Contact.

How can I update or change cost price (standard price) in odoo v13 postgresql database?

I am trying to change the cost price of products in Odoov13 in postgresql database, can anyone please support me with an example or guide? The question is simple, there is a selling price and a cost price (standard price) on the products, I just try to change the cost price, not the selling price, but I don't know how to get to the table or column, the Only reference I have is that the value can be stored in property field, but I don't know how to access it.
SELECT * FROM ir_property WHERE name = 'standard_price';
Fini
The field standard_price is computed field without store=True So it can store the data into postgres database.
If you want to update the field value, You can make the server-action following step:
Goto Settings->Server Actions
Model : Product Template
Action To Do: Update the Record
Data to Write:
Field : Cost (product.template)
Evaluation Type: Value
Value: Add your value example, 112
make the Create Contextual Action
Goto Product template and refresh the page on the action you can find the created server action and execute.

MS Access Age Calculation across tables

I'm editing a database template so I can track differences in patient tests across age for the same person.
I retro-fit the "Student Database" template to utilize the forms and macros already created.
I have a patient table that stores all data collected at initial intake : name, date of birth (DOB), etc. and a second table that would track test scores across visits that includes : name, date of visit (DOV) and score information. These are paired so I can pull up information from one patient and see their scores across visits.
What I need to do now is create a query where I can calculate their age when they took the tests.
To do so, I have used expression builder and entered Calculated:([Visit Date]-[DOB])/365
This works for calculating age only if I re-enter the DOB in a new column on the patient visit table
I've tried using DateDiff and using [Patient]![DOB] to recall the data from the other table but I get the same error.
(Calculated age: ([Patient Visit]![Visit Date]-[Patients]![DOB])/365)
Calculated age: (DateDiff("yyyy",[Patients]![DOB],[Patient Visit]![Visit Date]))
Both spit out the error : Enter Parameter Value 'Patients!DOB'
If I enter a date, all data points and patients calculated to have the same DOB that I entered.
How do I let Access know I need it to calculate the date at visit for the DOB of the same patient?
?: Do I need to create a lookup table for the patient ID to match with the DOB and then use that field for calculation?
If there is something wrong with the expression I can fix, that would be ideal. If not, what is the best way to calculate age at visit without having to manually enter in the patient DOB more than once (once in initial uptake and again at each visit).
Thank you in advance.
I found a solution!
I was using 'query' wrong. instead of trying to force it to recognize another table, I needed to add the table to the query upon query creation.
i.e.:
1_ selected 'Query Design'
2_ selected the tables with the required information (entered through forms)
3_ Used `
Patient Name: IIf(IsNull([Last Name]),IIf(IsNull([First Name]),[First Name]),IIf(IsNull([First Name]),[Last Name],[First Name] & " " & [Last Name]))
`
for the first field and
Patient Visit.*
for the second field. By adding "Patient Visit.*" the query will add all fields from the table into the query.
The third field I selected DOB from the Patients table (it was available for selection because I had the two tables selected in the layout initially).
I am now able to use the original
Calculated:([Visit Date]-[DOB])/365
for age calculation w/o any error. I finalized formatting under properties > format > fixed.
Wooo!

Resources