lineitemedit.php 12.6 KB
Newer Older
Monish Deb's avatar
Monish Deb committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php

require_once 'lineitemedit.civix.php';

/**
 * Implements hook_civicrm_config().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
 */
function lineitemedit_civicrm_config(&$config) {
  _lineitemedit_civix_civicrm_config($config);
}

/**
 * Implements hook_civicrm_xmlMenu().
 */
function lineitemedit_civicrm_xmlMenu(&$files) {
  _lineitemedit_civix_civicrm_xmlMenu($files);
}

/**
 * Implements hook_civicrm_install().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
 */
function lineitemedit_civicrm_install() {
  _lineitemedit_civix_civicrm_install();
}

/**
 * Implements hook_civicrm_uninstall().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall
 */
function lineitemedit_civicrm_uninstall() {
  _lineitemedit_civix_civicrm_uninstall();
}

/**
 * Implements hook_civicrm_enable().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
 */
function lineitemedit_civicrm_enable() {
  _lineitemedit_civix_civicrm_enable();
}

/**
 * Implements hook_civicrm_disable().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable
 */
function lineitemedit_civicrm_disable() {
  _lineitemedit_civix_civicrm_disable();
}

/**
 * Implements hook_civicrm_upgrade().
 */
function lineitemedit_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
  return _lineitemedit_civix_civicrm_upgrade($op, $queue);
}

/**
 * Implements hook_civicrm_managed().
 *
 * Generate a list of entities to create/deactivate/delete when this module
 * is installed, disabled, uninstalled.
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_managed
 */
function lineitemedit_civicrm_managed(&$entities) {
  _lineitemedit_civix_civicrm_managed($entities);
}

/**
 * Implements hook_civicrm_caseTypes().
 */
function lineitemedit_civicrm_caseTypes(&$caseTypes) {
  _lineitemedit_civix_civicrm_caseTypes($caseTypes);
}

/**
 * Implements hook_civicrm_angularModules().
 *
 * Generate a list of Angular modules.
 *
 * Note: This hook only runs in CiviCRM 4.5+. It may
 * use features only available in v4.6+.
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_caseTypes
 */
function lineitemedit_civicrm_angularModules(&$angularModules) {
Monish Deb's avatar
Monish Deb committed
94
  _lineitemedit_civix_civicrm_angularModules($angularModules);
Monish Deb's avatar
Monish Deb committed
95
96
97
98
99
100
101
102
103
104
105
}

/**
 * Implements hook_civicrm_alterSettingsFolders().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterSettingsFolders
 */
function lineitemedit_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) {
  _lineitemedit_civix_civicrm_alterSettingsFolders($metaDataFolders);
}

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
 * Implements hook_civicrm_container().
 */
function lineitemedit_civicrm_container(\Symfony\Component\DependencyInjection\ContainerBuilder $container) {
  $container->setDefinition("cache.lineitemEditor", new Symfony\Component\DependencyInjection\Definition(
    'CRM_Utils_Cache_Interface',
    [
      [
        'name' => 'lineitem-editor',
        'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
      ],
    ]
  ))->setFactory('CRM_Utils_Cache::create');
}

Monish Deb's avatar
Monish Deb committed
121
function lineitemedit_civicrm_buildForm($formName, &$form) {
Monish Deb's avatar
Monish Deb committed
122
  if ($formName == 'CRM_Contribute_Form_Contribution') {
123
    $contributionID = NULL;
Monish Deb's avatar
Monish Deb committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    if (!empty($form->_id) && ($form->_action & CRM_Core_Action::UPDATE)) {
      $contributionID = $form->_id;
      $pricesetFieldsCount = NULL;
      $isQuickConfig = empty($form->_lineItems) ? TRUE : FALSE;
      // Append line-item table only if current contribution has quick config lineitem
      if ($isQuickConfig) {
        $order = civicrm_api3('Order', 'getsingle', array('id' => $contributionID));
        $lineItemTable = CRM_Lineitemedit_Util::getLineItemTableInfo($order);
        $form->assign('lineItemTable', $lineItemTable);

        // Assumes templates are in a templates folder relative to this file
        $templatePath = realpath(dirname(__FILE__) . "/templates");
      }
      else {
        $pricesetFieldsCount = CRM_Core_Smarty::singleton()->get_template_vars('pricesetFieldsCount');
        CRM_Lineitemedit_Util::formatLineItemList($form->_lineItems, $pricesetFieldsCount);
        $form->assign('lineItem', $form->_lineItems);
        $form->assign('pricesetFieldsCount', TRUE);
      }
143
144
145
      if (!empty($form->_values['total_amount'])) {
        $form->setDefaults('total_amount', $form->_values['total_amount']);
      }
Monish Deb's avatar
Monish Deb committed
146
    }
Monish Deb's avatar
Monish Deb committed
147
148
149

    if (!($form->_action & CRM_Core_Action::DELETE)) {
      CRM_Lineitemedit_Util::buildLineItemRows($form, $contributionID);
Monish Deb's avatar
Monish Deb committed
150
151
152
      CRM_Core_Region::instance('page-body')->add(array(
        'template' => "CRM/Lineitemedit/Form/AddLineItems.tpl",
      ));
153
    }
Monish Deb's avatar
Monish Deb committed
154
155
156
  }
}

Monish Deb's avatar
Monish Deb committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
function lineitemedit_civicrm_postProcess($formName, &$form) {
  if ($formName == 'CRM_Contribute_Form_Contribution' &&
    !empty($form->_id) &&
    ($form->_action & CRM_Core_Action::UPDATE)
  ) {
    $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($form->_id);
    foreach ($lineItems as $id => $lineItem) {
      if ($lineItem['qty'] == 0 && $lineItem['line_total'] != 0) {
        $qtyRatio = ($lineItem['line_total'] / $lineItem['unit_price']);
        if ($lineItem['html_type'] == 'Text') {
          $qtyRatio = round($qtyRatio, 2);
        }
        else {
          $qtyRatio = (int) $qtyRatio;
        }
        civicrm_api3('LineItem', 'create', array(
          'id' => $id,
          'qty' => $qtyRatio ? $qtyRatio : 1,
        ));
      }
    }
  }
179
180
181
182
183
184
185
186
187
  if ('CRM_Batch_Form_Entry' == $formName) {
    CRM_Lineitemedit_Util::disableEnablePriceField(TRUE);
  }
}

function lineitemedit_civicrm_validateForm($formName, &$fields, &$files, &$form, &$errors) {
  if ('CRM_Batch_Form_Entry' == $formName && empty($errors)) {
    CRM_Lineitemedit_Util::disableEnablePriceField();
  }
188
189
}

Monish Deb's avatar
Monish Deb committed
190
function lineitemedit_civicrm_pre($op, $entity, $entityID, &$params) {
191
  if ($entity == 'Contribution') {
Monish Deb's avatar
Monish Deb committed
192
    if ($op == 'create' && empty($params['price_set_id'])) {
193
194
      $lineItemParams = [];
      $taxEnabled = (bool) CRM_Utils_Array::value('invoicing', Civi::settings()->get('contribution_invoice_settings'));
Monish Deb's avatar
Monish Deb committed
195
      for ($i = 0; $i <= 10; $i++) {
196
197
198
199
200
        $lineItemParams[$i] = [];
        $notFound = TRUE;
        foreach (['item_label', 'item_financial_type_id', 'item_qty', 'item_unit_price', 'item_line_total', 'item_price_field_value_id'] as $attribute) {
          if (!empty($params[$attribute]) && !empty($params[$attribute][$i])) {
            $notFound = FALSE;
Monish Deb's avatar
Monish Deb committed
201
202
203
            if (in_array($attribute, ['item_line_total', 'item_unit_price'])) {
              $params[$attribute][$i] = CRM_Utils_Rule::cleanMoney($params[$attribute][$i]);
            }
204
205
206
207
208
209
210
211
212
213
214
            $lineItemParams[$i][str_replace('item_', '', $attribute)] = $params[$attribute][$i];
            if ($attribute == 'item_price_field_value_id') {
              $lineItemParams[$i]['price_field_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $params[$attribute][$i], 'price_field_id');
            }
          }
        }
        if ($notFound) {
          unset($lineItemParams[$i]);
        }
        else {
          if ($taxEnabled) {
215
            $lineItemParams[$i]['tax_amount'] = (float) CRM_Utils_Array::value($i, $params['item_tax_amount'], 0.00);
216
217
            $params['tax_amount'] += $lineItemParams[$i]['tax_amount'];
          }
Monish Deb's avatar
Monish Deb committed
218
          $params['total_amount'] = $params['net_amount'] = $params['amount'] += (CRM_Utils_Array::value('line_total', $lineItemParams[$i], 0.00) + CRM_Utils_Array::value('tax_amount', $lineItemParams[$i], 0.00));
219
220
221
222
223
          if (!empty($lineItemParams[$i]['line_total']) && !empty($lineItemParams[$i]['price_field_id'])) {
            $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $lineItemParams[$i]['price_field_id'], 'price_set_id');
            if (!empty($params['line_item'][$priceSetID])) {
              $params['line_item'][$priceSetID][$lineItemParams[$i]['price_field_id']] = $lineItemParams[$i];
            }
Monish Deb's avatar
Monish Deb committed
224
225
226
          }
        }
      }
227
228
229
    }
    elseif ($op == 'edit') {
      $lineItemParams = $newLineItem = [];
Monish Deb's avatar
Monish Deb committed
230
      for ($i = 0; $i <= 10; $i++) {
231
232
        $lineItemParams[$i] = [];
        $notFound = TRUE;
233
        foreach (['item_label', 'item_financial_type_id', 'item_chapter_code', 'item_fund_code', 'item_qty', 'item_unit_price', 'item_line_total', 'item_price_field_value_id', 'item_tax_amount'] as $attribute) {
234
235
236
237
238
239
240
241
242
243
244
245
246
          if (!empty($params[$attribute]) && !empty($params[$attribute][$i])) {
            if ($attribute == 'item_line_total') {
              $notFound = FALSE;
            }
            $lineItemParams[$i][str_replace('item_', '', $attribute)] = $params[$attribute][$i];
            if ($attribute == 'item_price_field_value_id') {
              $lineItemParams[$i]['price_field_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $params[$attribute][$i], 'price_field_id');
            }
          }
        }
        if ($notFound) {
          unset($lineItemParams[$i]);
        }
Monish Deb's avatar
Monish Deb committed
247
      }
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272

      foreach ($lineItemParams as $key => $lineItem) {
        if ($lineItem['price_field_value_id'] == 'new') {
          list($lineItem['price_field_id'], $lineItem['price_field_value_id']) = CRM_Lineitemedit_Util::createPriceFieldByContributionID($entityID);
        }
        else {
          $lineItem['price_field_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $lineItem['price_field_value_id'], 'price_field_id');
        }
        list($lineEntityTable, $lineEntityID) = CRM_Lineitemedit_Util::addEntity(
          $lineItem['price_field_value_id'],
          $entityID,
          $lineItem['qty']
        );

        $newLineItemParams = array(
          'entity_table' => $lineEntityTable,
          'entity_id' => $lineEntityID,
          'contribution_id' => $entityID,
          'price_field_id' => $lineItem['price_field_id'],
          'label' => $lineItem['label'],
          'qty' => $lineItem['qty'],
          'unit_price' => CRM_Utils_Rule::cleanMoney($lineItem['unit_price']),
          'line_total' => CRM_Utils_Rule::cleanMoney($lineItem['line_total']),
          'price_field_value_id' => $lineItem['price_field_value_id'],
          'financial_type_id' => $lineItem['financial_type_id'],
bgm's avatar
bgm committed
273
          'tax_amount' => CRM_Utils_Array::value('tax_amount', $lineItem),
274
        );
275
276
277
278
279
280
281
282
283
284
        $newLineItem[] = $newId = civicrm_api3('LineItem', 'create', $newLineItemParams)['id'];
        $chapterFundParams = [
          'entity_id' => $newId,
          'entity_table' => 'civicrm_line_item',
          'chapter' => $lineItem['chapter_code'],
          'fund' => $lineItem['fund_code'],
        ];
        CRM_Core_Session::singleton()->set('noUpdate', TRUE);
        CRM_EFT_BAO_EFT::saveChapterFund($chapterFundParams);
        CRM_Core_Session::singleton()->set('noUpdate', FALSE);
285
286
287
288
289
290
291
292
293
294
295
296
297
298
      }

      if (!empty($lineItemParams)) {
        // calculate balance, tax and paidamount later used to adjust transaction
        $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($entityID);
        $taxAmount = CRM_Lineitemedit_Util::getTaxAmountTotalFromContributionID($entityID);

        // Record adjusted amount by updating contribution info and create necessary financial trxns
        list($trxn, $contriParams) = CRM_Lineitemedit_Util::recordAdjustedAmt(
          $updatedAmount,
          $entityID,
          $taxAmount,
          TRUE, TRUE
        );
299
        Civi::cache('lineitemEditor')->set($entityID, $contriParams);
300
301
302
303
304
305

        // record financial item on addition of lineitem
        if ($trxn) {
          foreach ($newLineItem as $lineItemID) {
            $lineItem = civicrm_api3('LineItem', 'getsingle', array('id' => $lineItemID));
            CRM_Lineitemedit_Util::insertFinancialItemOnAdd($lineItem, $trxn);
Monish Deb's avatar
Monish Deb committed
306
307
308
          }
        }
      }
Monish Deb's avatar
Monish Deb committed
309
310
311

      // we are already processing line-items above so no need to create/update them again via create()
      $params['skipLineItem'] = TRUE;
Monish Deb's avatar
Monish Deb committed
312
313
314
315
    }
  }
}

316
317
function lineitemedit_civicrm_post($op, $entity, $entityID, &$obj) {
  if ($entity == 'Contribution' && $op == 'edit') {
318
    $contriParams = Civi::cache('lineitemEditor')->get($entityID);
319
320
321
    if (!empty($contriParams)) {
      $obj->copyValues($contriParams);
      $obj->save();
322
      Civi::cache('lineitemEditor')->delete($entityID);
323
324
325
326
    }
  }
}

Monish Deb's avatar
Monish Deb committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/**
 * Implements hook_civicrm_navigationMenu().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_navigationMenu
 *
function lineitemedit_civicrm_navigationMenu(&$menu) {
  _lineitemedit_civix_insert_navigation_menu($menu, NULL, array(
    'label' => ts('The Page', array('domain' => 'biz.jmaconsulting.lineitemedit')),
    'name' => 'the_page',
    'url' => 'civicrm/the-page',
    'permission' => 'access CiviReport,access CiviContribute',
    'operator' => 'OR',
    'separator' => 0,
  ));
  _lineitemedit_civix_navigationMenu($menu);
} // */