@arthurke
Hie,
You can easily achieve this with a custom script logic, please do follow the link to get a clear idea.
Also please refer the manual for any similar related topics like a discount or setting margin on selling or buying
https://erpnext.com/docs/user/manual/en/accounts/pricing-rule