Merge pull request #20656 from eileenmcnaughton/cont_mode
[civicrm-core.git] / api / v3 / Order.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This api exposes CiviCRM Order objects, an abstract entity
14 * comprised of contributions and related line items.
15 *
16 * @package CiviCRM_APIv3
17 */
18
19 /**
20 * Retrieve a set of Order.
21 *
22 * @param array $params
23 * Input parameters.
24 *
25 * @return array
26 * Array of Order, if error an array with an error id and error message
27 * @throws \CiviCRM_API3_Exception
28 */
29 function civicrm_api3_order_get(array $params): array {
30 $contributions = [];
31 $params['api.line_item.get'] = ['qty' => ['<>' => 0]];
32 $isSequential = FALSE;
33 if (!empty($params['sequential'])) {
34 $params['sequential'] = 0;
35 $isSequential = TRUE;
36 }
37 $result = civicrm_api3('Contribution', 'get', $params);
38 if (!empty($result['values'])) {
39 foreach ($result['values'] as $key => $contribution) {
40 $contributions[$key] = $contribution;
41 $contributions[$key]['line_items'] = $contribution['api.line_item.get']['values'];
42 unset($contributions[$key]['api.line_item.get']);
43 }
44 }
45 $params['sequential'] = $isSequential;
46 return civicrm_api3_create_success($contributions, $params, 'Order', 'get');
47 }
48
49 /**
50 * Adjust Metadata for Get action.
51 *
52 * The metadata is used for setting defaults, documentation & validation.
53 *
54 * @param array $params
55 * Array of parameters determined by getfields.
56 */
57 function _civicrm_api3_order_get_spec(array &$params) {
58 $params['id']['api.aliases'] = ['order_id'];
59 $params['id']['title'] = ts('Contribution / Order ID');
60 }
61
62 /**
63 * Add or update a Order.
64 *
65 * @param array $params
66 * Input parameters.
67 *
68 * @return array
69 * Api result array
70 *
71 * @throws \CiviCRM_API3_Exception
72 * @throws API_Exception
73 */
74 function civicrm_api3_order_create(array $params): array {
75 civicrm_api3_verify_one_mandatory($params, NULL, ['line_items', 'total_amount']);
76 $entity = NULL;
77 $entityIds = [];
78 $params['contribution_status_id'] = 'Pending';
79 $priceSetID = NULL;
80
81 if (!empty($params['line_items']) && is_array($params['line_items'])) {
82 CRM_Contribute_BAO_Contribution::checkLineItems($params);
83 foreach ($params['line_items'] as $lineItems) {
84 $entityParams = $lineItems['params'] ?? [];
85 if (!empty($entityParams) && !empty($lineItems['line_item'])) {
86 $item = reset($lineItems['line_item']);
87 if (!empty($item['membership_type_id'])) {
88 $entity = 'membership';
89 }
90 else {
91 $entity = str_replace('civicrm_', '', $item['entity_table']);
92 }
93 }
94
95 if ($entityParams) {
96 $supportedEntity = TRUE;
97 switch ($entity) {
98 case 'participant':
99 if (isset($entityParams['participant_status_id'])
100 && (!CRM_Event_BAO_ParticipantStatusType::getIsValidStatusForClass($entityParams['participant_status_id'], 'Pending'))) {
101 throw new CiviCRM_API3_Exception('Creating a participant via the Order API with a non "pending" status is not supported');
102 }
103 $entityParams['participant_status_id'] = $entityParams['participant_status_id'] ?? 'Pending from incomplete transaction';
104 $entityParams['status_id'] = $entityParams['participant_status_id'];
105 $params['contribution_mode'] = 'participant';
106 break;
107
108 case 'membership':
109 $entityParams['status_id'] = 'Pending';
110 break;
111
112 default:
113 // Don't create any related entities. We might want to support eg. Pledge one day?
114 $supportedEntity = FALSE;
115 break;
116 }
117 if ($supportedEntity) {
118 $entityParams['skipLineItem'] = TRUE;
119 $entityResult = civicrm_api3($entity, 'create', $entityParams);
120 $entityIds[] = $params[$entity . '_id'] = $entityResult['id'];
121 foreach ($lineItems['line_item'] as &$items) {
122 $items['entity_id'] = $entityResult['id'];
123 }
124 }
125 }
126
127 if (empty($priceSetID)) {
128 $item = reset($lineItems['line_item']);
129 $priceSetID = (int) civicrm_api3('PriceField', 'getvalue', [
130 'return' => 'price_set_id',
131 'id' => $item['price_field_id'],
132 ]);
133 $params['line_item'][$priceSetID] = [];
134 }
135 $params['line_item'][$priceSetID] = array_merge($params['line_item'][$priceSetID], $lineItems['line_item']);
136 }
137 }
138 $contributionParams = $params;
139 // If this is nested we need to set sequential to 0 as sequential handling is done
140 // in create_success & id will be miscalculated...
141 $contributionParams['sequential'] = 0;
142 foreach ($contributionParams as $key => $value) {
143 // Unset chained keys so the code does not attempt to do this chaining twice.
144 // e.g if calling 'api.Payment.create' We want to finish creating the order first.
145 // it would probably be better to have a full whitelist of contributionParams
146 if (substr($key, 0, 3) === 'api') {
147 unset($contributionParams[$key]);
148 }
149 }
150
151 $contribution = civicrm_api3('Contribution', 'create', $contributionParams);
152 $contribution['values'][$contribution['id']]['line_item'] = $params['line_item'][$priceSetID] ?? [];
153
154 // add payments
155 if ($entity && !empty($contribution['id'])) {
156 foreach ($entityIds as $entityId) {
157 $paymentParams = [
158 'contribution_id' => $contribution['id'],
159 $entity . '_id' => $entityId,
160 ];
161 // if entity is pledge then build pledge param
162 if ($entity === 'pledge') {
163 $paymentParams += $entityParams;
164 // Pledges are not stored as entity_id in the line_item table.
165 CRM_Core_Error::deprecatedWarning('This should be unreachable & tests show it is never tested.');
166 civicrm_api3('PledgePayment', 'create', $paymentParams);
167 }
168 if ($entity === 'participant') {
169 civicrm_api3('ParticipantPayment', 'create', $paymentParams);
170 }
171
172 }
173 }
174 return civicrm_api3_create_success($contribution['values'] ?? [], $params, 'Order', 'create');
175 }
176
177 /**
178 * Delete a Order.
179 *
180 * @param array $params
181 * Input parameters.
182 *
183 * @return array
184 * @throws API_Exception
185 * @throws CiviCRM_API3_Exception
186 */
187 function civicrm_api3_order_delete(array $params): array {
188 $contribution = civicrm_api3('Contribution', 'get', [
189 'return' => ['is_test'],
190 'id' => $params['id'],
191 ]);
192 if ($contribution['id'] && $contribution['values'][$contribution['id']]['is_test'] == TRUE) {
193 $result = civicrm_api3('Contribution', 'delete', $params);
194 }
195 else {
196 throw new API_Exception('Only test orders can be deleted.');
197 }
198 return civicrm_api3_create_success($result['values'], $params, 'Order', 'delete');
199 }
200
201 /**
202 * Cancel an Order.
203 *
204 * @param array $params
205 * Input parameters.
206 *
207 * @return array
208 * @throws \CiviCRM_API3_Exception
209 */
210 function civicrm_api3_order_cancel(array $params) {
211 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
212 $params['contribution_status_id'] = array_search('Cancelled', $contributionStatuses);
213 $result = civicrm_api3('Contribution', 'create', $params);
214 return civicrm_api3_create_success($result['values'], $params, 'Order', 'cancel');
215 }
216
217 /**
218 * Adjust Metadata for Cancel action.
219 *
220 * The metadata is used for setting defaults, documentation & validation.
221 *
222 * @param array $params
223 * Array of parameters determined by getfields.
224 */
225 function _civicrm_api3_order_cancel_spec(array &$params) {
226 $params['contribution_id'] = [
227 'api.required' => 1,
228 'title' => 'Contribution ID',
229 'type' => CRM_Utils_Type::T_INT,
230 ];
231 }
232
233 /**
234 * Adjust Metadata for Create action.
235 *
236 * The metadata is used for setting defaults, documentation & validation.
237 *
238 * @param array $params
239 * Array of parameters determined by getfields.
240 */
241 function _civicrm_api3_order_create_spec(array &$params) {
242 $params['contact_id'] = [
243 'name' => 'contact_id',
244 'title' => 'Contact ID',
245 'type' => CRM_Utils_Type::T_INT,
246 'api.required' => TRUE,
247 ];
248 $params['total_amount'] = [
249 'name' => 'total_amount',
250 'title' => 'Total Amount',
251 ];
252 $params['skipCleanMoney'] = [
253 'api.default' => TRUE,
254 'title' => 'Do not attempt to convert money values',
255 'type' => CRM_Utils_Type::T_BOOLEAN,
256 ];
257 $params['financial_type_id'] = [
258 'name' => 'financial_type_id',
259 'title' => 'Financial Type',
260 'type' => CRM_Utils_Type::T_INT,
261 'api.required' => TRUE,
262 'table_name' => 'civicrm_contribution',
263 'entity' => 'Contribution',
264 'bao' => 'CRM_Contribute_BAO_Contribution',
265 'pseudoconstant' => [
266 'table' => 'civicrm_financial_type',
267 'keyColumn' => 'id',
268 'labelColumn' => 'name',
269 ],
270 ];
271 }
272
273 /**
274 * Adjust Metadata for Delete action.
275 *
276 * The metadata is used for setting defaults, documentation & validation.
277 *
278 * @param array $params
279 * Array of parameters determined by getfields.
280 */
281 function _civicrm_api3_order_delete_spec(array &$params) {
282 $params['contribution_id'] = [
283 'api.required' => TRUE,
284 'title' => 'Contribution ID',
285 'type' => CRM_Utils_Type::T_INT,
286 ];
287 $params['id']['api.aliases'] = ['contribution_id'];
288 }