Create Cart Price Rule and generate Coupon Codes programmatically

Magento provides the Cart Price Rules marketing feature, which allows applying discounts to items in the shopping cart, based on a set of conditions. The discount can be applied automatically as soon as the conditions are met, or when the customer enters a valid coupon code. The coupon codes can be generated per cart price rule via admin panel in Marketing -> Cart Price Rulessection. However, sometimes we need to automate this process. Let’s find out how to create a cart price rule and generate coupon codes programmatically in Magento 2.

The startSetup() and endSetup() methods are commonly used for schema and data setup scripts by many developers. But do we actually need to call these methods for every install or upgrade script implementation? The correct answer may be quite unexpected. :) No, we don’t need to use these methods by default in our setup scripts in most cases. Let’s find out why.

All orders have an order status that is associated with a stage in the order processing workflow.
The state describes the position of an order in the workflow. By default, Magento store has a set of predefined order statuses and order state settings. All the available order statuses can be found in admin panel under Stores -> Settings -> Order Status. Sometimes we need to create a new order status and state. Let’s figure out how to create a new order state and status programmatically in Magento 2.