Edit.php 9.89 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
<?php

require_once 'CRM/Core/Form.php';

/**
 * Form controller class
 *
 * @see http://wiki.civicrm.org/confluence/display/CRMDOC43/QuickForm+Reference
 */
class CRM_Lineitemedit_Form_Edit extends CRM_Core_Form {
Monish Deb's avatar
Monish Deb committed
11
12
13
14

  /**
   * The line-item values of an existing contribution
   */
Monish Deb's avatar
Monish Deb committed
15
16
17

  public $_id;

Monish Deb's avatar
Monish Deb committed
18
19
  public $_values;

20
21
22
  public $_isQuickConfig = FALSE;

  public $_priceFieldInfo = array();
Monish Deb's avatar
Monish Deb committed
23

24
25
  protected $_lineitemInfo;

Monish Deb's avatar
Monish Deb committed
26
27
  public function preProcess() {
    $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
Monish Deb's avatar
Monish Deb committed
28
29
    $this->assignFormVariables();
  }
Monish Deb's avatar
Monish Deb committed
30

31
32
33
34
35
36
37
38
39
40
  /**
   * Check if there is tax value for selected financial type.
   * @param $financialTypeId
   * @return bool
   */
  private function isTaxEnabledInFinancialType($financialTypeId) {
    $taxRates = CRM_Core_PseudoConstant::getTaxRates();
    return (isset($taxRates[$financialTypeId])) ? TRUE : FALSE;
  }

41
  public function assignFormVariables($params = []) {
42

43
    $this->_lineitemInfo = civicrm_api3('lineItem', 'getsingle', array('id' => $this->_id));
44
    $this->_lineitemInfo['tax_amount'] = CRM_Utils_Array::value('tax_amount', $this->_lineitemInfo, 0.00);
Monish Deb's avatar
Monish Deb committed
45
    foreach (CRM_Lineitemedit_Util::getLineitemFieldNames() as $attribute) {
46
      $this->_values[$attribute] = CRM_Utils_Array::value($attribute, $this->_lineitemInfo, 0);
Monish Deb's avatar
Monish Deb committed
47
48
49
50
    }

    $this->_values['currency'] = CRM_Core_DAO::getFieldValue(
      'CRM_Financial_DAO_Currency',
51
      CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_lineitemInfo['contribution_id'], 'currency'),
Monish Deb's avatar
Monish Deb committed
52
53
54
      'symbol',
      'name'
    );
55

Monish Deb's avatar
Monish Deb committed
56
    $this->_isQuickConfig = empty($this->_lineitemInfo['price_field_id']);
57

Monish Deb's avatar
Monish Deb committed
58
    if (!empty($this->_lineitemInfo['price_field_id'])) {
59
      $this->_priceFieldInfo = civicrm_api3('PriceField', 'getsingle', array('id' => $this->_lineitemInfo['price_field_id']));
Monish Deb's avatar
Monish Deb committed
60
      $this->_isQuickConfig = (bool) CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceFieldInfo['price_set_id'], 'is_quick_config');
61
    }
Monish Deb's avatar
Monish Deb committed
62

63
    if ($this->_isQuickConfig || empty($this->_priceFieldInfo['is_enter_qty'])) {
Monish Deb's avatar
Monish Deb committed
64
65
      $this->_values['qty'] = (int) $this->_values['qty'];
    }
Monish Deb's avatar
Monish Deb committed
66
67
68
69
70
71
72
73
  }

  /**
   * Set default values.
   *
   * @return array
   */
  public function setDefaultValues() {
Edselopez's avatar
Edselopez committed
74
75
76
77
78
79
    // Fetch chapter and fund codes.
    $codes = CRM_Core_DAO::executeQuery("SELECT chapter_code, fund_code FROM civicrm_chapter_entity WHERE entity_table = 'civicrm_line_item' AND entity_id = {$this->_lineitemInfo['id']}")->fetchAll()[0];
    if (!empty($codes)) {
      $this->_values['chapter_code'] = $codes['chapter_code'];
      $this->_values['fund_code'] = $codes['fund_code'];
    }
Monish Deb's avatar
Monish Deb committed
80
81
82
    return $this->_values;
  }

83
  public function buildQuickForm() {
Edselopez's avatar
Edselopez committed
84
85
    $fields = $this->_values;
    $fieldNames = array_keys($fields);
Monish Deb's avatar
Monish Deb committed
86
    foreach ($fieldNames as $fieldName) {
87
      $required = TRUE;
Monish Deb's avatar
Monish Deb committed
88
      if ($fieldName == 'line_total') {
89
90
91
92
93
        $this->add('text', 'line_total', ts('Total amount'), array(
          'size' => 6,
          'maxlength' => 14,
          'readonly' => TRUE)
        );
Monish Deb's avatar
Monish Deb committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
        continue;
      }
      elseif ($fieldName == 'currency') {
        $this->assign('currency', $this->_values['currency']);
        continue;
      }
      $properties = array(
        'entity' => 'LineItem',
        'name' => $fieldName,
        'context' => 'edit',
        'action' => 'create',
      );
      if ($fieldName == 'financial_type_id') {
        CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
        $properties['options'] = $financialTypes;
      }
110
      // In case of text non-quickconfig price field we cannot change the unit price
111
      elseif ($fieldName == 'tax_amount') {
112
        $properties['readonly'] = TRUE;
113
        $required = FALSE;
114
      }
115

Monish Deb's avatar
Monish Deb committed
116
117
118
119
      $ele = $this->addField($fieldName, $properties, $required);
      if ($this->_lineitemInfo['entity_table'] != 'civicrm_contribution' && $fieldName == 'financial_type_id') {
        $ele->freeze();
      }
Monish Deb's avatar
Monish Deb committed
120
    }
Edselopez's avatar
Edselopez committed
121
122
123
124
125
126
127
128
129
    // Add chapter codes.
    $chapterCodes = CRM_Core_OptionGroup::values('chapter_codes');
    $this->add('select', 'chapter_code',
      ts('Chapter Code'),
      $chapterCodes
    );
    // Add fund codes.
    $fundCodes = CRM_Core_OptionGroup::values('fund_codes');
    $this->add('select', 'fund_code',
130
      ts('Fund Code'),
Edselopez's avatar
Edselopez committed
131
132
      $fundCodes
    );
Monish Deb's avatar
Monish Deb committed
133
134
    $this->assign('fieldNames', $fieldNames);

Monish Deb's avatar
Monish Deb committed
135
136
    $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));

137
138
    $this->assign('isTaxEnabled', $this->isTaxEnabledInFinancialType($this->_values['financial_type_id']));

139
140
    $this->addFormRule(array(__CLASS__, 'formRule'), $this);

141
142
143
144
145
146
    $this->addButtons(array(
      array(
        'type' => 'submit',
        'name' => ts('Submit'),
        'isDefault' => TRUE,
      ),
147
148
      array(
        'type' => 'cancel',
Monish Deb's avatar
Monish Deb committed
149
        'name' => ts('Close'),
150
      ),
151
152
153
154
155
    ));

    parent::buildQuickForm();
  }

156
157
158
  public static function formRule($fields, $files, $self) {
    $errors = array();

159
160
161
162
163
    if (!CRM_Utils_Rule::integer($fields['qty'])) {
      if ($self->_isQuickConfig || $self->_priceFieldInfo['is_enter_qty'] == 0) {
        $errors['qty'] = ts('Please enter a whole number quantity');
      }
    }
164
165
166
167

    return $errors;
  }

168
169
  public function postProcess() {
    $values = $this->exportValues();
Monish Deb's avatar
Monish Deb committed
170
171
172
173
    $this->submit($values);
    parent::postProcess();
  }

174
  public function submit($values, $isTest = FALSE) {
175
    $values['line_total'] = CRM_Utils_Rule::cleanMoney($values['line_total']);
176
177

    $balanceAmount = ($values['line_total'] - $this->_lineitemInfo['line_total']);
178
179
180
181
    $contactId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution',
      $this->_lineitemInfo['contribution_id'],
      'contact_id'
    );
182
183
184
185

    if (!$this->isTaxEnabledInFinancialType($values['financial_type_id'])) {
      $values['tax_amount'] = '';
    }
186
    $params = array(
187
188
189
190
      'id' => $this->_id,
      'financial_type_id' => $values['financial_type_id'],
      'label' => $values['label'],
      'qty' => $values['qty'],
191
      'unit_price' => CRM_Utils_Rule::cleanMoney($values['unit_price']),
192
      'line_total' => $values['line_total'],
193
194
      'tax_amount' => CRM_Utils_Array::value('tax_amount', $values, 0.00),
    );
195

196
197
    $lineItem = CRM_Price_BAO_LineItem::create($params);
    $lineItem = $lineItem->toArray();
198

Edselopez's avatar
Edselopez committed
199
200
201
202
203
204
205
206
207
    // Save the chapter and fund information.
    $chapterFundParams = [
      'entity_id' => $this->_id,
      'entity_table' => 'civicrm_line_item',
      'chapter' => $values['chapter_code'],
      'fund' => $values['fund_code'],
    ];
    CRM_EFT_BAO_EFT::saveChapterFund($chapterFundParams);

208
209
210
211
    // calculate balance, tax and paidamount later used to adjust transaction
    $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($this->_lineitemInfo['contribution_id']);
    $taxAmount = CRM_Lineitemedit_Util::getTaxAmountTotalFromContributionID($this->_lineitemInfo['contribution_id']);
    // Record adjusted amount by updating contribution info and create necessary financial trxns
212
    CRM_Lineitemedit_Util::recordAdjustedAmt(
213
214
215
      $updatedAmount,
      $this->_lineitemInfo['contribution_id'],
      $taxAmount,
216
      FALSE
217
218
    );

Monish Deb's avatar
Monish Deb committed
219
    // Record financial item on edit of lineitem
220
221
    CRM_Lineitemedit_Util::insertFinancialItemOnEdit(
      $this->_id,
222
      $this->_lineitemInfo
223
    );
224

Monish Deb's avatar
Monish Deb committed
225
    if (in_array($this->_lineitemInfo['entity_table'], ['civicrm_membership', 'civicrm_participant']) && !empty($lineItem['entity_id'])) {
226
227
228
229
230
231
232
233
234
      $this->updateEntityRecord($this->_lineitemInfo);
      $entityTab = ($this->_lineitemInfo['entity_table'] == 'civicrm_membership') ? 'member' : 'participant';
      if (!$isTest) {
        $this->ajaxResponse['updateTabs']['#tab_' . $entityTab] = CRM_Contact_BAO_Contact::getCountComponent(str_replace('civicrm_', '', $this->_lineitemInfo['entity_table']), $contactId);
      }
    }
  }

  protected function updateEntityRecord($lineItem) {
Monish Deb's avatar
Monish Deb committed
235
236
237
    $params = ['id' => $lineItem['entity_id']];
    if (($lineItem['entity_table'] == 'civicrm_membership')) {
      if (!empty($lineItem['price_field_value_id'])) {
238
239
240
241
        $memberNumTerms = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $lineItem['price_field_value_id'], 'membership_num_terms');
        $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $lineItem['price_field_value_id'], 'membership_type_id');
        $memberNumTerms = empty($memberNumTerms) ? 1 : $memberNumTerms;
        $memberNumTerms = $lineItem['qty'] * $memberNumTerms;
Monish Deb's avatar
Monish Deb committed
242
243
        $params['num_terms'] = $memberNumTerms;
        $params['membership_type_id'] = $membershipTypeId;
244
      }
245
      if ($lineItem['qty'] == 0) {
Monish Deb's avatar
Monish Deb committed
246
247
        $params['status_id'] = 'Cancelled';
        $params['is_override'] = TRUE;
248
249
      }
      else {
Monish Deb's avatar
Monish Deb committed
250
        $params['skipStatusCal'] = FALSE;
251
      }
Monish Deb's avatar
Monish Deb committed
252
      civicrm_api3('Membership', 'create', $params);
253
    }
Monish Deb's avatar
Monish Deb committed
254
255
256
    else {
      $line = array();
      $lineTotal = 0;
257
258
259
260
261
262
263
264
265
266
267
      $getUpdatedLineItems = CRM_Utils_SQL_Select::from('civicrm_line_item')
                              ->where([
                                "entity_table = '!et'",
                                "entity_id = #eid",
                                "qty > 0",
                              ])
                              ->param('!et', $lineItem['entity_table'])
                              ->param('#eid', $lineItem['entity_id'])
                              ->execute()
                              ->fetchAll();
      foreach ($getUpdatedLineItems as $updatedLineItem) {
268
        $line[] = $updatedLineItem['label'] . ' - ' . (float) $updatedLineItem['qty'];
269
270
271
        $lineTotal += $updatedLineItem['line_total'] + $updatedLineItem['tax_amount'];
      }

Monish Deb's avatar
Monish Deb committed
272
273
274
      $params['fee_level'] = implode(', ', $line);
      $params['fee_amount'] = $lineTotal;
      civicrm_api3('Participant', 'create', $params);
275
276
277
278

      //activity creation
      CRM_Event_BAO_Participant::addActivityForSelection($lineItem['entity_id'], 'Change Registration');
    }
Monish Deb's avatar
Monish Deb committed
279
  }
280

Monish Deb's avatar
Monish Deb committed
281
  public function testSubmit($params) {
282
    $this->_id = (int) $params['id'];
283
284
    $this->assignFormVariables($params);
    $this->submit($params, TRUE);
285
  }
Monish Deb's avatar
Monish Deb committed
286

287
}