PluginProbe
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler / 1.5.3
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler v1.5.3
1.6.5 1.6.4 1.6.3 1.6.2 1.6.1 1.6.0 1.5.4 1.5.5 1.5.3 1.5.2 1.5.1 1.5.0 1.4.2 1.4.1 1.4.0 1.3.28 1.3.27 1.3.26 1.3.25 1.3.23 1.3.22 1.3.21 1.3.20 1.3.19 trunk All 48 releases
fluent-cart / api / Resource / CustomerAddressResource.php

CustomerAddressResource.php in FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler 1.5.3, at api/Resource/CustomerAddressResource.php

379 lines 13.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentCart\Api\Resource;
4
5 use FluentCart\App\App;
6 use FluentCart\App\Models\CustomerAddresses;
7 use FluentCart\App\Services\Renderer\CheckoutFieldsSchema;
8 use FluentCart\Framework\Database\Orm\Builder;
9 use FluentCart\Framework\Support\Arr;
10
11 class CustomerAddressResource extends BaseResourceApi
12 {
13
14 public static function getQuery(): Builder
15 {
16 return CustomerAddresses::query();
17 }
18
19 /**
20 * Get customer addresses with specified parameters.
21 *
22 * @param array $params Array containing the necessary parameters.
23 * [
24 * 'customer_id' => (int) Required. The ID of the customer.
25 * 'type' => (string) Optional. The type of address ('billing' by default).
26 * ]
27 *
28 */
29 public static function get(array $params = [])
30 {
31 $id = Arr::get($params, 'customer_id');
32
33 $type = Arr::get($params, 'type', 'billing');
34
35 $addresses = static::getQuery()->search(['customer_id' => ['column' => 'customer_id', 'value' => $id]]);
36
37 if ($type) {
38 $addresses->search(['type' => ['column' => 'type', 'value' => $type]]);
39 }
40 return $addresses->orderBy('is_primary', 'DESC')->get()->toArray();
41 }
42
43 /**
44 * Find customer address based on the given ID and parameters.
45 *
46 * @param int $id Required. The ID of the customer.
47 * @param array $params Optional. Array containing the necessary parameters.
48 * [
49 * 'type' => (string) Optional. The type of address ('billing' by default).
50 * ]
51 *
52 */
53 public static function find($id, $params = [])
54 {
55 $type = Arr::get($params, 'type', 'billing');
56 $params = [
57 "customer_id" => $id,
58 "type" => $type,
59 ];
60 $all = CustomerAddressResource::get($params);
61
62 if (empty($all)) {
63 return [];
64 }
65
66 $firstItem = Arr::first($all);
67 return Arr::only($firstItem, [
68 'address_1',
69 'address_2',
70 'city',
71 'state',
72 'postcode',
73 'country'
74 ]);
75 }
76
77 /*public static function find($id, $params = [])
78 {
79 return static::getQuery()->find($id);
80 }*/
81
82 /**
83 * Create customer address with the given data.
84 *
85 * @param array $data Required. Array containing the necessary parameters
86 * [
87 * 'email' => (string) Optional. The email of the address.
88 * 'name' => (string) Required. The name of the address.
89 * 'phone' => (string) Required. The phone of the address.
90 * 'address_1' => (string) Required. The primary address line.
91 * 'address_2' => (string) Optional. The secondary address line.
92 * 'city' => (string) Required. The city of the address.
93 * 'country' => (string) Required. The country of the address.
94 * 'postcode' => (string) Required. The postal code of the address.
95 * 'state' => (string) Required. The state of the address.
96 * 'type' => (string) Required. (e.g., 'billing', 'shipping').
97 * ]
98 * @param array $params Required. Additional parameters for creating an address.
99 * [
100 * 'id' => (int) Required. The ID of the customer.
101 * ]
102 *
103 */
104 public static function create($data, $params = [])
105 {
106 // Extract the customer ID from the provided parameters
107 $id = Arr::get($params, 'id');
108
109 // Retrieve the 'type' of address from the provided data array
110 $addressType = Arr::get($data, 'type');
111
112 // Check if the customer already has a primary address of the given type
113 $hasPrimary = static::getQuery()
114 ->where('customer_id', $id) // Match the customer ID
115 ->where('type', Arr::get($data, 'type')) // Match the address type from the data
116 ->where('is_primary', '1') // Look for addresses marked as primary
117 ->count(); // Get the count of matching primary addresses
118
119 // If no primary address exists, set 'is_primary' to '1'
120 if (!$hasPrimary) {
121 $data['is_primary'] = '1';
122 }
123
124 // Assign the customer ID to the data array
125 $data['customer_id'] = $id;
126
127 $data = static::normalizeBusinessFields($data);
128 $data = static::mergeAddressMetaFields($data);
129
130 // Create a new address record with the given data
131 $isCreated = static::getQuery()->create($data);
132
133 // If the address was successfully created
134 if ($isCreated) {
135 // Check if an 'order_id' is provided and the address is marked as primary
136 if (!empty($orderId = Arr::get($params, 'order_id', null)) && Arr::get($data, 'is_primary', null) == 1) {
137 // Include 'order_id' in the data for the order address
138 $data['order_id'] = $orderId;
139 // Check if the order already has an address of the given type
140 $alreadyOrderHasAddress = OrderAddressResource::find($orderId, ['type' => Arr::get($data, 'type', null)]);
141
142 if ($alreadyOrderHasAddress) {
143 // If an address already exists for the order, update it with the new data
144 OrderAddressResource::update($data, $orderId);
145 } else {
146 // If no address exists for the order, create a new one
147 OrderAddressResource::create($data);
148 }
149 }
150
151 if ($addressType === 'billing') {
152 return static::makeSuccessResponse(
153 $isCreated,
154 __('Billing address created successfully!', 'fluent-cart')
155 );
156 }
157 return static::makeSuccessResponse(
158 $isCreated,
159 __('Shipping address created successfully!', 'fluent-cart')
160 );
161 }
162
163 if ($addressType === 'billing') {
164 return static::makeErrorResponse([
165 ['code' => 400, 'message' => __('Failed creating billing address', 'fluent-cart')]
166 ]);
167 }
168
169 return static::makeErrorResponse([
170 ['code' => 400, 'message' => __('Failed creating shipping address', 'fluent-cart')]
171 ]);
172 }
173
174 /**
175 * Update the customer address with the given data.
176 *
177 * @param array $data Required. Array containing the necessary parameters
178 * [
179 * 'Email' => (string) Optional. The email of the address.
180 * 'Name' => (string) Required. The name of the address.
181 * 'Phone' => (string) Required. The phone of the address.
182 * 'Address_1' => (string) Required. The primary address line.
183 * 'Address_2' => (string) Optional. The secondary address line.
184 * 'City' => (string) Required. The city of the address.
185 * 'Country' => (string) Required. The country of the address.
186 * 'Postcode' => (string) Required. The postal code of the address.
187 * 'State' => (string) Required. The state of the address.
188 * 'Type' => (string) Required. (E.g., 'billing', 'shipping').
189 * ]
190 * @param int $id Required. The ID of the customer address to be updated.
191 *
192 */
193 public static function update($data, $id, $params = [])
194 {
195 if (!$id) {
196 return static::makeErrorResponse([
197 ['code' => 403, 'message' => __('Please edit a valid address!', 'fluent-cart')]
198 ]);
199 }
200
201 $address = static::getQuery()->find($id);
202
203 // Retrieve the 'type' of address from the provided data array
204 $addressType = Arr::get($address, 'type');
205
206
207 if (!$address) {
208 return static::makeErrorResponse([
209 ['code' => 404, 'message' => __('Address not found, please reload the page and try again!', 'fluent-cart')]
210 ]);
211 }
212
213 $data = static::normalizeBusinessFields($data);
214 $data = static::mergeAddressMetaFields($data, $address);
215
216 $address->update($data);
217 $address->refresh();
218
219 if ($address) {
220 if (!empty($orderId = Arr::get($params, 'order_id', null))) {
221 OrderAddressResource::update($data, $orderId);
222 }
223
224 if ($addressType === 'billing') {
225 return static::makeSuccessResponse(
226 $address,
227 __('Billing address updated successfully!', 'fluent-cart')
228 );
229 }
230
231 return static::makeSuccessResponse(
232 $address,
233 __('Shipping address updated successfully!', 'fluent-cart')
234 );
235 }
236
237 if ($addressType === 'billing') {
238 return static::makeErrorResponse([
239 ['code' => 400, 'message' => __('Failed updating billing address', 'fluent-cart')]
240 ]);
241 }
242
243 return static::makeErrorResponse([
244 ['code' => 400, 'message' => __('Failed updating shipping address', 'fluent-cart')]
245 ]);
246 }
247
248 public static function normalizeBusinessFields(array $data): array
249 {
250 $type = Arr::get($data, 'type', 'billing');
251
252 if ($type !== 'billing') {
253 unset($data['company_name'], $data['vat_number'], $data['legal_registration_id']);
254 return $data;
255 }
256
257 if (!CheckoutFieldsSchema::isCompanyNameEnabled()) {
258 unset($data['company_name']);
259 }
260
261 if (!CheckoutFieldsSchema::isVatNumberEnabled()) {
262 unset($data['vat_number']);
263 }
264
265 if (!CheckoutFieldsSchema::isLegalRegistrationIdEnabled()) {
266 unset($data['legal_registration_id']);
267 }
268
269 return $data;
270 }
271
272 private static function mergeAddressMetaFields(array $data, ?CustomerAddresses $address = null): array
273 {
274 $meta = $address ? $address->meta : Arr::get($data, 'meta', []);
275 $meta = is_array($meta) ? $meta : [];
276
277 $metaKeys = ['company_name', 'vat_number', 'legal_registration_id'];
278 foreach ($metaKeys as $metaKey) {
279 if (!array_key_exists($metaKey, $data)) {
280 continue;
281 }
282
283 $value = Arr::get($data, $metaKey);
284
285 if ($value === '' || $value === null) {
286 unset($meta['other_data'][$metaKey]);
287 } else {
288 Arr::set($meta, 'other_data.' . $metaKey, $value);
289 }
290 }
291
292 $data['meta'] = $meta;
293 unset($data['company_name'], $data['vat_number'], $data['legal_registration_id']);
294
295 return $data;
296 }
297
298 /**
299 * Delete an address based on the given ID and parameters.
300 *
301 * @param int $id Required. The ID of the customer address.
302 * @param array $params Optional. Additional parameters for address deletion.
303 *
304 */
305 public static function delete($id, $params = [])
306 {
307 // Check if a valid ID is provided
308 if (!$id) {
309 return static::makeErrorResponse([
310 ['code' => 403, 'message' => __('Please use a valid address ID!', 'fluent-cart')]
311 ]);
312 }
313
314 // Retrieve the customer address using the ID
315 $customerAddress = static::getQuery()->find($id);
316
317 if ($customerAddress) {
318 // Check if the address is marked as primary
319 if ($customerAddress->is_primary) {
320 return static::makeErrorResponse([
321 ['code' => 403, 'message' => __('Primary address cannot be deleted!', 'fluent-cart')]
322 ]);
323 }
324 // Get the count of addresses for this customer
325 $addressCount = static::getQuery()->where('customer_id', $customerAddress->customer_id)->count();
326
327 // Check if there's only one address, do not allow deletion in that case
328 if ($addressCount <= 1) {
329 return static::makeErrorResponse([
330 ['code' => 403, 'message' => __('At least one address must remain. Address deletion failed!', 'fluent-cart')]
331 ]);
332 }
333
334 // If the address is not primary and there are multiple addresses, proceed with deletion
335 if ($customerAddress->delete()) {
336 return static::makeSuccessResponse('', __('Address successfully deleted.', 'fluent-cart'));
337 }
338
339 // Return an error if the address is not found in the database
340 return static::makeErrorResponse([
341 ['code' => 400, 'message' => __('Address deletion failed!', 'fluent-cart')]
342 ]);
343 }
344
345 return static::makeErrorResponse([
346 ['code' => 404, 'message' => __('Address not found in database, failed to remove.', 'fluent-cart')]
347 ]);
348 }
349
350 /**
351 * Make primary address for the specified customer.
352 *
353 * @param int $customerId Required. The ID of the customer.
354 * @param array $params Optional. Additional parameters for making an address primary.
355 * [
356 * 'address' => [
357 * 'id' => (int) Required. The ID of the address to be set as primary.
358 * 'type' => (string) Required. The type of the address (e.g., 'billing', 'shipping').
359 * ],
360 * ]
361 */
362 public static function makePrimary($customerId, $addressId, $type)
363 {
364 static::getQuery()->where('customer_id', $customerId)
365 ->where('type', $type)
366 ->update(array('is_primary' => '0'));
367
368 $isUpdated = static::getQuery()->where('id', $addressId)->where('customer_id', $customerId)->where('type', $type)->update(array('is_primary' => '1'));
369
370 if ($isUpdated) {
371 return static::makeSuccessResponse('', __('Address successfully set as the primary', 'fluent-cart'));
372 }
373
374 return static::makeErrorResponse([
375 ['code' => 400, 'message' => __('Address set as primary failed.', 'fluent-cart')]
376 ]);
377 }
378 }
379