3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Api4\PriceField
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * This class is intended to become the object to manage orders, including via Order.api.
23 * As of writing it is in the process of having appropriate functions built up.
24 * It should **NOT** be accessed directly outside of tested core methods as it
27 class CRM_Financial_BAO_Order
{
34 protected $priceSetID;
37 * Selected price items in the format we see in forms.
40 * [price_3 => 4, price_10 => 7]
41 * is equivalent to 'option_value 4 for radio price field 3 and
42 * a quantity of 7 for text price field 10.
46 protected $priceSelection = [];
49 * Override for financial type id.
51 * Used when the financial type id is to be overridden for all line items
52 * (as can happen in backoffice forms)
56 protected $overrideFinancialTypeID;
59 * Override for the total amount of the order.
61 * When there is a single line item the order total may be overriden.
65 protected $overrideTotalAmount;
68 * Line items in the order.
72 protected $lineItems = [];
75 * Metadata for price fields.
79 protected $priceFieldMetadata = [];
84 * @return \CRM_Core_Form|NULL
86 public function getForm(): ?CRM_Core_Form
{
93 * @param \CRM_Core_Form|NULL $form
95 public function setForm(?CRM_Core_Form
$form): void
{
100 * The serialize & unserialize functions are to prevent the form being serialized & stored.
102 * The form could be potentially large & circular.
104 * We simply serialize the values needed to re-serialize the form.
108 public function _serialize(): array {
110 'OverrideTotalAmount' => $this->getOverrideTotalAmount(),
111 'OverrideFinancialType' => $this->getOverrideFinancialTypeID(),
112 'PriceSelection' => $this->getPriceSelection(),
117 * Re-instantiate the the class with non-calculated variables.
121 public function _unserialize(array $data): void
{
122 foreach ($data as $key => $value) {
129 * Form object - if present the buildAmount hook will be called.
131 * @var \CRM_Member_Form_Membership|\CRM_Member_Form_MembershipRenewal
136 * Get Set override for total amount of the order.
138 * @return float|false
140 public function getOverrideTotalAmount() {
141 if (count($this->getPriceOptions()) !== 1) {
144 return $this->overrideTotalAmount ??
FALSE;
148 * Set override for total amount.
150 * @param float $overrideTotalAmount
152 public function setOverrideTotalAmount(float $overrideTotalAmount): void
{
153 $this->overrideTotalAmount
= $overrideTotalAmount;
157 * Get override for total amount.
161 public function getOverrideFinancialTypeID() {
162 if (count($this->getPriceOptions()) !== 1) {
165 return $this->overrideFinancialTypeID ??
FALSE;
169 * Set override for financial type ID.
171 * @param int $overrideFinancialTypeID
173 public function setOverrideFinancialTypeID(int $overrideFinancialTypeID) {
174 $this->overrideFinancialTypeID
= $overrideFinancialTypeID;
178 * Getter for price set id.
182 public function getPriceSetID(): int {
183 return $this->priceSetID
;
187 * Setter for price set id.
189 * @param int $priceSetID
191 public function setPriceSetID(int $priceSetID) {
192 $this->priceSetID
= $priceSetID;
196 * Getter for price selection.
200 public function getPriceSelection(): array {
201 return $this->priceSelection
;
205 * Setter for price selection.
207 * @param array $priceSelection
209 public function setPriceSelection(array $priceSelection) {
210 $this->priceSelection
= $priceSelection;
214 * Price options the simplified price fields selections.
216 * ie. the 'price_' is stripped off the key name and the field ID
217 * is cast to an integer.
221 public function getPriceOptions():array {
223 foreach ($this->getPriceSelection() as $fieldName => $value) {
224 $fieldID = substr($fieldName, 6);
225 $priceOptions[(int) $fieldID] = $value;
227 return $priceOptions;
231 * Get the metadata for the given field.
237 public function getPriceFieldSpec(int $id) :array {
238 return $this->getPriceFieldsMetadata()[$id];
242 * Get the metadata for the fields in the price set.
246 public function getPriceFieldsMetadata(): array {
247 if (empty($this->priceFieldMetadata
)) {
248 $this->priceFieldMetadata
= CRM_Price_BAO_PriceSet
::getCachedPriceSetDetail($this->getPriceSetID())['fields'];
249 if ($this->getForm()) {
250 CRM_Utils_Hook
::buildAmount($this->form
->getFormContext(), $this->form
, $this->priceFieldMetadata
);
253 return $this->priceFieldMetadata
;
257 * Set the price field selection from an array of params containing price fields.
259 * This function takes the sort of 'anything & everything' parameters that come in from the
260 * form layer and filters them before assigning them to the priceSelection property.
262 * @param array $input
264 public function setPriceSelectionFromUnfilteredInput(array $input): void
{
265 foreach ($input as $fieldName => $value) {
266 if (strpos($fieldName, 'price_') === 0) {
267 $fieldID = substr($fieldName, 6);
268 if (is_numeric($fieldID)) {
269 $this->priceSelection
[$fieldName] = $value;
280 * @throws \CiviCRM_API3_Exception
282 public function getLineItems():array {
283 if (empty($this->lineItems
)) {
284 $this->lineItems
= $this->calculateLineItems();
286 return $this->lineItems
;
291 * @throws \CiviCRM_API3_Exception
293 protected function calculateLineItems(): array {
295 $params = $this->getPriceSelection();
296 if ($this->getOverrideTotalAmount() !== FALSE) {
297 // We need to do this to keep getLine from doing weird stuff but the goal
298 // is to ditch getLine next round of refactoring
299 // and make the code more sane.
300 $params['total_amount'] = $this->getOverrideTotalAmount();
303 foreach ($this->getPriceOptions() as $fieldID => $valueID) {
304 if (!isset($this->priceSetID
)) {
305 $this->setPriceSetID(PriceField
::get()->addSelect('price_set_id')->addWhere('id', '=', $fieldID)->execute()->first()['price_set_id']);
307 $throwAwayArray = [];
308 // @todo - still using getLine for now but better to bring it to this class & do a better job.
309 $newLines = CRM_Price_BAO_PriceSet
::getLine($params, $throwAwayArray, $this->getPriceSetID(), $this->getPriceFieldSpec($fieldID), $fieldID)[1];
310 foreach ($newLines as $newLine) {
311 $lineItems[$newLine['price_field_value_id']] = $newLine;
315 foreach ($lineItems as &$lineItem) {
316 // Set any pre-calculation to zero as we will calculate.
317 $lineItem['tax_amount'] = 0;
318 if ($this->getOverrideFinancialTypeID() !== FALSE) {
319 $lineItem['financial_type_id'] = $this->getOverrideFinancialTypeID();
321 $taxRate = $this->getTaxRate((int) $lineItem['financial_type_id']);
322 if ($this->getOverrideTotalAmount() !== FALSE) {
324 // Total is tax inclusive.
325 $lineItem['tax_amount'] = ($taxRate / 100) * $this->getOverrideTotalAmount() / (1 +
($taxRate / 100));
326 $lineItem['line_total'] = $lineItem['unit_price'] = $this->getOverrideTotalAmount() - $lineItem['tax_amount'];
329 $lineItem['line_total'] = $lineItem['unit_price'] = $this->getOverrideTotalAmount();
333 $lineItem['tax_amount'] = ($taxRate / 100) * $lineItem['line_total'];
340 * Get the total amount for the order.
344 * @throws \CiviCRM_API3_Exception
346 public function getTotalTaxAmount() :float {
348 foreach ($this->getLineItems() as $lineItem) {
349 $amount +
= $lineItem['tax_amount'] ??
0.0;
355 * Get the total tax amount for the order.
359 * @throws \CiviCRM_API3_Exception
361 public function getTotalAmount() :float {
363 foreach ($this->getLineItems() as $lineItem) {
364 $amount +
= $lineItem['line_total'] ??
0.0;
370 * Get the tax rate for the given financial type.
372 * @param int $financialTypeID
376 public function getTaxRate(int $financialTypeID) {
377 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
378 if (!isset($taxRates[$financialTypeID])) {
381 return $taxRates[$financialTypeID];