Skip to content

Instantly share code, notes, and snippets.

@angebagui
Last active May 15, 2020 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angebagui/5252580450d3ae05345fba2a2b4ad001 to your computer and use it in GitHub Desktop.
Save angebagui/5252580450d3ae05345fba2a2b4ad001 to your computer and use it in GitHub Desktop.
CustomerNotificationUtils to push notification in Adjemin
<?php
namespace App\Utils;
use App\Models\Customer;
use App\Models\CustomerDevice;
use App\Models\CustomerNotification;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
class CustomerNotificationUtils
{
const MESSAGE_SENT = "message_sent";
const ORDER_PASSED = "passed_order";
const ORDER_CONFIRMED = "order_confirmed";
const ORDER_REFUSED = "order_refused";
const TASK_ACCEPTED = "task_accepted";
const TASK_REFUSED = "task_refused";
/**
* @param $customerId
* @param $message @CustomerNotification
* @return bool|string
*/
public static function notify($customerId, $customerNotification){
$customer = Customer::where(["id" => $customerId])->first();
$defaultLanguage = $customer->language;
if($defaultLanguage == "fr"){
$title = $customerNotification->title;
$subtitle = $customerNotification->subtitle;
}else{
$title = $customerNotification->title_en;
$subtitle = $customerNotification->subtitle_en;
}
$customerDevices = CustomerDevice::where([
"customer_id" => $customerId,
"deleted_at" => null
])->orderBy('id', 'DESC')->take(1)->get();
foreach($customerDevices as $customerDevice){
$metadata = $customerNotification->toArray();
$typeNotification = $customerNotification->type_notification;
if($customerDevice != null){
$device = "".$customerDevice->firebase_id;
return FirebaseMessagingUtils::sendNotification($title, $subtitle,$typeNotification, $metadata, $device);
}else{
return "No Devices";
}
}
}
}
<?php
namespace App\Http\Controllers\API;
use App\Http\Requests\API\CreateOrderAPIRequest;
use App\Http\Requests\API\UpdateOrderAPIRequest;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\InvoicePayment;
use App\Models\Order;
use App\Models\OrderHistory;
use App\Models\OrderItem;
use App\Models\Product;
use App\Repositories\OrderRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Collection;
use Response;
use Symfony\Component\HttpFoundation\ParameterBag;
App\Utils\CustomerNotificationUtils;
/**
* Class OrderController
* @package App\Http\Controllers\API
*/
class OrderAPIController extends AppBaseController
{
/** @var OrderRepository */
private $orderRepository;
public function __construct(OrderRepository $orderRepo)
{
$this->orderRepository = $orderRepo;
}
/**
* @param CreateOrderAPIRequest $request
* @return Response
*
* @SWG\Post(
* path="/orders",
* summary="Store a newly created Order in storage",
* tags={"Order"},
* description="Store Order",
* produces={"application/json"},
* @SWG\Parameter(
* name="body",
* in="body",
* description="Order that should be stored",
* required=false,
* @SWG\Schema(ref="#/definitions/Order")
* ),
* @SWG\Response(
* response=200,
* description="successful operation",
* @SWG\Schema(
* type="object",
* @SWG\Property(
* property="success",
* type="boolean"
* ),
* @SWG\Property(
* property="data",
* ref="#/definitions/Order"
* ),
* @SWG\Property(
* property="message",
* type="string"
* )
* )
* )
* )
*/
public function store(CreateOrderAPIRequest $request)
{
try{
/** @var ParameterBag $jsonFields */
$jsonFields = $request->json();
$input = [];
$input['customer_id'] = $jsonFields->getInt('customer_id');
$input['is_waiting'] = true;
$input['current_status'] = 'waiting';
$input['payment_method_slug'] = $jsonFields->get('payment_method_slug');
$input['delivery_fees'] = (double) $jsonFields->get('delivery_fees');
$input['is_delivered'] = false;
$input['rating'] = '';
$input['is_waiting_payment'] = true;
$input['note'] = '';
$customer = Customer::where(['id' => $jsonFields->getInt('customer_id')])->first();
$items = (array) $jsonFields->get('items');
$order = $this->orderRepository->create($input);
$subtotal = (double) $jsonFields->get('delivery_fees');
$currencyCode = 'XOF';
foreach ($items as $item){
$item = (array)$item;
/** @var Product $product */
$product = Product::where(['id' => $item['product_id']])->first();
$currencyCode = $product->currency_slug;
$totalAmount = ((int)$product->price) * ((int)$item['quantity']);
$subtotal += $totalAmount;
$orderItem = OrderItem::create([
'order_id'=> $order->id,
'meta_data_id' => $product->id,
'meta_data' => json_encode($product),
'quantity' => $item['quantity'],
'quantity_unit'=> 'number',
'unit_price' => $product->price,
'currency_code' => $product->currency_slug,
'total_amount' => $totalAmount
]);
}
$tax = $subtotal * Invoice::TAXES;
$total = $subtotal + $tax;
$order->amount = $total;
$order->currency_code = $currencyCode;
$order->save();
$invoice = Invoice::create([
'order_id' => $order->id,
'customer_id' => $jsonFields->getInt('customer_id'),
'reference' => Invoice::generateID('SHOP', $order->id, $jsonFields->getInt('customer_id')),
'link' => '#',
'subtotal' => $subtotal,
'service' => 'shop',
'tax' => $tax,
'fees_delivery' => (double) $jsonFields->get('delivery_fees'),
'total' => $total,
'status' => 'unpaid',
'is_paid_by_customer' => false,
'is_paid_by_delivery_service' => false,
'currency_code' => $currencyCode
]);
$orderHistory = new OrderHistory();
$orderHistory->order_id = $order->id;
$orderHistory->status = 'waiting_payment';
$orderHistory->order_id = $order->id;
$orderHistory->creator = 'customer';
$orderHistory->creator_id = $customer->id;
$orderHistory->creator_name = $customer->name;
$orderHistory->save();
$transactionResponse = null;
if($jsonFields->get('payment_method_slug') == "online"){
//TODO Notify user
$transactionId = self::generateTransId($customer->id, $invoice->id, $order->id);
$transaction = InvoicePayment::create([
'invoice_id' => $invoice->id,
'payment_method'=> $jsonFields->get('payment_method_slug'),
'payment_reference' => $transactionId,
'amount' => $invoice->total,
'currency_code' => $invoice->currency_code,
'creator_id' => $customer->id,
'creator' => 'customer',
'creator_name' => $customer->name
]);
$transactionResponse = [
'payment_method'=> $transaction->payment_method,
'transaction_id' => $transactionId,
'transaction_designation' => 'Buying Product',
'amount' => $transaction->amount,
'currency_code' => $transaction->currency_code,
'status' => $transaction->status
];
}
if($jsonFields->get('payment_method_slug') == "online"){
$customerNotification = CustomerNotification::create(
[
'title' => 'Commande #'.$order->id.' en attente',
'title_en' => 'Order #'.$order->id.' pending',
'subtitle' => 'Vous avez une commande à valider.',
'subtitle_en' => 'You have an order to confirm.',
'action' => '',
'action_by' => '',
'meta_data' => $order,
'meta_data_id' => $order->id,
'type_notification' => CustomerNotification::ORDER_PASSED,
'is_read' => false,
'is_received' => false,
'data' => $order,
'customer_id' => $customer->id,
'data_id' => $order->id
]
);
CustomerNotificationUtils::notify($customer->id, $customerNotification);
}
return $this->sendResponse([
'order' => $order,
'transaction' => $transactionResponse
], 'Order saved successfully');
}catch (\Exception $exception){
return $this->sendError($exception->getMessage());
}
}
/**
* generate transId
* @return int
*/
public static function generateTransId($customerId, $invoiceId, $orderId)
{
$timestamp = time();
$parts = explode(' ', microtime());
$id = ($timestamp + $parts[0] - strtotime('today 00:00')) * 10;
$id = sprintf('%06d', $id) . mt_rand(100, 9999);
$transId = $id."-".$customerId."-".$invoiceId."-".$orderId;
$transactions = InvoicePayment::where(['payment_reference' => $transId])->get();
if( count($transactions) == 0){
return $transId;
}else{
$autoIncrement = count($transactions) + 1;
$transId = $transId.'-'.$autoIncrement;
return $transId;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment