· 5 years ago · Jan 30, 2021, 11:24 AM
1<?php
2
3namespace App\Http\Controllers\api;
4
5use App\Http\Controllers\Controller;
6use Illuminate\Http\Request;
7use App\Http\Resources\Provinces as ProvinceResourceCollection;
8use App\Models\City;
9use App\Http\Resources\Cities as CityResourceCollection;
10use DB;
11use Auth;
12use Validator;
13use App\Models\User;
14use App\Models\Book;
15use App\Models\Order;
16use App\Models\BookOrder;
17use App\Models\Province;
18
19
20class ShopController extends Controller
21{
22 public function provinces()
23 {
24 return new ProvinceResourceCollection(Province::get());
25 }
26
27 public function cities()
28 {
29 return new CityResourceCollection(City::get());
30 }
31
32 /**
33 * Update the specified resource in storage.
34 *
35 * @param \Illuminate\Http\Request $request
36 * @return \Illuminate\Http\Response
37 */
38 public function shipping(Request $request)
39 {
40 $user = Auth::user();
41 $status = "error";
42 $message = "";
43 $data = null;
44 $code = 200;
45 if ($user) {
46 $this->validate($request, [
47 'name' => 'required',
48 'address' => 'required',
49 'phone' => 'required',
50 'province_id' => 'required',
51 'city_id' => 'required',
52 ]);
53 $user->name = $request->name;
54 $user->address = $request->address;
55 $user->phone = $request->phone;
56 $user->province_id = $request->province_id;
57 $user->city_id = $request->city_id;
58 if($user->save()){
59 $status = "success";
60 $message = "Update shipping success";
61 $data = $user->toArray();
62 }
63 else{
64 $message = "Update shipping failed";
65 }
66 }
67 else{
68 $message = "User not found";
69 }
70
71 return response()->json([
72 'status' => $status,
73 'message' => $message,
74 'data' => $data
75 ], $code);
76 }
77
78 public function couriers()
79 {
80 $couriers = [
81 ['id'=>'jne', 'text'=> 'JNE'],
82 ['id'=>'tiki', 'text'=> 'TIKI'],
83 ['id'=>'pos', 'text'=> 'POS'],
84 ];
85
86 return response()->json([
87 'status' => 'success',
88 'message' => 'courier',
89 'data' => $couriers
90 ], 200);
91 }
92
93 protected function getServices($data)
94 {
95 $url_cost = "https://api.rajaongkir.com/starter/cost";
96 $key="006cd37c5e5cedd9cede4579df76a79e";
97 $postdata = http_build_query($data);
98 $curl = curl_init();
99 curl_setopt_array($curl, [
100 CURLOPT_URL => $url_cost,
101 CURLOPT_RETURNTRANSFER => true,
102 CURLOPT_ENCODING => "",
103 CURLOPT_MAXREDIRS => 10,
104 CURLOPT_TIMEOUT => 30,
105 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
106 CURLOPT_CUSTOMREQUEST => "POST",
107 CURLOPT_POSTFIELDS => $postdata,
108 CURLOPT_HTTPHEADER => [
109 "content-type: application/x-www-form-urlencoded",
110 "key: ".$key
111 ],
112 ]);
113 $response = curl_exec($curl);
114 $error = curl_error($curl);
115 curl_close($curl);
116 return [
117 'error' => $error,
118 'response' => $response,
119 ];
120 }
121
122 protected function validateCart($carts)
123 {
124 $safe_carts = [];
125 $total = [
126 'quantity_before' => 0,
127 'quantity' => 0,
128 'price' => 0,
129 'weight' => 0,
130 ];
131 $idx = 0;
132 foreach($carts as $cart){
133 $id = (int)$cart['id'];
134 $quantity = (int)$cart['quantity'];
135 $total['quantity_before'] += $quantity;
136 $book = Book::find($id);
137 if($book){
138 if($book->stock>0){
139 $safe_carts[$idx]['id'] = $book->id;
140 $safe_carts[$idx]['title'] = $book->title;
141 $safe_carts[$idx]['cover'] = $book->cover;
142 $safe_carts[$idx]['price'] = $book->price;
143 $safe_carts[$idx]['weight'] = $book->weight;
144 if($book->stock < $quantity){
145 $quantity = (int) $book->stock;
146 }
147 $safe_carts[$idx]['quantity'] = $quantity;
148
149 $total['quantity'] += $quantity;
150 $total['price'] += $book->price * $quantity;
151 $total['weight'] += $book->weight * $quantity;
152 $idx++;
153 }
154 else{
155 continue;
156 }
157 }
158 }
159 return [
160 'safe_carts' => $safe_carts,
161 'total' => $total,
162 ];
163 }
164
165 public function services(Request $request)
166 {
167 $status = "error";
168 $message = "";
169 $data = [];
170 // validasi kelengkapan data
171 $this->validate($request, [
172 'courier' => 'required',
173 'carts' => 'required',
174 ]);
175
176 $user = Auth::user();
177 if($user){
178 $destination = $user->city_id;
179 if($destination>0){
180 // hardcode
181 $origin = 153; // Jakarta Selatan
182 $courier = $request->courier;
183 $carts = $request->carts;
184 $carts = json_decode($carts, true);
185 // validasi data belanja
186 $validCart = $this->validateCart($carts);
187 $data['safe_carts'] = $validCart['safe_carts'];
188 $data['total'] = $validCart['total'];
189 $quantity_different = $data['total']['quantity_before']<>$data['total']['quantity'];
190 $weight = $validCart['total']['quantity'] * 1000;
191 if($weight>0){
192 // request courier service API RajaOngkir
193 $parameter = [
194 "origin" => $origin,
195 "destination" => $destination,
196 "weight" => $weight,
197 "courier" => $courier
198 ];
199 $respon_services = $this->getServices($parameter);
200 if ($respon_services['error']==null) {
201 $services = [];
202 $response = json_decode($respon_services['response']);
203 // return response()->json([
204 // 'debug' => $response,
205 // ], 200);
206 // dd($response);
207 $costs = $response->rajaongkir->results[0]->costs;
208 foreach($costs as $cost){
209 $service_name = $cost->service;
210 $service_cost = $cost->cost[0]->value;
211 $service_estimation = str_replace('hari', '', trim($cost->cost[0]->etd));
212 $services[] = [
213 'service' => $service_name,
214 'cost' => $service_cost,
215 'estimation' => $service_estimation,
216 'resume' => $service_name .' [ Rp. '.number_format($service_cost).', Etd: '.$cost->cost[0]->etd.' day(s) ]'
217 ];
218 }
219
220 // Response
221 if(count($services)>0){
222 $data['services'] = $services;
223 $status = "success";
224 $message = "getting services success";
225 }
226 else{
227 $message = "courier services unavailable";
228 }
229
230 if($quantity_different){
231 $status = "warning";
232 $message = "Check cart data, ".$message;
233 }
234
235 } else {
236 $message = "cURL Error #:" . $respon_services['error'];
237 }
238 }
239 else{
240 $message = "weight invalid";
241 }
242 }
243 else{
244 $message = "destination not set";
245 }
246 }
247 else{
248 $message = "user not found";
249 }
250
251 return response()->json([
252 'status' => $status,
253 'message' => $message,
254 'data' => $data
255 ], 200);
256 }
257
258 public function payment(Request $request)
259 {
260 $error = 0;
261 $status = "error";
262 $message = "";
263 $data = [];
264
265 $user = Auth::user();
266 if ($user) {
267 // validasi kelengkapan data
268 $this->validate($request, [
269 'courier' => 'required',
270 'service' => 'required',
271 'carts' => 'required',
272 ]);
273
274 DB::beginTransaction();
275 try {
276 // prepare data
277 $origin = 153; // Jakarta Selatan
278 $destination = $user->city_id;
279 if($destination<=0) $error++;
280 $courier = $request->courier;
281 $service = $request->service;
282 $carts = json_decode($request->carts, true);
283
284 // create order
285 $order = new Order;
286 $order->user_id = $user->id;
287 $order->total_bill = 0;
288 $order->invoice_number = date('YmdHis');
289 $order->courier_service = $courier.'-'.$service;
290 $order->status = 'SUBMIT';
291 if($order->save()){
292 $total_price = 0;
293 $total_weight = 0;
294 foreach($carts as $cart){
295 $id = (int)$cart['id'];
296 $quantity = (int)$cart['quantity'];
297 $book = Book::find($id);
298 if($book){
299 if($book->stock>=$quantity){
300 $total_price += $book->price * $quantity;
301 $total_weight += $book->weight * $quantity;
302 // create book order
303 $book_order = new BookOrder;
304 $book_order->book_id = $book->id;
305 $book_order->order_id = $order->id;
306 $book_order->quantity = $quantity;
307 if($book_order->save()){
308 // kurangi stock
309 $book->stock = $book->stock - $quantity;
310 $book->save();
311 }
312 }
313 else{
314 $error++;
315 throw new \Exception('Out of stock');
316 }
317 }
318 else{
319 $error++;
320 throw new \Exception('Book is not found');
321 }
322 }
323
324 $totalBill = 0;
325 $weight = $total_weight * 1000; // to gram
326 if($weight<=0) {
327 $error++;
328 throw new \Exception('Weight null');
329 }
330 $data = [
331 "origin" => $origin,
332 "destination" => $destination,
333 "weight" => $weight,
334 "courier" => $courier
335 ];
336 $data_cost = $this->getServices($data);
337 if ($data_cost['error']){
338 $error++;
339 throw new \Exception('Courier service unavailable');
340 }
341
342 $response = json_decode($data_cost['response']);
343 $costs = $response->rajaongkir->results[0]->costs;
344 $service_cost = 0;
345 foreach($costs as $cost){
346 $service_name = $cost->service;
347 if($service == $service_name){
348 $service_cost = $cost->cost[0]->value;
349 break;
350 }
351 }
352 if ($service_cost<=0){
353 $error++;
354 throw new \Exception('Service cost invalid');
355 }
356
357 $total_bill = $total_price + $service_cost;
358 // update total bill order
359 $order->total_bill = $total_bill;
360 if($order->save()){
361 if($error==0){
362 DB::commit();
363 $status = 'success';
364 $message = 'Transaction success';
365 $data = [
366 'order_id' => $order->id,
367 'total_bill' => $total_bill,
368 'invoice_number' => $order->invoice_number,
369 ];
370 }
371 else{
372 $message = 'There are '.$error.' errors';
373 }
374 }
375 }
376 } catch (\Exception $e) {
377 $message = $e->getMessage();
378 DB::rollback();
379 }
380 }
381 else{
382 $message = "User not found";
383 }
384
385 return response()->json([
386 'status' => $status,
387 'message' => $message,
388 'data' => $data
389 ], 200);
390
391 }
392
393 public function myOrder(Request $request)
394 {
395 $user = Auth::user();
396 $status = "error";
397 $message = "";
398 $data = [];
399 if($user){
400 $orders = Order::select('*')
401 ->where('user_id','=',$user->id)
402 ->orderBy('id','DESC')
403 ->get();
404
405 $status = "success";
406 $message = "data my order ";
407 $data = $orders;
408 }
409 else{
410 $message = "User not found";
411 }
412
413 return response()->json([
414 'status' => $status,
415 'message' => $message,
416 'data' => $data
417 ], 200);
418 }
419}