LineItem.php 21.3 KB
Newer Older
totten's avatar
totten committed
1 2 3
<?php
/*
 +--------------------------------------------------------------------+
Kurund Jalmi's avatar
Kurund Jalmi committed
4
 | CiviCRM version 4.7                                                |
totten's avatar
totten committed
5
 +--------------------------------------------------------------------+
yashodha's avatar
yashodha committed
6
 | Copyright CiviCRM LLC (c) 2004-2017                                |
totten's avatar
totten committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the GNU Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
26
 */
totten's avatar
totten committed
27 28 29 30

/**
 *
 * @package CRM
yashodha's avatar
yashodha committed
31
 * @copyright CiviCRM LLC (c) 2004-2017
totten's avatar
totten committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
 * $Id$
 *
 */

/**
 *
 * @package CRM
 * @author Marshal Newrock <marshal@idealso.com>
 * $Id$
 */

/**
 * Business objects for Line Items generated by monetary transactions
 */
class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {

  /**
   * Creates a new entry in the database.
   *
51 52
   * @param array $params
   *   (reference) an assoc array of name/value pairs.
totten's avatar
totten committed
53
   *
54 55 56 57
   * @return \CRM_Price_DAO_LineItem
   *
   * @throws \CiviCRM_API3_Exception
   * @throws \Exception
totten's avatar
totten committed
58
   */
59
  public static function create(&$params) {
60 61 62
    $id = CRM_Utils_Array::value('id', $params);
    if ($id) {
      CRM_Utils_Hook::pre('edit', 'LineItem', $id, $params);
63
      $op = CRM_Core_Action::UPDATE;
64 65 66
    }
    else {
      CRM_Utils_Hook::pre('create', 'LineItem', $params['entity_id'], $params);
67
      $op = CRM_Core_Action::ADD;
68
    }
69

70 71 72 73 74
    // unset entity table and entity id in $params
    // we never update the entity table and entity id during update mode
    if ($id) {
      unset($params['entity_id'], $params['entity_table']);
    }
75 76 77 78 79
    else {
      if (!isset($params['unit_price'])) {
        $params['unit_price'] = 0;
      }
    }
80
    if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Utils_Array::value('check_permissions', $params)) {
81 82 83
      if (empty($params['financial_type_id'])) {
        throw new Exception('Mandatory key(s) missing from params array: financial_type_id');
      }
84 85
      CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
      if (!in_array($params['financial_type_id'], array_keys($types))) {
86
        throw new Exception('You do not have permission to create this line item');
87 88
      }
    }
eileen's avatar
eileen committed
89

totten's avatar
totten committed
90 91 92 93
    $lineItemBAO = new CRM_Price_BAO_LineItem();
    $lineItemBAO->copyValues($params);

    $return = $lineItemBAO->save();
94 95 96 97 98 99 100 101 102
    if ($lineItemBAO->entity_table == 'civicrm_membership' && $lineItemBAO->contribution_id && $lineItemBAO->entity_id) {
      $membershipPaymentParams = array(
        'membership_id' => $lineItemBAO->entity_id,
        'contribution_id' => $lineItemBAO->contribution_id,
      );
      if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
        civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
      }
    }
totten's avatar
totten committed
103

104
    if ($id) {
105
      CRM_Utils_Hook::post('edit', 'LineItem', $id, $lineItemBAO);
106 107
    }
    else {
108
      CRM_Utils_Hook::post('create', 'LineItem', $lineItemBAO->id, $lineItemBAO);
109
    }
totten's avatar
totten committed
110 111 112 113 114

    return $return;
  }

  /**
115 116 117
   * Retrieve DB object based on input parameters.
   *
   * It also stores all the retrieved values in the default array.
totten's avatar
totten committed
118
   *
119 120 121 122
   * @param array $params
   *   (reference ) an assoc array of name/value pairs.
   * @param array $defaults
   *   (reference ) an assoc array to hold the flattened values.
totten's avatar
totten committed
123
   *
124
   * @return CRM_Price_BAO_LineItem
totten's avatar
totten committed
125
   */
126
  public static function retrieve(&$params, &$defaults) {
totten's avatar
totten committed
127 128 129 130 131 132 133 134 135
    $lineItem = new CRM_Price_BAO_LineItem();
    $lineItem->copyValues($params);
    if ($lineItem->find(TRUE)) {
      CRM_Core_DAO::storeValues($lineItem, $defaults);
      return $lineItem;
    }
    return NULL;
  }

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  /**
   * Modifies $params array for filtering financial types.
   *
   * @param array $params
   *   (reference ) an assoc array of name/value pairs.
   *
   */
  public static function getAPILineItemParams(&$params) {
    CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types);
    if ($types && empty($params['financial_type_id'])) {
      $params['financial_type_id'] = array('IN' => array_keys($types));
    }
    elseif ($types) {
      if (is_array($params['financial_type_id'])) {
        $invalidFts = array_diff($params['financial_type_id'], array_keys($types));
      }
      elseif (!in_array($params['financial_type_id'], array_keys($types))) {
        $invalidFts = $params['financial_type_id'];
      }
      if ($invalidFts) {
        $params['financial_type_id'] = array('NOT IN' => $invalidFts);
      }
    }
    else {
      $params['financial_type_id'] = 0;
    }
  }

164
  /**
165
   * @param int $contributionId
166 167 168
   *
   * @return null|string
   */
169
  public static function getLineTotal($contributionId) {
170
    $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
171
FROM civicrm_line_item li
172 173 174
WHERE li.contribution_id = %1";
    $params = array(1 => array($contributionId, 'Integer'));
    $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal, $params);
175 176 177
    return $lineItemTotal;
  }

178
  /**
179
   * Wrapper for line item retrieval when contribution ID is known.
colemanw's avatar
colemanw committed
180
   * @param int $contributionID
181 182 183
   *
   * @return array
   */
184
  public static function getLineItemsByContributionID($contributionID) {
totten's avatar
totten committed
185
    return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
186 187
  }

totten's avatar
totten committed
188 189 190 191
  /**
   * Given a participant id/contribution id,
   * return contribution/fee line items
   *
colemanw's avatar
colemanw committed
192 193 194 195
   * @param int $entityId
   *   participant/contribution id.
   * @param string $entity
   *   participant/contribution.
totten's avatar
totten committed
196
   *
197
   * @param bool $isQuick
Eileen McNaughton's avatar
Eileen McNaughton committed
198
   * @param bool $isQtyZero
199
   * @param bool $relatedEntity
Eileen McNaughton's avatar
Eileen McNaughton committed
200
   *
Web Access's avatar
Web Access committed
201
   * @param bool $invoice
202
   * @return array
203
   *   Array of line items
totten's avatar
totten committed
204
   */
205
  public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE, $invoice = FALSE) {
206
    $whereClause = $fromClause = NULL;
totten's avatar
totten committed
207 208 209
    $selectClause = "
      SELECT    li.id,
      li.label,
210
      li.contribution_id,
totten's avatar
totten committed
211 212 213
      li.qty,
      li.unit_price,
      li.line_total,
214 215
      li.entity_table,
      li.entity_id,
totten's avatar
totten committed
216 217
      pf.label as field_title,
      pf.html_type,
218
      pf.price_set_id,
totten's avatar
totten committed
219
      pfv.membership_type_id,
220
      pfv.membership_num_terms,
totten's avatar
totten committed
221 222 223
      li.price_field_id,
      li.participant_count,
      li.price_field_value_id,
Pradeep Nayak's avatar
Pradeep Nayak committed
224
      li.financial_type_id,
225
      li.tax_amount,
totten's avatar
totten committed
226 227
      pfv.description";

228 229 230 231 232
    $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
    if ($relatedEntity) {
      $condition = "li.contribution_id = %2.id ";
    }

totten's avatar
totten committed
233 234
    $fromClause = "
      FROM      civicrm_%2 as %2
235
      LEFT JOIN civicrm_line_item li ON ({$condition})
totten's avatar
totten committed
236 237 238 239 240
      LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
      LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
    $whereClause = "
      WHERE     %2.id = %1";

Web Access's avatar
Web Access committed
241 242
    // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any)
    if ($entity == 'participant' && $invoice) {
243 244
      $additionalParticipantIDs = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
      if (!empty($additionalParticipantIDs)) {
jitendrapurohit's avatar
jitendrapurohit committed
245
        $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
246 247 248
      }
    }

249 250
    $orderByClause = " ORDER BY pf.weight, pfv.weight";

totten's avatar
totten committed
251 252 253 254
    if ($isQuick) {
      $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
      $whereClause .= " and cps.is_quick_config = 0";
    }
255 256 257 258 259

    if (!$isQtyZero) {
      $whereClause .= " and li.qty != 0";
    }

totten's avatar
totten committed
260 261 262 263 264 265 266 267 268 269 270
    $lineItems = array();

    if (!$entityId || !$entity || !$fromClause) {
      return $lineItems;
    }

    $params = array(
      1 => array($entityId, 'Integer'),
      2 => array($entity, 'Text'),
    );

271
    $getTaxDetails = FALSE;
272
    $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
273
    $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
274

275
    $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
totten's avatar
totten committed
276 277 278 279 280
    while ($dao->fetch()) {
      if (!$dao->id) {
        continue;
      }
      $lineItems[$dao->id] = array(
jitendrapurohit's avatar
jitendrapurohit committed
281
        'qty' => (float) $dao->qty,
totten's avatar
totten committed
282 283 284 285 286 287 288 289 290
        'label' => $dao->label,
        'unit_price' => $dao->unit_price,
        'line_total' => $dao->line_total,
        'price_field_id' => $dao->price_field_id,
        'participant_count' => $dao->participant_count,
        'price_field_value_id' => $dao->price_field_value_id,
        'field_title' => $dao->field_title,
        'html_type' => $dao->html_type,
        'description' => $dao->description,
291
        'entity_id' => $dao->entity_id,
292
        'entity_table' => $dao->entity_table,
293
        'contribution_id' => $dao->contribution_id,
Pradeep Nayak's avatar
Pradeep Nayak committed
294
        'financial_type_id' => $dao->financial_type_id,
295
        'financial_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id),
totten's avatar
totten committed
296
        'membership_type_id' => $dao->membership_type_id,
297
        'membership_num_terms' => $dao->membership_num_terms,
298
        'tax_amount' => $dao->tax_amount,
299
        'price_set_id' => $dao->price_set_id,
totten's avatar
totten committed
300
      );
301 302 303 304 305 306 307 308 309
      $taxRates = CRM_Core_PseudoConstant::getTaxRates();
      if (isset($lineItems[$dao->id]['financial_type_id']) && array_key_exists($lineItems[$dao->id]['financial_type_id'], $taxRates)) {
        // We are close to output/display here - so apply some rounding at output/display level - to not show Tax Rate in all 8 decimals
        $lineItems[$dao->id]['tax_rate'] = round($taxRates[$lineItems[$dao->id]['financial_type_id']], 3);
      }
      else {
        // There is no Tax Rate associated with this Financial Type
        $lineItems[$dao->id]['tax_rate'] = FALSE;
      }
310
      $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
311 312 313
      if ($lineItems[$dao->id]['tax_amount'] != '') {
        $getTaxDetails = TRUE;
      }
totten's avatar
totten committed
314
    }
315 316 317 318 319 320
    if ($invoicing) {
      $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
      $smarty = CRM_Core_Smarty::singleton();
      $smarty->assign('taxTerm', $taxTerm);
      $smarty->assign('getTaxDetails', $getTaxDetails);
    }
totten's avatar
totten committed
321 322 323 324 325 326 327
    return $lineItems;
  }

  /**
   * This method will create the lineItem array required for
   * processAmount method
   *
328 329 330 331 332
   * @param int $fid
   *   Price set field id.
   * @param array $params
   *   Reference to form values.
   * @param array $fields
333
   *   Array of fields belonging to the price set used for particular event
334 335
   * @param array $values
   *   Reference to the values array(.
336
   *   this is
totten's avatar
totten committed
337
   *                          lineItem array)
338
   * @param string $amount_override
totten's avatar
totten committed
339
   */
340
  public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
totten's avatar
totten committed
341 342 343 344 345 346 347 348 349 350 351
    if (empty($params["price_{$fid}"])) {
      return;
    }

    //lets first check in fun parameter,
    //since user might modified w/ hooks.
    $options = array();
    if (array_key_exists('options', $fields)) {
      $options = $fields['options'];
    }
    else {
352
      CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
totten's avatar
totten committed
353 354 355
    }
    $fieldTitle = CRM_Utils_Array::value('label', $fields);
    if (!$fieldTitle) {
356
      $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
totten's avatar
totten committed
357 358 359
    }

    foreach ($params["price_{$fid}"] as $oid => $qty) {
360
      $price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
totten's avatar
totten committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

      // lets clean the price in case it is not yet cleant
      // CRM-10974
      $price = CRM_Utils_Rule::cleanMoney($price);

      $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);

      $values[$oid] = array(
        'price_field_id' => $fid,
        'price_field_value_id' => $oid,
        'label' => CRM_Utils_Array::value('label', $options[$oid]),
        'field_title' => $fieldTitle,
        'description' => CRM_Utils_Array::value('description', $options[$oid]),
        'qty' => $qty,
        'unit_price' => $price,
        'line_total' => $qty * $price,
        'participant_count' => $qty * $participantsPerField,
        'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
        'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
        'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
        'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
        'html_type' => $fields['html_type'],
Pradeep Nayak's avatar
Pradeep Nayak committed
383
        'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
384
        'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
385
        'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $options[$oid]),
totten's avatar
totten committed
386
      );
387

monishdeb's avatar
monishdeb committed
388
      if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
eileen's avatar
eileen committed
389
        $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
totten's avatar
totten committed
390 391 392 393 394 395 396 397 398 399
      }
    }
  }

  /**
   * Delete line items for given entity.
   *
   * @param int $entityId
   * @param int $entityTable
   *
400
   * @return bool
totten's avatar
totten committed
401
   */
eileen's avatar
eileen committed
402
  public static function deleteLineItems($entityId, $entityTable) {
totten's avatar
totten committed
403
    if (!$entityId || !$entityTable) {
404
      return FALSE;
totten's avatar
totten committed
405 406 407 408 409 410
    }

    if ($entityId && !is_array($entityId)) {
      $entityId = array($entityId);
    }

Pradeep Nayak's avatar
Pradeep Nayak committed
411
    $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
totten's avatar
totten committed
412
    $dao = CRM_Core_DAO::executeQuery($query);
413
    return TRUE;
totten's avatar
totten committed
414 415 416
  }

  /**
colemanw's avatar
colemanw committed
417
   * Process price set and line items.
Eileen McNaughton's avatar
Eileen McNaughton committed
418
   *
colemanw's avatar
colemanw committed
419
   * @param int $entityId
420 421
   * @param array $lineItem
   *   Line item array.
totten's avatar
totten committed
422
   * @param object $contributionDetails
423 424
   * @param string $entityTable
   *   Entity table.
totten's avatar
totten committed
425
   *
Eileen McNaughton's avatar
Eileen McNaughton committed
426 427
   * @param bool $update
   *
totten's avatar
totten committed
428 429
   * @return void
   */
430
  public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
totten's avatar
totten committed
431 432 433 434 435
    if (!$entityId || !is_array($lineItem)
      || CRM_Utils_system::isNull($lineItem)
    ) {
      return;
    }
eileen's avatar
eileen committed
436

437
    foreach ($lineItem as $priceSetId => &$values) {
totten's avatar
totten committed
438 439 440 441
      if (!$priceSetId) {
        continue;
      }

442
      foreach ($values as &$line) {
443 444 445
        if (empty($line['entity_table'])) {
          $line['entity_table'] = $entityTable;
        }
446 447 448
        if (empty($line['entity_id'])) {
          $line['entity_id'] = $entityId;
        }
449
        if (!empty($line['membership_type_id'])) {
450
          $line['entity_table'] = 'civicrm_membership';
451
        }
452 453 454 455
        if (!empty($contributionDetails->id)) {
          $line['contribution_id'] = $contributionDetails->id;
          if ($line['entity_table'] == 'civicrm_contribution') {
            $line['entity_id'] = $contributionDetails->id;
456
          }
457 458
          // CRM-19094: entity_table is set to civicrm_membership then ensure
          // the entityId is set to membership ID not contribution by default
deb.monish's avatar
deb.monish committed
459
          elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id) {
460 461 462
            $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
            $line['entity_id'] = $membershipId ? $membershipId : $line['entity_id'];
          }
463
        }
464

totten's avatar
totten committed
465 466
        // if financial type is not set and if price field value is NOT NULL
        // get financial type id of price field value
467
        if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
468
          $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
totten's avatar
totten committed
469 470 471
        }
        $lineItems = CRM_Price_BAO_LineItem::create($line);
        if (!$update && $contributionDetails) {
472 473
          $financialItem = CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
          $line['financial_item_id'] = $financialItem->id;
474
          if (!empty($line['tax_amount'])) {
475 476
            CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
          }
totten's avatar
totten committed
477 478 479
        }
      }
    }
480 481 482
    if (!$update && $contributionDetails) {
      CRM_Core_BAO_FinancialTrxn::createDeferredTrxn($lineItem, $contributionDetails);
    }
eileen's avatar
eileen committed
483
  }
totten's avatar
totten committed
484

485
  /**
colemanw's avatar
colemanw committed
486
   * @param int $entityId
487 488
   * @param string $entityTable
   * @param $amount
colemanw's avatar
colemanw committed
489
   * @param array $otherParams
490
   */
totten's avatar
totten committed
491
  public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
totten's avatar
totten committed
492
    if (!$entityId || CRM_Utils_System::isNull($amount)) {
totten's avatar
totten committed
493
      return;
totten's avatar
totten committed
494
    }
totten's avatar
totten committed
495 496 497 498 499

    $from = " civicrm_line_item li
      LEFT JOIN   civicrm_price_field pf ON pf.id = li.price_field_id
      LEFT JOIN   civicrm_price_set ps ON ps.id = pf.price_set_id ";

eileen's avatar
eileen committed
500
    $set = " li.unit_price = %3,
totten's avatar
totten committed
501 502
      li.line_total = %3 ";

eileen's avatar
eileen committed
503
    $where = " li.entity_id = %1 AND
totten's avatar
totten committed
504 505 506 507 508 509 510 511 512 513 514
      li.entity_table = %2 ";

    $params = array(
      1 => array($entityId, 'Integer'),
      2 => array($entityTable, 'String'),
      3 => array($amount, 'Float'),
    );

    if ($entityTable == 'civicrm_contribution') {
      $entityName = 'default_contribution_amount';
      $where .= " AND ps.name = %4 ";
eileen's avatar
eileen committed
515 516
      $params[4] = array($entityName, 'String');
    }
totten's avatar
totten committed
517 518 519 520 521 522 523
    elseif ($entityTable == 'civicrm_participant') {
      $from .= "
        LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
        LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
      $set .= " ,li.label = %4,
        li.price_field_value_id = cpfv.id ";
      $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
totten's avatar
totten committed
524
      $amount = empty($amount) ? 0 : $amount;
totten's avatar
totten committed
525 526 527 528 529 530
      $params += array(
        4 => array($otherParams['fee_label'], 'String'),
        5 => array($otherParams['event_id'], 'String'),
      );
    }

eileen's avatar
eileen committed
531
    $query = "
totten's avatar
totten committed
532 533
      UPDATE $from
      SET    $set
eileen's avatar
eileen committed
534
      WHERE  $where
totten's avatar
totten committed
535 536 537 538 539
      ";

    CRM_Core_DAO::executeQuery($query, $params);
  }

totten's avatar
totten committed
540
  /**
colemanw's avatar
colemanw committed
541
   * Build line items array.
eileenmcnaugton's avatar
eileenmcnaugton committed
542
   *
543 544
   * @param array $params
   *   Form values.
totten's avatar
totten committed
545
   *
546 547
   * @param string $entityId
   *   Entity id.
totten's avatar
totten committed
548
   *
549 550
   * @param string $entityTable
   *   Entity Table.
totten's avatar
totten committed
551
   *
eileenmcnaugton's avatar
eileenmcnaugton committed
552
   * @param bool $isRelatedID
totten's avatar
totten committed
553
   */
554
  public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
eileen's avatar
eileen committed
555

totten's avatar
totten committed
556
    if (!$entityId) {
557 558 559
      $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
      $totalAmount = CRM_Utils_Array::value('total_amount', $params);
      $financialType = CRM_Utils_Array::value('financial_type_id', $params);
totten's avatar
totten committed
560
      foreach ($priceSetDetails as $values) {
561
        if ($entityTable == 'membership') {
562 563 564 565 566 567 568 569
          if ($isRelatedID != $values['membership_type_id']) {
            continue;
          }
          if (!$totalAmount) {
            $totalAmount = $values['amount'];
          }
          $financialType = $values['financial_type_id'];
        }
totten's avatar
totten committed
570 571 572 573 574
        $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
          'price_field_id' => $values['priceFieldID'],
          'price_field_value_id' => $values['priceFieldValueID'],
          'label' => $values['label'],
          'qty' => 1,
575 576 577
          'unit_price' => $totalAmount,
          'line_total' => $totalAmount,
          'financial_type_id' => $financialType,
578
          'membership_type_id' => $values['membership_type_id'],
totten's avatar
totten committed
579
        );
580
        break;
totten's avatar
totten committed
581
      }
eileen's avatar
eileen committed
582
    }
totten's avatar
totten committed
583 584
    else {
      $setID = NULL;
Pradeep Nayak's avatar
Pradeep Nayak committed
585
      $totalEntityId = count($entityId);
586 587 588
      if ($entityTable == 'contribution') {
        $isRelatedID = TRUE;
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
589
      foreach ($entityId as $id) {
590
        $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
Pradeep Nayak's avatar
Pradeep Nayak committed
591
        foreach ($lineItems as $key => $values) {
592
          if (!$setID && $values['price_field_id']) {
593 594
            $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
            $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
Pradeep Nayak's avatar
Pradeep Nayak committed
595
          }
596
          if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
totten's avatar
totten committed
597 598
            && $totalEntityId == 1
          ) {
Pradeep Nayak's avatar
Pradeep Nayak committed
599 600 601 602
            $values['line_total'] = $values['unit_price'] = $params['total_amount'];
          }
          $values['id'] = $key;
          $params['line_item'][$setID][$key] = $values;
totten's avatar
totten committed
603 604 605 606
        }
      }
    }
  }
607

totten's avatar
totten committed
608
}