I am trying to add a markup based on a percentage (eg. 30%) onto the cost prices of products. I am thinking of separating different markups/percentages in different product variation types in the Commerce module. Therefore, I can create products starting based on what markup they should be. In the administration or products menu, I want to be able to see both the cost and marked up price for accounting. It would also be a good idea to retrieve the desired markup from a field in the UI (maybe default value?), so it wouldn’t be hard coded.
I’ve been referring to these two articles: https://www.rapiddg.com/article/modifying-product-prices-drupal-commerce-2-drupal-8
https://dev.studiopresent.com/blog/back-end/drupal-commerce-2-and-sale-price
Here’s the code I came up with:
markup_20 = production variation type machine name
<?php namespace DrupalmarkupResolvers; use DrupalcommerceContext; use DrupalcommercePurchasableEntityInterface; use Drupalcommerce_pricePrice; use Drupalcommerce_priceResolverPriceResolverInterface; /** * Class MarkupResolver. * * @package DrupalmarkupResolvers */ class MarkupResolver implements PriceResolverInterface { /** * {@inheritdoc} */ public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) { if (!$entity->id('markup_20')) { return $entity->getPrice()->multiply('1.20'); $markup_price = $entity->get('field_markup_price'); return new Price($markup_price); } return $entity->getPrice(); } }