-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExtension.php
executable file
·340 lines (270 loc) · 13 KB
/
Extension.php
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
namespace CupNoodles\Postmates;
use System\Classes\BaseExtension;
use System\Traits\SendsMailTemplate;
use App;
use Event;
use ApplicationException;
use Geocoder;
use Admin\Controllers\Orders;
use Admin\Widgets\Form;
use Admin\Widgets\Toolbar;
use Admin\Models\Location_areas_model;
use System\Classes\BaseController;
use Igniter\Local\Classes\Location;
use CupNoodles\Postmates\Models\PostmatesSettings;
use CupNoodles\Postmates\Classes\PostmatesCoveredArea;
use CupNoodles\PriceByWeight\Components\CheckoutByWeight;
use Igniter\Cart\Models\Orders_Model;
use Admin\Models\Orders_model as Admin_Orders_Model;
class Extension extends BaseExtension
{
use SendsMailTemplate;
public $order_model;
/**
* Returns information about this extension.
*
* @return array
*/
public function extensionMeta()
{
return [
'name' => 'Postmates',
'author' => 'CupNoodles',
'description' => 'Postmates API integration.',
'icon' => 'fa fa-shipping-fast',
'version' => '1.0.0'
];
}
/**
* Register method, called when the extension is first registered.
*
* @return void
*/
public function register()
{
$this->app->singleton('location', Location::class);
}
/**
* Boot method, called right before the request route.
*
* @return void
*/
public function boot()
{
// object replacement
Event::listen('main.page.init', function($controller){
$this->updatePostmatesDeliveryCost(app('location'));
});
Event::listen('location.area.updated', function($location,$coveredArea){
$this->updatePostmatesDeliveryCost($location);
$this->saveUserAddressToSession($location);
});
// Put a 'postmates' button for type on delivery areas
Event::listen('admin.form.extendFields', function (Form $form, $fields) {
if ($form->model instanceof Location_areas_model) {
//The following line can trigger E_WARNING if ->config hasn't been initialized yet.
@$fields['conditions']->config['form']['fields']['delivery_service'] = [
'label' => 'lang:cupnoodles.postmates::default.delivery_service',
'type' => 'radiotoggle',
'default' => 'self_delivery',
'options' => [
'self_delivery' => 'lang:cupnoodles.postmates::default.self_delivery',
'postmates' => 'lang:cupnoodles.postmates::default.postmates'
],
];
}
});
// create an order page button that calls the actual Postmates Delivery when it's ready (or about to be)
Event::listen('admin.form.extendFieldsBefore', function (Form $form) {
if ($form->model instanceof Admin_Orders_Model) {
if ($form->model->order_type == 'delivery'){
Event::listen('admin.toolbar.extendButtons', function (Toolbar $toolbar) use ($form) {
$toolbar->buttons['call_postmates'] = [
'label' => 'lang:cupnoodles.postmates::default.call_postmates',
'class' => 'btn btn-primary',
'data-request' => 'onCallPostmates',
'data-request-data' => "_method:'POST', order_id:" . $form->model->order_id . ", refresh:1",
'data-request-confirm' => 'lang:cupnoodles.postmates::default.call_postmates_confirmation',
];
});
}
}
});
Orders::extend(function($controller){
$controller->addDynamicMethod('edit_onCallPostmates', function($action, $order_id) use ($controller) {
$model = $controller->formFindModelObject($order_id);
$this->callPostmatesDelivery($model);
if ($redirect = $controller->makeRedirect('edit', $model)) {
return $redirect;
}
});
} );
// Since the final delivery address can be entered in on the checkout screen, it may not match what was shown to the customer after entering a (possibly different) address into the localBox component.
// This final check creates a location object out of the order delivery data, and check that the last postmates delivery price set in session is equal to the quote as returned byu the checkout address.
Event::listen('igniter.checkout.beforeSaveOrder', function(Orders_Model $order, $data){
if($order->order_type == 'delivery'){
$collection = Geocoder::geocode($data['address']['address_1'] . ' ' . $data['address']['address_2'] . ' ' .$data['address']['city'] . ' ' .$data['address']['state'] . ' ' .$data['address']['postcode']);
if (!$collection OR $collection->isEmpty()) {
Log::error(implode(PHP_EOL, Geocoder::getLogs()));
throw new ApplicationException(lang('igniter.local::default.alert_invalid_search_query'));
}
$userLocation = $collection->first();
if (!$userLocation->hasCoordinates())
throw new ApplicationException(lang('igniter.local::default.alert_invalid_search_query'));
$location = App::make('location');
$postmates_quote_amt = session('postmates_delivery_quote');
$location->updateUserPosition($userLocation);
$this->updatePostmatesDeliveryCost($location);
$final_delivery_check = $location->deliveryAmount($order->order_total);
if(number_format($final_delivery_check, 2) != number_format($postmates_quote_amt, 2) ){
throw new ApplicationException('Postmates Delivery Quote has changed. Please confirm the new delivery estimate.');
}
}
});
}
public function saveUserAddressToSession($location){
session(['postmates_address_1' => $location->userPosition()->getStreetNumber() . " " . $location->userPosition()->getStreetName()]);
if(isset($location->userPosition()->data['subpremise'])){
session(['postmates_address_2' => $location->userPosition()->data['subpremise']]);
}
session(['postmates_city' => $location->userPosition()->getLocality()]);
if( $location->userPosition()->getAdminLevels() !== null && $location->userPosition()->getAdminLevels()->last() !== null ) {
session(['postmates_state' => $location->userPosition()->getAdminLevels()->last()->getCode()]);
}
session(['postmates_postcode' => $location->userPosition()->getPostalCode()]);
}
public function registerMailTemplates()
{
return [
'cupnoodles.postmates::mail.delivery_requested' => 'Order confirmation email to customer'
];
}
public function callPostmatesDelivery($order_model){
$address = $order_model->address->toArray();
$deliver_to = $address['address_1'] . ', ' . $address['city'] . ', ' . $address['state'] . ', ' . $address['postcode'];
$location_address = $order_model->location->getModel()->getAddress();
$location_address = $location_address['address_1'] . ', ' . $location_address['city'] . ', ' . $location_address['state'] . ', ' . $location_address['postcode'];
$post_data = [
'dropoff_address' => $deliver_to,
'dropoff_name' => $order_model->first_name . ' ' . $order_model->last_name,
'dropoff_phone_number'=> $order_model->telephone,
'manifest' => 'Postmates delivery for ' . $order_model->first_name . ' ' . $order_model->last_name . 'from' . '',
'manifest_items' => [
'name' => 'Postmates delivery for ' . $order_model->first_name . ' ' . $order_model->last_name . 'from' . '',
'quantity' => 1,
'size' => 'medium'
],
'pickup_address' => $location_address,
'pickup_name' => $order_model->location->getModel()->location_name,
'pickup_phone_number' => $order_model->location->getModel()->location_telephone
//'quote_id' => '' //not yet implemented
];
// get postmates sandbox/production settings
if( PostmatesSettings::get('testing_mode') ){
$api_key = PostmatesSettings::get('production_api_key');
}
else{
$api_key = PostmatesSettings::get('sandbox_api_key');
}
$b64_api_key = base64_encode($api_key . ':');
$base_url = 'https://api.postmates.com/';
$quote_url = $base_url . 'v1/customers/'.PostmatesSettings::get('customer_id').'/deliveries';
$ch = curl_init($quote_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-type: application/x-www-form-urlencoded", 'Authorization: Basic '. $b64_api_key]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$result_json = curl_exec($ch);
$result = json_decode($result_json, true);
if($result['kind'] == 'error'){
throw new ApplicationException($result['message'] ); // could do with some better error handling here, there's potentially a $params array in response that could be helpful to users.
}
else{
$this->tracking_url = $result['tracking_url'];
$this->order_model = $order_model;
// add the tracking link into the order status
$order_model->updateOrderStatus(null, ['comment' => 'Postmates Delivery requested from admin. Tracking url: <a target="_blank" href="' . $result['tracking_url'] . '" >'.$result['tracking_url'].'</a>']);
// send an email if the setting's on
if( PostmatesSettings::get('send_email_auto') ){
$this->mailSend('cupnoodles.postmates::mail.delivery_requested', 'customer');
$this->mailSend('cupnoodles.postmates::mail.delivery_requested', 'location');
}
}
}
public function mailGetRecipients($type)
{
$recipients = [];
switch ($type) {
case 'customer':
$recipients[] = [$this->order_model->email, $this->order_model->first_name . ' ' . $this->order_model->last_name];
break;
case 'location':
$recipients[] = [$this->order_model->location->location_email, $this->order_model->location->location_name];
break;
case 'admin':
$recipients[] = [setting('site_email'), setting('site_name')];
break;
}
return $recipients;
}
public function mailGetData()
{
return [
'tracking_url' => $this->tracking_url,
'first_name' => $this->order_model->first_name,
'last_name' => $this->order_model->last_name,
'requested_time' => date('H:i')
];
}
public function updatePostmatesDeliveryCost($location){
// if $location->coveredArea is of the base type but has delivery_service == postmates, replace it with the new PostmatesCoveredAreaClass
if(is_array($location->coveredArea()->conditions) && isset($location->coveredArea()->conditions[0])){
if($location->coveredArea()->conditions[0]['delivery_service'] == 'postmates'
&& is_object($location->coveredArea()) && get_class($location->coveredArea()) == 'Igniter\Local\Classes\CoveredArea'){
if ($areaId = (int)$location->getSession('area')){
$area = $location->getModel()->findDeliveryArea($areaId);
}
if (is_null($area)) {
$area = $location->getModel()->searchOrDefaultDeliveryArea(
$location->userPosition()->getCoordinates()
);
}
$ca = new PostmatesCoveredArea($area, $location);
$location->setCoveredArea($ca);
}
}
//echo get_class($location->coveredArea()); die();
}
public function registerSettings()
{
return [
'settings' => [
'label' => 'Postmates API settings',
'description' => 'Manage Postmates delivery API settings.',
'icon' => 'fa fa-shipping-fast',
'model' => 'CupNoodles\Postmates\Models\PostmatesSettings',
'permissions' => ['Module.Postmates'],
],
];
}
/**
* Registers any front-end components implemented in this extension.
*
* @return array
*/
public function registerComponents()
{
}
/**
* Registers any admin permissions used by this extension.
*
* @return array
*/
public function registerPermissions()
{
}
public function registerNavigation()
{
}
}