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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
|
<?php
class Invoice extends BaseModel { protected $table = "invoice";
public function invoiceItems() { return $this->hasMany('InvoiceItem', 'invoice_id', 'id'); }
public function order() { return $this->belongsTo('Order', 'order_id', 'id'); }
public function customer() { return $this->belongsTo('Customer', 'customer_id', 'id'); }
public function paymentRecords() { return $this->hasMany('PaymentRecord', 'invoice_id', 'id'); }
// payments is a temp name, should be paymentRecords public function payments() { return $this->morphMany('PaymentRecord', 'payable'); }
public function generateCode($force_update = false) { // code already exist if ($this->code && !$force_update) { return $this; }
if ($this->id && $this->order && $this->order->code) { $this->code = "{$this->order->code}-I{$this->id}"; } else { $this->code = MasterSetting::get('ORDER_NUMBER_PREFIX') . date("ym") . "-D{$this->id}"; } return $this; }
public function calcAmount() { $amount = 0; foreach ($this->InvoiceItems as $invoiceItem) { $amount += $invoiceItem->discounted_price; } $this->amount = $amount; return $this; }
public function getDiscountAmount() { $amount = 0; foreach ($this->InvoiceItems as $invoiceItem) { $amount += ($invoiceItem->price * $invoiceItem->quantity) - $invoiceItem->discounted_price; } return $amount; }
public function getForeignAmount() { return $this->amount * $this->currency_rate; }
public function confirm($_DATA) { if (in_array($this->status, ["PAID"])) { // or any status that invoice payment should not be accepted // duplicated confirm notification throw new InvoiceAlreadyCompletedException("Completed Order", 1); }
$validData = true;
if (!$validData) { $response = array("RESPONSE_CONTENT" => null, "RESPONSE_CODE" => "FAIL", "RESPONSE_ERR_MSG" => lang("Missing required parameters.")); } else { global $site_info, $dbh, $_delivery, $_order_email, $_checkout, $master_settings;
foreach ($this->invoiceItems as $invoiceItem) { switch (get_class($invoiceItem->invoiceable)) { case 'OrderItemPhase': $invoiceItem->invoiceable->confirm(); break;
default: throw new Exception("Unexpected invoiceable: " . get_class($invoiceItem->invoiceable), 1); break; } // vdump(get_class($invoiceable), $invoiceable); }
$valid = false; try { $dbh->beginTransaction(); $message = "";
$nowdate = date("Y-m-d H:i:s");
// assume one invoice belongs to one order $order_item_info = [$this->invoiceItems[0]->invoiceable->orderItem]; $order = $order_item_info[0]->order ?: $this->order; // vdump($order, $this->invoiceItems[0]->invoiceable->orderItem); exit; $customer_info = $this->customer->decrypt();
//update order $gain_point = floor($this["amount"] - $this["shipping_fee"]); $client_ip = get_client_ip(); $user_agent = $_SERVER['HTTP_USER_AGENT'];
$this->fill([ 'gain_points' => $gain_point, 'currency_code' => $_DATA["currency_code"] ?: $site_info['currency_code'], 'currency_rate' => $_DATA['currency_rate'] ?: 1, 'purchase_date' => timestamp(), 'ip' => $client_ip, 'user_agent' => $user_agent, 'status' => 'PAID', ])->save();
$order->fill([ 'temp' => 0, 'gain_points' => $order->gain_points + $gain_point, 'currency_code' => $_DATA["currency_code"] ?: $site_info['currency_code'], 'currency_rate' => $_DATA["currency_rate"] ?: 1, 'purchase_date' => $order->purchase_date ?: $nowdate, 'ip' => $client_ip, 'user_agent' => $user_agent, 'status' => "PAID", ])->generateCode()->save();
$order_code = $order->code;
if ($order->type == "BULK") { foreach ($order->supplierOrders as $supplierOrder) { // update supplierOrder.amount with sum of invoiceItems of the supplier // vdump($supplierOrder->supplier->id); $item_total = 0; $ori_total_amount = 0; $discounted_price_total = 0; $total_amount = 0;
// calculate totals $this->invoiceItems->where('supplier_id', $supplierOrder->supplier_id) ->each(function ($m) use ($supplierOrder, &$item_total, &$ori_total_amount, &$total_amount) { $item_total += $m->price * $m->quantity; $ori_total_amount += $m->discounted_price; $total_amount = $supplierOrder->supplier->deductCommission($ori_total_amount); }); // vdump($item_total, $ori_total_amount, $total_amount);
$supplierOrder = $order->orderItems->first()->supplierOrder; $supplierOrder->fill([ 'purchase_date' => timestamp(), 'code' => $order->code, 'item_total' => $item_total, 'discount_total' => $item_total - $discounted_price_total, 'ori_total_amount' => $ori_total_amount, 'total_amount' => $total_amount, 'status' => $order->status, 'langcode' => $order->langcode, 'currency_code' => $order->currency_code, 'currency_rate' => $order->currency_rate, ])->save();
//notification $syscmslogin = SysCmsLogin::select("cmsloginid")->where("supplier_id", $supplierOrder->supplier_id)->first(); $notification = Notification::create(array( 'type' => 'NEGOTIATION_PAID', 'table_name' => 'supplier_order', 'table_id' => $supplierOrder->id, 'cmsloginid' => $syscmslogin->cmsloginid, 'createdate' => date("Y-m-d H:i:s"), 'createby' => $syscmslogin->cmsloginid, 'lastupdate' => date("Y-m-d H:i:s"), 'lastupby' => $syscmslogin->cmsloginid, )); // end of notification } } else { // mark temp customer order item to this order foreach ($order->customerTempOrderItems() as $orderItem) { $order->orderItems()->save($orderItem); // vdump($orderItem->order_id); // $orderItem->order_id = $order->id; // $orderItem->save(); }
// create supplier order by order item $supplierOrders = []; foreach ($order->orderItems as $orderItem) { if (!array_key_exists($orderItem->supplier_id, $supplierOrders)) { $supplierOrder = new SupplierOrder([ 'order_id' => $order->id, 'supplier_id' => $orderItem->supplier_id, 'temp' => 0, 'customer_id' => $order->customer_id, 'purchase_date' => $order->purchase_date, 'code' => $order->code, 'currency_code' => $order->currency_code, 'currency_rate' => $order->currency_rate, 'status' => $order->status, 'langcode' => $order->langcode, // 'item_total' => ($orderItem->price * $orderItem->quantity), // price*quantity // 'discount_total' => ($orderItem->price * $orderItem->quantity) - $orderItem->discounted_price,// $item_total - $discounted_price_total // 'ori_total_amount' => $orderItem->discounted_price, // $ori_total_amount // 'total_amount' => $orderItem->supplier->deductCommission($orderItem->discounted_price),// $amount ]);
//notification $syscmslogin = SysCmsLogin::select("cmsloginid")->where("supplier_id", $orderItem->supplier_id)->first(); $notification = Notification::create(array( 'type' => 'NEGOTIATION_PAID', 'table_name' => 'supplier_order', 'table_id' => $supplierOrder->id, 'cmsloginid' => $syscmslogin->cmsloginid, 'createdate' => date("Y-m-d H:i:s"), 'createby' => $syscmslogin->cmsloginid, 'lastupdate' => date("Y-m-d H:i:s"), 'lastupby' => $syscmslogin->cmsloginid, )); // end of notification }
$supplierOrder->item_total += ($orderItem->price * $orderItem->quantity); // price*quantity $supplierOrder->discount_total += ($orderItem->price * $orderItem->quantity) - $orderItem->discounted_price; // $item_total - $discounted_price_total $supplierOrder->ori_total_amount += $orderItem->discounted_price; // $ori_total_amount $supplierOrder->total_amount += $orderItem->supplier->deductCommission($orderItem->discounted_price); // $amount
$supplierOrders[$orderItem->supplier_id] = $supplierOrder; } $order->supplierOrders()->saveMany($supplierOrders);
// update orderItem.supplier_order_id foreach ($order->orderItems as $orderItem) { if (!$orderItem->supplier_order_id && $orderItem->supplier_id && array_key_exists($orderItem->supplier_id, $supplierOrders)) { $orderItem->supplierOrder()->associate($supplierOrders[$orderItem->supplier_id]); $orderItem->save(); // $supplierOrders[$orderItem->supplier_id]->orderItems()->save($orderItem); } }
//deduct points if (!empty($order["apply_available_points"])) {
$sql = "insert into customer_point (customer_id, points, status, table_name, table_refid, createby, createdate) values (?,?,?,?,?,?,?)"; $parameters = array($this->customer->id, -$order["apply_available_points"], "APPROVED", "order", $order->id, 0, $nowdate); bind_pdo($sql, $parameters);
$sql = "update customer set points=points-? where id = ?"; $parameters = array($order["apply_available_points"], $this->customer->id); bind_pdo($sql, $parameters); }
//update order discount, temp = 0 $sql = "update order_discount set order_id = ?, temp = ? where customer_id = ? and temp = ? "; $parameters = array($order->id, 0, $this->customer->id, 1); bind_pdo($sql, $parameters);
//get coupon, coupon usage $sql = "select * from coupon_usage cu INNER JOIN coupon c ON c.id = cu.coupon_id where cu.temp = ? and cu.customer_id = ?"; $parameters = array(1, $this->customer->id); $result = bind_pdo($sql, $parameters, "selectall"); foreach ($result as $row) { if ($row["coupon_type"] == "COUPON") { //direct update coupon status to used $sql = "update coupon set `status` = ?, lastupdate = ? where id = ? and customer_id = ?"; $parameters = array("USED", date("Y-m-d H:i:s"), $row["coupon_id"], $this->customer->id); bind_pdo($sql, $parameters); } else if ($row["coupon_type"] == "PROMOTION_CODE") { //check the total used number in coupon usage $sql = "select count(*) as used_num from coupon_usage where temp = ? and customer_id IS NOT NULL and total_deduct_amt > ? and deleted = ?"; $parameters = array(0, 0, 0); $result2 = bind_pdo($sql, $parameters, "selectone"); if ($result2["used_num"] >= $row["usage_limit"]) { //update promotion code status to used $sql = "update coupon set `status` = ?, lastupdate = ? where id = ?"; $parameters = array("USED", date("Y-m-d H:i:s"), $row["coupon_id"]); bind_pdo($sql, $parameters); } }
//update coupon usage / promotion code $sql = "update coupon_usage set order_id = ?, temp = ? where customer_id = ? and temp = ? "; $parameters = array($order->id, 0, $this->customer->id, 1); bind_pdo($sql, $parameters);
}
//update order discount $sql = "update order_discount set order_id = ?, temp = ? where customer_id = ? and temp = ? "; $parameters = array($order->id, 0, $this->customer->id, 1); bind_pdo($sql, $parameters); } // end order.type!=BULK
foreach ($order->orderItems as $orderItem) { $orderItem->temp = 0; $orderItem->updateStatus($order->status)->save(); $orderItemTrack = $orderItem->createOrderItemTrack('SYSTEM', "Payment is completed.", "", [$this->code])->save(); }
//insert data to payease table $payeasePayment = PayeasePayment::create([ 'code' => $this->code, 'status' => "INPROGRESS", 'invoice_id' => $this->id, ]);
foreach ($this->invoiceItems as $invoiceItem) { $supplier = $invoiceItem->invoiceable->orderItem->supplier;
// //update payease payment dtl code // $sql = "update order_item set payease_payment_dtl_code = ? where id = ? "; // $parameters = array($order_code . "-" . $invoiceItem["order_item_id"], $invoiceItem["order_item_id"]); // bind_pdo($sql, $parameters); $invoiceItem->payease_payment_dtl_code = "{$this->code}-{$invoiceItem->id}"; $invoiceItem->save();
$paymentRecord = $this->paymentRecords()->where('paystatus', 1)->first();
//for supplier in payment currency $supplierPayeasePaymentDtl = PayeasePaymentDtl::create([ 'payease_payment_id' => $payeasePayment->id, 'code' => "{$this->code}-{$invoiceItem->id}", 'status' => 'NEW', // 'amount' => round($supplier->deductCommission($invoiceItem->discounted_price), 1), 'currency_code' => $paymentRecord->currency_code ?: 'CNY', 'amount' => $invoiceItem->getSupplierReceivableAmount(), 'name_en' => floatval(100 - $supplier->platform_commission_value) . "% " . $supplier["name_en"] . " of " . $invoiceItem->invoiceable->orderItem->proProductSku->code, 'qty' => $invoiceItem->quantity, 'number' => $invoiceItem->invoiceable->orderItem->proProductSku->code, 'payease_account_code' => $supplier->payease_account_code, 'supplier_id' => $supplier->id, 'invoice_item_id' => $invoiceItem->id, 'payment_type' => $paymentRecord->payment_type ?: "NA", 'payment_method' => $paymentRecord->payment_method ?: "NA", 'settlement_paymentgateway' => $supplier->getSettlementPaymentGateway(), 'settlement_currency_code' => $supplier->currency_code, 'settlement_amount' => $invoiceItem->getSupplierReceivableAmount(), // in supplier currency ]);
// exit($supplierPayeasePaymentDtl);exit;
//for platform in payment currency PayeasePaymentDtl::create([ 'payease_payment_id' => $payeasePayment->id, 'code' => "{$this->code}-{$invoiceItem->id}-PLATFORM", 'status' => 'NEW', 'currency_code' => $paymentRecord->currency_code ?: 'CNY', 'amount' => ($invoiceItem->discounted_price * $this->currency_rate) - $supplierPayeasePaymentDtl->amount, 'name_en' => floatval($supplier->platform_commission_value) . "% Platform Commission of " . $invoiceItem->invoiceable->orderItem->proProductSku->code, 'qty' => $invoiceItem->quantity, 'number' => $invoiceItem->invoiceable->orderItem->proProductSku->code, 'payease_account_code' => MasterSetting::get('PAYEASE_MID'), 'invoice_item_id' => $invoiceItem->id, 'payment_type' => $paymentRecord->payment_type ?: "NA", 'payment_method' => $paymentRecord->payment_method ?: "NA", // settlement_paymentgateway // settlement_currency_code // settlement_amount ]); } // vdump($invoiceItem->discounted_price, $invoiceItem->getSupplierReceivableAmount(), ($invoiceItem->discounted_price * $this->currency_rate) - $supplierPayeasePaymentDtl->amount); // dq(1,1);
$dbh->commit();
$valid = true; } catch (Exception $e) {
$dbh->rollBack();
echo $e->getMessage(); // vdump($e); exit; }
if ($valid) { if (!empty($customer_info{"email"}) && filter_var($customer_info{"email"}, FILTER_VALIDATE_EMAIL)) { $send_result = $this->sendEmailCustomer(); } else { $send_result = lang("We have received your order. Your order will process as soon as possible."); }
$this->sendEmailSupplier(); //end of email to supplier if (isset($_DATA["PC"]) && $_DATA["PC"] == 1) { global $segment; $segment->setFlash('success', $send_result); header("Location: order_success.php?order_code=" . $order_code); /*return '<script type="text/javascript"> alert("' . $send_result . '"); top.location.href="order_success.php?order_code=' . $order_code . '"; </script>';*/ } else { if (!empty($order_code)) { $response = array("RESPONSE_CONTENT" => $order_code, "RESPONSE_CODE" => "SUCCESS", "RESPONSE_ERR_MSG" => null, "HTML_MSG" => $send_result); } else { $response = array("RESPONSE_CONTENT" => null, "RESPONSE_CODE" => "FAIL", "RESPONSE_ERR_MSG" => "Cannot return invoice number."); } } } }
return $response; }
public function sendEmailCustomer() {
global $site_info; global $langcode;
$customer_info = $this->customer->decrypt();
$x_mail = new PHPMailer(); // default values $x_mail->IsSMTP(); $x_mail->IsHTML(true); // $x_mail->SMTPDebug = 1; // $x_mail->SMTPDebug = true; $x_mail->Host = MasterSetting::get('SMTP_HOST') ?: $x_mail->Host; $x_mail->Port = MasterSetting::get('SMTP_PORT') ?: $x_mail->Port; $x_mail->SMTPAuth = MasterSetting::get('SMTP_SMTPAUTH') ? true : false; $x_mail->Username = MasterSetting::get('SMTP_USERNAME'); $x_mail->Password = MasterSetting::get('SMTP_PASSWORD'); $x_mail->SMTPSecure = MasterSetting::get('SMTP_SMTPSECURE') ?: $x_mail->SMTPSecure; $x_mail->CharSet = "UTF-8"; $x_mail->WordWrap = 50; $x_mail->Sender = MasterSetting::get('PLATFORM_ORDER_EMAIL'); $x_mail->From = MasterSetting::get('PLATFORM_ORDER_EMAIL'); $x_mail->FromName = $site_info{"companyname_" . $langcode}; $x_mail->Subject = $site_info{"companyname_" . $langcode} . " " . $this->code; $x_mail->AddAddress($customer_info->email, $customer_info->fullname());
ob_start(); require __DIR__ . '/../resources/invoice_customer.php'; $x_mail->Body = ob_get_contents(); ob_end_clean();
// echo $x_mail->Body;
if ($x_mail->Send()) { $this->send_email_customer = 1; $send_result = lang("We have received your order. Your order will process as soon as possible. <br><br> You can get your order detail in your email account."); } else { // vdump($x_mail->ErrorInfo); $this->send_email_customer = 0; $send_result = lang("We have received your order. Your order will process as soon as possible. <br><br> Email cannot send to you."); }
$this->save(); return $send_result; }
public function sendEmailSupplier() {
global $site_info; global $langcode;
$order_supplier_list = get_order_supplier_list(0, $this->order->id); $customer_info = $this->customer->decrypt();
$this->send_email_supplier = 0; foreach ($order_supplier_list as $supplier_id) { $supplier_info = get_supplier($supplier_id); //$supplier_order_info = get_supplier_order(); if (empty($supplier_info["receive_order_email"])) { continue; }
$supplier_email_langcode = $supplier_info["email_langcode"];
// get item info in supplier language // $order_item_info_supplier_lang = get_order_item($this->customer->id, null, 0, $order_id, null, null, 0, $supplier_email_langcode); // vdump($order_item_info_supplier_lang); exit;
$x_mail = new PHPMailer(); // default values $x_mail->IsSMTP(); $x_mail->IsHTML(true); // $x_mail->SMTPDebug = 1; // $x_mail->SMTPDebug = true; $x_mail->Host = MasterSetting::get('SMTP_HOST') ?: $x_mail->Host; $x_mail->Port = MasterSetting::get('SMTP_PORT') ?: $x_mail->Port; $x_mail->SMTPAuth = MasterSetting::get('SMTP_SMTPAUTH') ? true : false; $x_mail->Username = MasterSetting::get('SMTP_USERNAME'); $x_mail->Password = MasterSetting::get('SMTP_PASSWORD'); $x_mail->SMTPSecure = MasterSetting::get('SMTP_SMTPSECURE') ?: $x_mail->SMTPSecure; $x_mail->CharSet = "UTF-8"; $x_mail->WordWrap = 50; $x_mail->Sender = MasterSetting::get('PLATFORM_ORDER_EMAIL'); $x_mail->From = MasterSetting::get('PLATFORM_ORDER_EMAIL'); $x_mail->FromName = $site_info{"companyname_" . $langcode}; $x_mail->Subject = $site_info{"companyname_" . $langcode} . " " . $this->code; $x_mail->AddAddress($customer_info->email, $customer_info->fullname());
ob_start(); require __DIR__ . '/../resources/invoice_supplier.php'; $x_mail->Body = ob_get_contents(); ob_end_clean();
// echo $x_mail->Body;
if ($x_mail->Send()) { $this->send_email_supplier = 1; } }
$this->save(); }
public function createCustomerPoint(Customer $customer) { if ($this->amountToPoint() > 0) { // vdump("InvoiceID: {$invoice->id} amount:{$invoice->amount}"); $customerPoint = CustomerPoint::create([ 'customer_id' => $customer->id, // amount to point ratio = 1:1 'points' => $this->amountToPoint(), 'status' => 'APPROVED', 'table_name' => get_class($invoice), 'table_refid' => $this->id, ]);
$this['give_points'] = $customerPoint->points; $this->save(); } }
/** * invoice amount (CNY) to customer point * @return int customer point */ public function amountToPoint() { return 0; // formula: 1:1 return max(0, floor($this->amount)); } }
|