diff --git a/app/Http/Controllers/Admin/CategoryController.php b/app/Http/Controllers/Admin/CategoryController.php new file mode 100644 index 0000000..de4dd61 --- /dev/null +++ b/app/Http/Controllers/Admin/CategoryController.php @@ -0,0 +1,85 @@ +has('active')) { + $query->where('active', (int) $request->active); + } + + if ($request->filled('search')) { + $query->where('name', 'like', '%' . $request->search . '%'); + } + + $categories = $query + ->orderBy('id', 'asc') + ->get(); + + return response()->json($categories); + } + + public function store(Request $request) + { + $name = trim((string) $request->input('name')); + + if ($name === '') { + throw new UnprocessableEntityHttpException('نام دسته‌بندی الزامی است'); + } + + if (Category::where('name', $name)->exists()) { + throw new UnprocessableEntityHttpException('این دسته‌بندی قبلا ثبت شده است'); + } + + $category = Category::create([ + 'name' => $name, + 'active' => $request->has('active') ? (int) $request->active : 1, + ]); + + return response()->json($category); + } + + public function clientIndex(Request $request) + { + $query = Category::query() + ->where('active', 1); + + if ($request->filled('search')) { + $query->where('name', 'like', '%' . $request->search . '%'); + } + + $categories = $query + ->orderBy('id', 'asc') + ->get(); + + return response()->json($categories); + } + + public function changeActive($id, $active) + { + $active = (int) $active; + + if (! in_array($active, [0, 1], true)) { + throw new UnprocessableEntityHttpException('وضعیت active نامعتبر است'); + } + + $category = Category::findOrFail($id); + + $category->active = $active; + $category->save(); + + return response()->json([ + 'message' => $active ? 'دسته‌بندی فعال شد' : 'دسته‌بندی غیرفعال شد', + 'data' => $category, + ]); + } +} diff --git a/app/Http/Controllers/Admin/GiftCardController.php b/app/Http/Controllers/Admin/GiftCardController.php index 9466f9d..b3ca3f6 100644 --- a/app/Http/Controllers/Admin/GiftCardController.php +++ b/app/Http/Controllers/Admin/GiftCardController.php @@ -12,12 +12,17 @@ use App\Models\Withdraw; use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException; use Rooyesh\Wallet\interfaces\TransactionInterface; use Rooyesh\Wallet\interfaces\WalletInterface; +use App\Services\ConfigService; class GiftCardController extends Controller { public function redeem(Request $request) { + if (app(ConfigService::class)->isStore()) { + return $this->storeRedeem($request); + } + $user = auth()->user(); $count = $request->count; $amount = $request->amount; @@ -170,6 +175,203 @@ class GiftCardController extends Controller ]); } + public function useDiscount(Request $request) + { + if (! app(ConfigService::class)->isStore()) { + return response()->json(['message' => 'این قابلیت فقط برای فروشگاه فعال است'], 403); + } + + $result = $this->applyDiscount((string) $request->input('code'), auth('customer')->id()); + + if (! empty($result['message'])) { + return response()->json(['message' => $result['message']], 400); + } + + return response()->json(['amount' => $result['amount']]); + } + + public function validateDiscount(Request $request) + { + if (! app(ConfigService::class)->isStore()) { + return response()->json(['message' => 'این قابلیت فقط برای فروشگاه فعال است'], 403); + } + + $giftcode = $this->verifyDiscount((string) $request->input('code')); + if (! empty($giftcode['message'])) { + return response()->json(['message' => $giftcode['message']], 400); + } + + return response()->json(['giftcard' => $giftcode], 200); + } + + private function storeRedeem(Request $request) + { + $user = auth()->user(); + $count = $request->count; + $amount = $request->amount; + if (! $user) { + throw new UnprocessableEntityHttpException('auth failed!'); + } + + if ((! is_numeric($count) || $count < 0) || (! is_numeric($amount) || $amount <= 0)) { + return response()->json(['message' => 'تعداد کد را چک کنید!'], 400); + } + + if (isset($request->code) && GiftCardCodes::where('code', $request->code)->where('unit', $request->unit)->exists()) { + return response()->json(['message' => 'کد تکراری میباشد!'], 400); + } + + $codes = []; + $unitAmount = $request->unit == 3 ? $amount / 100 : $amount; + + if ($request->use_once) { + $gift = GiftCard::create([ + 'use_once' => $request->use_once ? 1 : 0, + 'count' => $count, + 'amount' => $unitAmount, + 'name' => $request->name, + 'total' => $request->unit == 3 ? null : $count * $amount, + 'sts' => 1, + 'unit' => $request->unit, + 'expiry_date' => $request->expiry_date, + 'created_at' => now(), + 'updated_at' => now(), + 'description' => $request->description, + ]); + + for ($i = 0; $i < $count; $i++) { + do { + $unique_code = strtoupper(bin2hex(random_bytes(4))); + } while (GiftCardCodes::where('code', $unique_code)->exists()); + + $codes[] = [ + 'giftcard_id' => $gift->id, + 'use_once' => $request->use_once ? 1 : 0, + 'code' => $unique_code, + 'sts' => 1, + 'unit' => $request->unit, + 'amount' => $unitAmount, + 'expiry_date' => $request->expiry_date, + 'created_at' => now(), + ]; + } + GiftCardCodes::insert($codes); + } else { + do { + $unique_code = strtoupper(bin2hex(random_bytes(4))); + } while (GiftCardCodes::where('code', $unique_code)->exists()); + + $gift = GiftCard::create([ + 'use_once' => $request->use_once ? 1 : 0, + 'count' => $count, + 'unique_code' => ! empty($request->code) ? $request->code : $unique_code, + 'amount' => $unitAmount, + 'name' => $request->name, + 'total' => $request->unit == 3 ? null : $count * $amount, + 'sts' => 1, + 'unit' => $request->unit, + 'expiry_date' => $request->expiry_date, + 'created_at' => now(), + 'updated_at' => now(), + 'description' => $request->description, + ]); + + GiftCardCodes::insert([ + 'giftcard_id' => $gift->id, + 'use_once' => $request->use_once ? 1 : 0, + 'code' => ! empty($request->code) ? $request->code : $unique_code, + 'sts' => 1, + 'unit' => $request->unit, + 'amount' => $unitAmount, + 'expiry_date' => $request->expiry_date, + 'created_at' => now(), + ]); + } + + return response()->json([ + 'order' => $gift, + 'codes' => $gift->giftcardcodes, + 'total' => $count * $amount, + ]); + } + + private function applyDiscount(string $code, $customerId): array + { + $giftcode = $this->verifyDiscount($code); + if (! empty($giftcode['message'])) { + return ['message' => $giftcode['message']]; + } + + $giftcode = GiftCardCodes::where('code', $code)->first(); + $gift = GiftCard::find($giftcode->giftcard_id); + + $idsArray = json_decode($giftcode->assigned_to, true); + if (! is_array($idsArray)) { + $idsArray = []; + } + + $idsArray[] = $customerId; + if ($gift->use_once == 1) { + $giftcode->sts = 2; + } + $giftcode->assigned_to = json_encode($idsArray); + $giftcode->save(); + + $gift->used_count += 1; + if ($gift->used_count + 1 > $gift->count) { + $gift->sts = 2; + } + $gift->save(); + + return ['amount' => $giftcode->amount]; + } + + private function verifyDiscount(string $code) + { + $giftcode = GiftCardCodes::where('code', $code)->first(); + + if (! $giftcode) { + return ['message' => 'کد تخفیف یافت نشد!']; + } + + $gift = GiftCard::find($giftcode->giftcard_id); + $customer_id = auth('customer')->id(); + + if ($gift->unit !== 3 || $giftcode->unit !== 3) { + return ['message' => 'کد تخفیف صحیح نمیباشد!']; + } + + if ($gift->use_once === 0) { + $stored_ids = json_decode($giftcode->assigned_to, true); + if (is_array($stored_ids) && in_array($customer_id, $stored_ids)) { + return ['message' => 'شما قبلا از تخفیف خود استفاده کرده اید!']; + } + } elseif ($gift->use_once === 1) { + if (GiftCardCodes::where('giftcard_id', $gift->id)->where('assigned_to', '['.auth('customer')->id().']')->exists()) { + return ['message' => 'شما قبلا از تخفیف خود استفاده کرده اید!']; + } + } + + if ($gift->expiry_date <= now() || $gift->sts === 3) { + $gift->sts = 3; + $giftcode->sts = 3; + $giftcode->save(); + $gift->save(); + + return ['message' => 'کد تخفیف منقضی شده است!']; + } + + if ($giftcode->sts === 2) { + return ['message' => 'کد تخفیف قبلا استفاده شده است!']; + } + + if ($gift->used_count + 1 > $gift->count) { + return ['message' => 'تعداد استفاده کد تخفیف به پایان رسیده است!']; + } + + return $giftcode; + } + public function table(Request $request) { $user = auth()->user(); diff --git a/app/Http/Controllers/Admin/ProductController.php b/app/Http/Controllers/Admin/ProductController.php index e59c63f..7777f05 100644 --- a/app/Http/Controllers/Admin/ProductController.php +++ b/app/Http/Controllers/Admin/ProductController.php @@ -180,6 +180,26 @@ class ProductController extends SuperController return response()->json($products); } + public function ProductById($id) + { + $this->getPrice(); + $this->auto_close_open(); + $product = Product::with(['file']) + ->where('id', $id) + ->first(); + + if ($product) { + $product->similar = Product::with(['file']) + ->where('group_type', $product->group_type) + ->where('id', '!=', $id) + ->get(); + } else { + return response()->json(false); + } + + return response()->json($product); + } + public function getPrice() { app(\App\Services\ProductPriceSyncService::class)->syncAll(true); diff --git a/app/Http/Controllers/Customer/CartController.php b/app/Http/Controllers/Customer/CartController.php new file mode 100644 index 0000000..f4295cf --- /dev/null +++ b/app/Http/Controllers/Customer/CartController.php @@ -0,0 +1,328 @@ +header('X-Cart-Session'); + + if (!$sessionId) { + $sessionId = (string) Str::uuid(); + } + + $cart = Cart::firstOrCreate( + [ + 'session_id' => $sessionId, + 'sts' => 1, + ] + ); + + return [$cart, $sessionId]; + } + + public function getCart(Request $request) + { + [$cart, $sessionId] = $this->getOrCreateCart($request); + + return response()->json([ + 'cart' => $cart->load('items'), + 'session_id' => $sessionId + ]); + } + + public function addItem(Request $request) + { + [$cart, $sessionId] = $this->getOrCreateCart($request); + $product = Product::select('id', 'title', 'group_type')->where('id', $request->product_id)->first(); + $item = CartItem::where('cart_id', $cart->id) + ->where('product_id', $request->product_id) + ->first(); + + if ($item) { + $item->increment('quantity'); + } else { + CartItem::create([ + 'cart_id' => $cart->id, + 'product_id' => $product->id, + 'title' => $product->title, + 'group_type' => $product->group_type, + 'quantity' => 1, + ]); + } + + return response()->json([ + 'message' => 'محصول اضافه شد.', + 'session_id' => $sessionId + ]); + } + + public function removeItem(Request $request) + { + $request->validate([ + 'product_id' => 'required|integer', + ]); + + $sessionId = $request->header('X-Cart-Session'); + + if (!$sessionId) { + return response()->json([ + 'message' => 'Cart session not found' + ], 400); + } + + $cart = Cart::where('session_id', $sessionId) + ->where('sts', 'open') + ->first(); + + if (!$cart) { + return response()->json([ + 'message' => 'Active cart not found' + ], 404); + } + + $item = CartItem::where('cart_id', $cart->id) + ->where('product_id', $request->product_id) + ->first(); + + if (!$item) { + return response()->json([ + 'message' => 'Item not found in cart' + ], 404); + } + + if ($item->quantity > 1) { + $item->decrement('quantity'); + } else { + $item->delete(); + } + + return response()->json([ + 'message' => 'Item updated successfully' + ]); + } + + public function checkout(Request $request) + { +// return $request; + + $data = $request->json()->all(); + $user= auth()->user(); + if ($user->is_legal == 0 || !$user) { + return response()->json(['massage' => 'شما باید اول خود را احراز هویت کنید'], 422); + + } + +// $data->validate([ +// 'session_id' => 'required' +// ]); +//dd($data['products']); + if(isset($data['gateway']) && $data['gateway'] !== 'wallet'){ + return response()->json(['massage' => "Under construction👷🏻"], 501); + } + if( isset($data['session_id']) && ($data['session_id'] !== '' || $data['session_id'] !== null)){ + $cart = Cart::where('session_id', $data['session_id']) + ->where('sts', 1) + ->first()->load('items'); + if(!$cart){ + return response()->json(['message' => 'سبد خرید پیدا نشد!'], 404); + } + + // اتصال سبد به کاربر لاگین شده + $cart->update([ + 'customer_id' => auth('customer')->id(), + // 'sts' => 2, + ]); + } else{ + $items = []; + + [$cart, $sessionId] = $this->getOrCreateCart($request); + + $cart->customer_id = auth('customer')->id(); + $cart->save(); + + $productIds = collect($data) + ->pluck('product_id') + ->unique() + ->values(); + + $products = Product::select('id', 'title', 'group_type', 'inventory', 'amount', 'percent_fee_buy', 'cash_fee_buy', 'price_profit') + ->whereIn('id', $productIds) + ->get() + ->keyBy('id'); + + $numbers = collect($data) + ->mapWithKeys(function ($item) { + return [ + $item['product_id'] => $item['number'] ?? 1 + ]; + }); + foreach ($products as $product) { + if(($product->inventory - $numbers[$product->id]) < 0){ + return response()->json(['message' => "موجودی محصول {$product->title} کافی نیست!"], 422); + } + $items[] = [ + 'cart_id' => $cart->id, + 'product_id' => $product->id, + 'title' => $product->title, + 'group_type' => $product->group_type, + 'quantity' => $numbers[$product->id] ?? 1, + 'created_at'=> now(), + 'updated_at'=> now(), + ]; + } + + CartItem::insert($items); + + $cart = Cart::where('session_id', $cart->session_id) + ->first() + ->load('items'); + } + + $wallet = Wallet::where('owner',auth('customer')->id())->whereNull('fund_id')->whereNull('product_id') + ->first(); + + $priceRow = Price::latest()->first(); + $goldPrice = $priceRow->price; + $data['price'] = $goldPrice; + $data['price_id'] = $priceRow->id; + $data['price_original'] = $goldPrice; + + $data['customer_id'] = auth('customer')->id(); + + $total_price = 0; + $total_amount = 0; + $product_fees = 0; + $wallet_interface = new WalletInterface($data['customer_id'], auth('customer')->user()->type); + + // قیمت‌گیری لحظه‌ای + $data['amount'] = 0; + $data['service_charge_percentage'] = 0; + $data['fee'] = 0; + foreach ($cart->items as $item) { + + $product = Product::find($item->product_id); + + // کارمزد درصدی هر واحد از محصول + $feeAmount = $product->percent_fee_buy * $product->amount; + //وزن نهایی هر واحد از محصول با احتساب کارمزد + $finalAmount = $product->amount + $feeAmount; + //وزن کل محصول با احتساب تعداد و کارمزد + $total_amount += $product->amount * $item->quantity; + //محاسبه مجموع وزن سبد با احتساب کارمزد + $data['amount'] += $finalAmount * $item->quantity; + //محاسبه مجموع درصد کارمزد سبد با احتساب تعداد + $data['service_charge_percentage'] += $product->percent_fee_buy * $item->quantity; + //محاسبه مجموع کارمزد ثابت سبد با احتساب تعداد + $data['fee'] += $product->cash_fee_buy * $item->quantity; + // قیمت نهایی هر گرم + $priceWithFee = $goldPrice + $data['fee']; + //محاسبه مجموع کارمزد ثابت سبد با احتساب تعداد + $product_fees += $product->cash_fee_buy; + // قیمت آیتم + $itemTotalPrice = $finalAmount * $priceWithFee; + + // قیمت کل این آیتم با احتساب تعداد + $itemTotalPrice = $item->quantity * $itemTotalPrice; + //مبلغ سبد خرید با احتساب این آیتم + $total_price += $itemTotalPrice; + + // ذخیره شفاف برای گزارش و فاکتور + $item->update([ + 'price' => $itemTotalPrice, + 'gold_price' => $goldPrice + ]); + } + //قیمت هر گرم با احتساب کارمزد ثابت + $total_price_with_fees = $goldPrice + $product_fees; + //مجموع کارمز ثابت و متغیر در سبد خرید + $data['total_fee'] = $data['fee'] + ($total_price_with_fees * ($data['service_charge_percentage'] * $total_amount)); + //قیمت هر گرم بدون احتساب کارمزدها + $data['total_price_original'] = $total_amount * $goldPrice; + //کارمزد طلایی + $data['service_charge'] = $data['service_charge_percentage'] * $total_amount; + //کارمزد ریالی + $data['service_charge_price'] = $data['service_charge'] * $data['price_original']; + //قیمت کل برای مشتری + $data['total_price'] = $total_price; + //مقدار قابل پرداخت + $data['payment_amount'] = $data['total_price']; + if(!empty($data[0]['discount_code'])){ + $discount = new GiftCardController(); + $discount = $discount->useDiscount($data[0]['discount_code'], $data['customer_id']); + $data['discount'] = true; + if(!empty($discount['amount'])){ + $data['payment_amount'] = $data['total_price'] = $data['total_price'] - ($data['total_price'] * (float)$discount['amount']); + } + } + $data['cart_id'] = (int)$cart->id; + $data['sts'] = 1; + + if ($wallet->cash < $data['total_price']){ + throw new UnprocessableEntityHttpException('موجودی کیف پول شما کافی نیست.'); + } + $data['direction'] = 1; // خرید + $data['pay_at'] = now(); + $order = Order::create($data); + $cart->order_id = $order->id; + $cart->save(); + $tr = new TransactionInterface($wallet_interface, $_inp = [ + "cash" => $data['payment_amount'], + 'expire_at' => now(), + 'active' => true, + 'order_id' => $order->id, + 'start_at' => now(), + 'title' => "سبد خرید" + ], 12, false, false); + foreach ($cart->items as $item) { + $wallet_interface_product = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type, null, $item->product_id); + $wallet_interface_product->wallet->gold = intval($wallet_interface_product->wallet->gold); + $wallet_interface_product->wallet->save(); + new TransactionInterface($wallet_interface_product, [ + "gold" => $item->quantity, + "product_id" => $item->product_id, + 'expire_at' => now(), + 'active' => true, + 'order_id' => $order->id, + 'start_at' => now(), + ], 1, true, false); + + } + + $order->sts = 2; // پرداخت شده +// $order->direction = 3; // سبد خرید + $order->payment_sts = 4; // وضعیت پرداخت شده + $order->save(); + + foreach ($cart->items as $item) { + Product::where('id', $item->product_id)->decrement('inventory', $item->quantity); + + // $product = Product::find($item->product_id); + // $product->decrement('inventory', $item->quantity); + } + + return response()->json([ + 'message' => 'true', + ]); + } +} diff --git a/app/Http/Controllers/Customer/havaleController.php b/app/Http/Controllers/Customer/havaleController.php new file mode 100644 index 0000000..e3ff9d6 --- /dev/null +++ b/app/Http/Controllers/Customer/havaleController.php @@ -0,0 +1,185 @@ +user(); + $sender = Customer::find(auth('customer')->id()); + $sender_wallet = new WalletInterface(auth('customer')->id(), 2); +// dd($sender_wallet); +// dump($sender_wallet->wallet->gold); + + if ($request->amount > $sender_wallet->wallet->gold) { + return response()->json(['message' => 'موجودی حساب کافی نمی باشد!'], 422); + } + $receiver = Customer::where('virtual_card_number', $request->destination)->first(); +// dd($receiver); + if (!$receiver) { + return response()->json(['message' => "کارت مقصد معتبر نمی باشد!"], 422); + } + + +// try { +// DB::transaction(function () use ($sender_wallet, $receiver, $request) { +// +// new TransactionInterface($sender_wallet, [ +// "gold" => $request->amount, +// 'expire_at' => now(), +// 'active' => true, +// 'start_at' => now(), +// ], 1, false); +// +// $receiver_wallet = new WalletInterface($receiver->id, 2); +// dd($receiver_wallet); +// new TransactionInterface($receiver_wallet, [ +// "gold" => $request->amount, +// 'expire_at' => now(), +// 'active' => true, +// 'start_at' => now(), +// ], 1, true); +// +// }); +// +// return response()->json(['message' => 'حواله با موفقیت انجام شد!'], 200); +// +// } catch (\Exception $e) { +// // در صورت بروز خطا، تمام عملیات رول‌بک می‌شود +// return response()->json([ +// 'message' => 'خطا در انجام تراکنش!', +// 'error' => $e->getMessage() +// ], 500); +// } +// dd($receiver->name,$sender->name); + + new TransactionInterface($sender_wallet, [ + "title" => "حواله", + "gold" => $request->amount, + 'expire_at' => now(), + 'active' => true, + 'start_at' => now(), + 'note' => " حواله از $sender->name به $receiver->name به مقدار $request->amount گرم", + ], 10, false); +// dump($sender_wallet->wallet->gold); + $receiverWallet = new WalletInterface($receiver->id, 2); +// dump($reciverWallet->wallet->gold); + new TransactionInterface($receiverWallet, [ + "title" => "حواله", + "gold" => $request->amount, + 'expire_at' => now(), + 'active' => true, + 'start_at' => now(), + 'note' => " حواله از $sender->name به $receiver->name به مقدار $request->amount گرم", + ], 10, true); +// dump($reciverWallet->wallet->gold); + return "تراکنش موفق"; + + + } + + public function virtualCardValidate(Request $request) + { + $input = str_replace(' ', '', $request->input('cardNumber')); + if(strlen($input) !== 16 && strlen($input) !== 11) + return response()->json(['message' => 'مقدار وارد شده معتبر نمی باشد!'], 422); + + if (strlen($input) == 16) { + $input = implode('-', str_split($input, 4)); + } + + if (auth('customer')->user()->virtual_card_number == $input || + auth('customer')->user()->mobile == $input){ + return response()->json(['message' => 'شماره کارت مبدا و مقصد یکسان است!'], 422); + } + + $data = Customer::where('virtual_card_number', $input) + ->orwhere('mobile', $input) + ->select('name', 'virtual_card_number') + ->first(); + if($data) + return $data; + + return response()->json(['message' => 'مقصد وجود ندارد!'], 422); + + + + + + + + +// if (strlen(str_replace(' ', '', $request->input('cardNumber'))) == 19) { +// return $data = Customer:: +// where('virtual_card_number', str_replace(' ', '', $request->input('cardNumber'))) +// ->select('name', 'virtual_card_number') +// ->first(); +// } elseif (strlen(str_replace(' ', '', $request->input('cardNumber'))) == 16) { +// $normalized = implode('-', str_split(str_replace(' ', '', $request->input('cardNumber')), 4)); +// $data = Customer::where('virtual_card_number', $normalized) +// ->select('name', 'virtual_card_number') +// ->first(); +// return $data ?? response()->json([1], 422); +// } elseif (strlen(str_replace(' ', '', $request->input('cardNumber'))) == 11){ +// return $data = Customer:: +// where('mobile', str_replace(' ', '', $request->input('cardNumber'))) +// ->select('name', 'virtual_card_number') +// ->first(); +// }else { +// return response()->json(['message' => 'شماره کارت باید 16 رقم باشد!'], 422); +// } + } + + public function havaleList(Request $request){ + $id = $request->input('id'); + $havale = DB::table('transactions') + ->select('gold', 'note', 'created_at', 'unit', 'title', 'customer_id') + ->where('title', 'حواله') + ->where('customer_id', $id) + ->get(); + return $havale; + + } + +// public function ztest(Request $request) +// { +// $user = Customer::findOrFail($request->id); +//// $user = Customer::find(auth('customer')->id()); +// if($user) { +// $response = Http::withHeaders([ +// 'Content-Type' => 'application/json', +// 'Accept' => 'application/json', +// ])->post('https://shop.liman.gold/zarinpal', [ +// 'amount' => $request->amount, +// 'user_name' => $user->name, +// 'user_id' => $user->id, +// 'currency' => 'IRR', +// 'user' => [ +// 'name' => $user->name, +// 'phone' => $user->mobile, +// ], +// 'title' => env('APP_NAME'), +// 'return_url' => 'https://ghatreh.gold/zarinpal', +// ]); +// +//// دریافت جواب به صورت آرایه +// $result = $response->json(); +// return redirect($result['pay_link']); +// } +// return "user not found"; +////// یا نمایش کامل پاسخ +//// dd($result); +// +// } +} diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index a93debd..48f3c66 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -66,5 +66,6 @@ class Kernel extends HttpKernel 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'validation'=>ValidationMiddleware::class, 'request.validation' => \App\Http\Middleware\ValidateRequests::class, + 'LogRequests' => \App\Http\Middleware\LogRequests::class, ]; } diff --git a/app/Http/Middleware/LogRequests.php b/app/Http/Middleware/LogRequests.php new file mode 100644 index 0000000..50820b8 --- /dev/null +++ b/app/Http/Middleware/LogRequests.php @@ -0,0 +1,66 @@ +ip = $request->ip(); + $Pargar->m = $request->route()?->getName() ?? 'not_found'; +//get action name from controller + if ($route = $request->route()) { + // تلاش برای گرفتن نام اکشن (کنترلر و متد) + $Pargar->function_name = $route->getActionName(); + } else { + $Pargar->function_name = 'not_found'; + } + + + $Pargar->finance_data = json_encode($request->all(), JSON_UNESCAPED_UNICODE); + $Pargar->finance_head = json_encode($request->headers->all(), JSON_UNESCAPED_UNICODE); + $Pargar->url = $request->fullUrl(); + $Pargar->method = $request->method(); + $Pargar->save(); + } catch (\Throwable $e) { + $Pargar = null; // برای اطمینان از عدم خطا در ادامه + } + + // اجرای درخواست اصلی + $response = $next($request); + + try { + + if ($Pargar) { +// if ($route = $request->route()) { +// try { +// $Pargar->m = $route +// ? $route->getActionName() . ' (' . (new \ReflectionClass($route->getController()))->getFileName() . ')' +// : 'unknown'; +// } catch (\Throwable $e) { +// $Pargar->m = 'unknown'; +// } +// +// } + $Pargar->response = $response->getContent(); + $Pargar->ms = round((microtime(true) - $start) * 1000, 2); // زمان در میلی‌ثانیه + $Pargar->save(); + } + } catch (\Throwable $e) {} + + return $response; + } +} diff --git a/app/Jobs/LogRouteCustomerJob.php b/app/Jobs/LogRouteCustomerJob.php new file mode 100644 index 0000000..1f52607 --- /dev/null +++ b/app/Jobs/LogRouteCustomerJob.php @@ -0,0 +1,70 @@ +customer = $customer; + $this->route = $route; + } + + public function handle() + { + $now = now(); + + $this->customer->last_using_api = $now; + $this->customer->save(); + + $parts = explode(' ', $this->route); + if (count($parts) < 2) { + return; + } + + $method = trim($parts[0]); + $path = trim($parts[1]); + + $routeInfo = RouteInfo::where('method', $method) + ->where('route', $path) + ->first(); + + $lastlog = DB::table('customer_route_logs') + ->where('customer_id', $this->customer->id) + ->where('route', $this->route) + ->where('last_using_api', '<', $now) + ->orderBy('last_using_api', 'desc') + ->first(); + + if ($lastlog) { + $diff = Carbon::parse($lastlog->last_using_api)->diff($now); + $timeSpentFormatted = sprintf('%02d:%02d:%02d', $diff->h + ($diff->d * 24), $diff->i, $diff->s); + + DB::table('customer_route_logs') + ->where('id', $lastlog->id) + ->update(['time_spent' => $timeSpentFormatted]); + } + + DB::table('customer_route_logs')->insert([ + 'customer_id' => $this->customer->id, + 'route' => $this->route, + 'route_info_id' => $routeInfo ? $routeInfo->id : null, + 'last_using_api' => $now, + 'time_spent' => null, + ]); + } +} diff --git a/app/Models/Cart.php b/app/Models/Cart.php new file mode 100644 index 0000000..5c087a0 --- /dev/null +++ b/app/Models/Cart.php @@ -0,0 +1,37 @@ +'در انتظار ثبت', + 2=>'در انتظار پرداخت', + 3=>'پرداخت شده', + 4=>'لغو شده', + ]; + + public function items() + { + return $this->hasMany(CartItem::class, 'cart_id'); + } + + protected function serializeDate(\DateTimeInterface $date) + { + return $date->format('Y-m-d H:i:s'); + } + +} diff --git a/app/Models/CartItem.php b/app/Models/CartItem.php new file mode 100644 index 0000000..3d571f5 --- /dev/null +++ b/app/Models/CartItem.php @@ -0,0 +1,33 @@ +belongsTo(Cart::class); + } + + protected function serializeDate(\DateTimeInterface $date) + { + return $date->format('Y-m-d H:i:s'); + } + +} diff --git a/app/Models/Category.php b/app/Models/Category.php new file mode 100644 index 0000000..1485247 --- /dev/null +++ b/app/Models/Category.php @@ -0,0 +1,22 @@ + 'boolean', + ]; +} diff --git a/app/Models/GiftCard.php b/app/Models/GiftCard.php index 03635e2..f1026b3 100644 --- a/app/Models/GiftCard.php +++ b/app/Models/GiftCard.php @@ -14,6 +14,7 @@ class GiftCard extends Model protected $fillable = [ 'customer_id', + 'use_once', 'count', 'amount', 'total', diff --git a/app/Models/Pargar.php b/app/Models/Pargar.php new file mode 100644 index 0000000..103a0a3 --- /dev/null +++ b/app/Models/Pargar.php @@ -0,0 +1,28 @@ + 'json', + 'finance_head' => 'json', + 'finance_data' => 'json', + 'response' => 'json', + ]; +} diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index f541a46..433897a 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -7,6 +7,7 @@ use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvi use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route; +use App\Services\ConfigService; class RouteServiceProvider extends ServiceProvider { @@ -55,6 +56,13 @@ class RouteServiceProvider extends ServiceProvider ->namespace($this->namespace) ->group(base_path('routes/customer.php')); + if (app(ConfigService::class)->isStore()) { + Route::prefix('pargar') + ->middleware('LogRequests') + ->namespace($this->namespace) + ->group(base_path('routes/pargar.php')); + } + Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); diff --git a/app/Services/ConfigService.php b/app/Services/ConfigService.php index 22585fb..40b7ad5 100644 --- a/app/Services/ConfigService.php +++ b/app/Services/ConfigService.php @@ -51,6 +51,12 @@ class ConfigService return filter_var($value, FILTER_VALIDATE_BOOLEAN); } + /** فروشگاهی (قطره / کشکول) — روت‌ها و رفتار store فقط وقتی true باشد فعال می‌شوند */ + public function isStore(): bool + { + return $this->getBool('is_store', false); + } + public function getInt(string $key, int $default = 0): int { $value = $this->get($key, $default); diff --git a/config/price_providers.php b/config/price_providers.php index 399f6e9..bd09228 100644 --- a/config/price_providers.php +++ b/config/price_providers.php @@ -21,6 +21,7 @@ return [ 'register_referral_sms_to_referrer' => false, 'register_referral_bonus_message' => false, 'external_order_api_enabled' => false, + 'is_store' => false, 'node_client_id' => '', 'node_shared_secret' => '', 'profit_gold_api_enabled' => false, diff --git a/database/migrations/2026_06_11_000001_add_store_tables_and_columns.php b/database/migrations/2026_06_11_000001_add_store_tables_and_columns.php new file mode 100644 index 0000000..46fb68e --- /dev/null +++ b/database/migrations/2026_06_11_000001_add_store_tables_and_columns.php @@ -0,0 +1,97 @@ +id(); + $table->string('name'); + $table->boolean('active')->default(true); + $table->timestamp('created_at')->nullable(); + }); + } + + if (! Schema::hasTable('cart')) { + Schema::create('cart', function (Blueprint $table) { + $table->id(); + $table->unsignedBigInteger('customer_id')->nullable(); + $table->unsignedTinyInteger('sts')->default(1); + $table->string('session_id')->nullable()->index(); + $table->timestamps(); + }); + } + + if (! Schema::hasTable('cart_items')) { + Schema::create('cart_items', function (Blueprint $table) { + $table->id(); + $table->unsignedBigInteger('cart_id'); + $table->unsignedBigInteger('product_id')->nullable(); + $table->unsignedInteger('quantity')->default(1); + $table->decimal('price', 15, 2)->nullable(); + $table->string('title')->nullable(); + $table->string('group_type')->nullable(); + $table->decimal('gold_price', 15, 4)->nullable(); + $table->timestamps(); + }); + } + + if (! Schema::hasTable('pargar_reqasts')) { + Schema::create('pargar_reqasts', function (Blueprint $table) { + $table->id(); + $table->string('m')->nullable(); + $table->string('route')->nullable(); + $table->string('ip')->nullable(); + $table->json('data')->nullable(); + $table->json('finance_head')->nullable(); + $table->json('finance_data')->nullable(); + $table->json('response')->nullable(); + $table->string('function_name')->nullable(); + $table->timestamps(); + }); + } + + if (Schema::hasTable('giftcards') && ! Schema::hasColumn('giftcards', 'use_once')) { + Schema::table('giftcards', function (Blueprint $table) { + $table->unsignedTinyInteger('use_once')->default(0)->after('customer_id'); + }); + } + + if (Schema::hasTable('giftcard_codes') && ! Schema::hasColumn('giftcard_codes', 'use_once')) { + Schema::table('giftcard_codes', function (Blueprint $table) { + $table->unsignedTinyInteger('use_once')->default(0)->after('giftcard_id'); + }); + } + + if (Schema::hasTable('giftcard_codes') && Schema::hasColumn('giftcard_codes', 'assigned_to')) { + \Illuminate\Support\Facades\DB::statement( + 'ALTER TABLE `giftcard_codes` MODIFY `assigned_to` TEXT NULL' + ); + } + } + + public function down(): void + { + Schema::dropIfExists('cart_items'); + Schema::dropIfExists('cart'); + Schema::dropIfExists('categories'); + Schema::dropIfExists('pargar_reqasts'); + + if (Schema::hasTable('giftcards') && Schema::hasColumn('giftcards', 'use_once')) { + Schema::table('giftcards', function (Blueprint $table) { + $table->dropColumn('use_once'); + }); + } + + if (Schema::hasTable('giftcard_codes') && Schema::hasColumn('giftcard_codes', 'use_once')) { + Schema::table('giftcard_codes', function (Blueprint $table) { + $table->dropColumn('use_once'); + }); + } + } +}; diff --git a/database/sql/baseline_migrations.sql b/database/sql/baseline_migrations.sql index e4e78ae..fdf6b34 100644 --- a/database/sql/baseline_migrations.sql +++ b/database/sql/baseline_migrations.sql @@ -14,6 +14,7 @@ INSERT INTO `migrations` (`migration`, `batch`) VALUES ('2026_06_06_000003_add_order_limit_columns_to_products_table', 1), ('2026_06_09_000001_add_show_in_assets_to_products_table', 1), ('2026_06_10_000001_add_use_last_price_if_zero_to_products_table', 1), -('2026_06_10_000002_add_type_column_to_settings_table', 1); +('2026_06_10_000002_add_type_column_to_settings_table', 1), +('2026_06_11_000001_add_store_tables_and_columns', 1); SELECT migration, batch FROM migrations ORDER BY migration; diff --git a/database/sql/deploy_settings_const.sql b/database/sql/deploy_settings_const.sql index b884087..b4adff3 100644 --- a/database/sql/deploy_settings_const.sql +++ b/database/sql/deploy_settings_const.sql @@ -179,6 +179,10 @@ INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `de SELECT 'external_order_api_enabled', 'true', 'فعال‌سازی API سفارش خارجی (get_wallet / order)', 1, 1, 'true + node_client_id + node_shared_secret' WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'external_order_api_enabled' LIMIT 1); +INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`) +SELECT 'is_store', 'false', 'حالت فروشگاهی (قطره / کشکول)', 1, 1, 'true = روت‌های سبد خرید، دسته‌بندی، حواله، پرگار، تخفیف', 'switch' +WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'is_store' LIMIT 1); + -- Jibit INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`) SELECT 'jibit_verification', 'true', 'تأیید کارت بانکی با جیبیت', 1, 1, 'true/false — BankAccountController' @@ -429,7 +433,7 @@ UPDATE `settings` SET `type` = 'switch' WHERE `key` IN ( 'has_page_physical_gold', 'has_chat', 'charge_notif', 'group_sms', 'display_montzar', 'montzar_closed', 'montzar_open_buy', 'montzar_open_sell', 'product_update_price_on_list', 'product_auto_close_open_on_list', 'payping_fin_sync_enabled', - 'fee_free', 'external_order_api_enabled' + 'fee_free', 'external_order_api_enabled', 'is_store' ); -- number diff --git a/database/sql/fix_migrations_after_failed_migrate.sql b/database/sql/fix_migrations_after_failed_migrate.sql index 6143e59..07b91ba 100644 --- a/database/sql/fix_migrations_after_failed_migrate.sql +++ b/database/sql/fix_migrations_after_failed_migrate.sql @@ -12,6 +12,7 @@ INSERT INTO `migrations` (`migration`, `batch`) VALUES ('2026_06_06_000003_add_order_limit_columns_to_products_table', 1), ('2026_06_09_000001_add_show_in_assets_to_products_table', 1), ('2026_06_10_000001_add_use_last_price_if_zero_to_products_table', 1), -('2026_06_10_000002_add_type_column_to_settings_table', 1); +('2026_06_10_000002_add_type_column_to_settings_table', 1), +('2026_06_11_000001_add_store_tables_and_columns', 1); SELECT migration, batch FROM migrations ORDER BY migration; diff --git a/routes/admin.php b/routes/admin.php index 03b61a7..fdf869d 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -19,6 +19,8 @@ use App\Http\Controllers\Admin\FileController; use App\Http\Controllers\Site\OfferCodesController; use App\Http\Controllers\Admin\SettingsController; use \App\Http\Controllers\Admin\GiftCardController; +use App\Http\Controllers\Admin\CategoryController; +use App\Services\ConfigService; Route::middleware('auth:user')->group(function (){ @@ -164,5 +166,11 @@ Route::middleware('auth:user')->group(function (){ Route::post('giftcard/generate/', [GiftCardController::class, 'redeem']); Route::post('giftcard/table/', [GiftCardController::class, 'table']); + if (app(ConfigService::class)->isStore()) { + Route::get('categories', [CategoryController::class, 'index']); + Route::post('categories', [CategoryController::class, 'store']); + Route::get('categories/{id}/active/{active}', [CategoryController::class, 'changeActive']); + } + }); }); diff --git a/routes/api.php b/routes/api.php index db1e969..a3934c6 100644 --- a/routes/api.php +++ b/routes/api.php @@ -11,6 +11,8 @@ use App\Models\File; use App\Http\Controllers\Admin\SettingsController; use App\Http\Controllers\Site\RequestsController; use App\Services\ConfigService; +use App\Http\Controllers\Customer\CartController; +use App\Http\Controllers\Admin\CategoryController; /* |-------------------------------------------------------------------------- @@ -44,3 +46,10 @@ if (app(ConfigService::class)->getBool('external_order_api_enabled', false)) { Route::post('order', [RequestsController::class, 'order']); }); } + +if (app(ConfigService::class)->isStore()) { + Route::get('/cart', [CartController::class, 'getCart']); + Route::post('/cart/add', [CartController::class, 'addItem']); + Route::post('/cart/remove', [CartController::class, 'removeItem']); + Route::get('categories', [CategoryController::class, 'clientIndex']); +} diff --git a/routes/customer.php b/routes/customer.php index 8e1fc91..f4e9c03 100644 --- a/routes/customer.php +++ b/routes/customer.php @@ -16,6 +16,8 @@ use App\Http\Controllers\Admin\TahesabController; use App\Http\Controllers\Site\OfferCodesController; use App\Http\Controllers\Admin\GiftCardController; use App\Services\ConfigService; +use App\Http\Controllers\Customer\havaleController; +use App\Http\Controllers\Customer\CartController; //----------gateway-verify @@ -23,6 +25,10 @@ Route::get('/TCharchee ', [paypingController::class, 'TCharchee']); Route::post('/charge_account_verify', [paypingController::class, 'verifyTransation']); Route::post('/charge_account_verify/{id}', [paypingController::class, 'verifyTransationByID']); +if (app(ConfigService::class)->isStore()) { + Route::get('/product/list', [AdminProductController::class, 'listProduct']); + Route::get('/product/list/{id}', [AdminProductController::class, 'ProductById']); +} Route::middleware('auth:customer')->group(function () { Route::middleware('validation')->group(function () { @@ -110,5 +116,14 @@ Route::middleware('auth:customer')->group(function () { //offer code Route::post('offer_code/check_code', [OfferCodesController::class, 'check_code']); + if (app(ConfigService::class)->isStore()) { + Route::post('vc_validate', [havaleController::class, 'virtualCardValidate']); + Route::post('havale', [havaleController::class, 'havale']); + Route::post('havale_list', [havaleController::class, 'havaleList']); + Route::post('/cart/checkout', [CartController::class, 'checkout']); + Route::post('validateDiscount', [GiftCardController::class, 'validateDiscount']); + Route::post('useDiscount', [GiftCardController::class, 'useDiscount']); + } + }); }); diff --git a/routes/pargar.php b/routes/pargar.php new file mode 100644 index 0000000..4cf9885 --- /dev/null +++ b/routes/pargar.php @@ -0,0 +1,344 @@ +take(100)->get()->each(function ($item) { + if (is_string($item->finance_data)) { + $decoded = json_decode($item->finance_data, true); + if (json_last_error() === JSON_ERROR_NONE) { + $item->finance_data = $decoded; // Laravel will re-encode correctly + $item->save(); + } + } + }); + + $pars = Pargar::latest('id')->take(100) + ->select(['id','finance_data','m']) + ->get(); + +// foreach ($pars as $par) { +// if (!empty($par->finance_data['Customers'])) { +// $par->m = 'CUSTOMER'; +// $par->save(); +// $cu = Customer::where("pargar_id", $par->finance_data['Customers'][0]['AccountId'])->first(); +// if (!($cu)) { +// $cu = new Customer(); +// $cu->agent_id = 3137; +// $cu->type = 2; +// } +// $cu->pargar_id = $par->finance_data['Customers'][0]['AccountId']; +// $cu->tahesab_id = $par->finance_data['Customers'][0]['AccountId']; +// $cu->lname = $par->finance_data['Customers'][0]['FullName']; +// $cu->name = $par->finance_data['Customers'][0]['FullName']; +// $cu->mobile = $par->finance_data['Customers'][0]['CellPhone']; +// $cu->save(); +// } +// if (!empty($par->finance_data['accountName']) && !empty($par->finance_data['accountId']) && !empty($par->finance_data['transactions'])) { +// $par->m = 'trans'; +// $par->save(); +// $cu = Customer::where("pargar_id", $par->finance_data['accountId'])->first(); +// if (!($cu)) { +// $cu = new Customer(); +// $cu->agent_id = 3137; +// $cu->type = 2; +// } +// $accountId = $par->finance_data['accountId']; +// foreach ($par->finance_data['transactions'] as $transaction) { +// $docId = $transaction['docId']; +// // Check if docId already exists +// if (PargarDoc::where('docId', $docId)->exists()) { +// continue; // Skip duplicates +// } +// +// // Save new transaction +// PargarDoc::create([ +// 'docId' => $docId, +// 'date' => $transaction['date'], +// 'docType' => $transaction['docType'], +// 'desc' => $transaction['desc'], +// 'goldState' => $transaction['goldState'], +// 'rialState' => $transaction['rialState'], +// 'bedGold' => $transaction['bedGold'], +// 'besGold' => $transaction['besGold'], +// 'bedRial' => $transaction['bedRial'], +// 'besRial' => $transaction['besRial'], +// 'remainGold' => $transaction['remainGold'], +// 'remainRial' => $transaction['remainRial'], +// 'accountId' => $accountId, +// ]); +// } +// $cu->name = $par->finance_data['accountName']; +// $cu->fname = $par->finance_data['accountName']; +// +// $cu->finance_data = ($par->finance_data['transactions']);; +// $cu->mobile = $par->finance_data['accountId']; +// $cu->pargar_id = $par->finance_data['accountId']; +// $cu->tahesab_id = $par->finance_data['accountId']; +// $cu->save(); +// } +// if (!empty($par->finance_data['GoldInv']) && !empty($par->finance_data['RialInv'])) { +// $par->m = 'MANDEH'; +// $par->save(); +// $cu = Customer::where("pargar_id", $par->finance_data['AccountId'])->first(); +// if (!($cu)) { +// $par->m = 'MANDEHnoC'; +// $par->save(); +// continue; +//// $cu = new Customer(); +// } +// $cu->pargar_id = $par->finance_data['AccountId']; +// $cu->tahesab_id = $par->finance_data['AccountId']; +// $cu->gold_balance = $par->finance_data['GoldInv']; +// $cu->rial_balance = $par->finance_data['RialInv']; +// $cu->save(); +// } +// } +} +Route::post('/login', function (Request $request) { + /* + * accounting@09131523432.com + hJNFTV + */ + if ($request->password !== 'mont' && $request->password !== 'Abc123' ) { + return response()->json([ + 'success' => false, + 'data' => [], + 'message' => 'Invalid credentials!' + ]); + } + finalizeProcessing(); + return response()->json([ + 'success' => true, + 'data' => ['token' => base64_encode(Str::random(40))], + 'data' => ['token' => 'wQ12e245d5%rdpb78oBh31Aos*bIdQemiUeeq9e9G!oey23SMXp40Ew2fodjx9J5buKNW0M4@nYMr1PR6d0KtuqhLQlx*K$'], + 'message' => 'You are logged in successfully.' + ]); +}); +Route::post('/customers', function (Request $request) { + $data = $request->all(); + if (!empty($data['Customers'])) { + $cu = Customer::where("finance_code", $data['Customers'][0]['AccountId'])->first(); + $message ="با موفقیت ویرایش شد."; + + if (!($cu)) { + $cu = new Customer(); + $cu->finance_code = 3137; + $cu->referral_to_id = 'ghatre'; + $message ="با موفقیت ایجاد شد."; + } + do { + $referral = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, 4); + } while (Customer::where('referral_id', $referral)->exists()); + $data['referral_id'] = $referral; + + do { + $vcn = $this->Config('default_vc_number') . rand(10, 99) . '-' . rand(1000, 9999) . '-' . rand(1000, 9999); + } while (Customer::where('virtual_card_number', $vcn)->exists()); + $data['virtual_card_number'] = $vcn; + + $cu->lname = $data['Customers'][0]['FullName']; + $cu->name = $data['Customers'][0]['FullName']; + $cu->mobile = $data['Customers'][0]['CellPhone']; + $cu->save(); + } + return response()->json([ + 'state' => 'true', + 'msg' =>$cu->finance_code.":" . $cu->name.$message, + 'result' => 'OK' + ]); +}); +Route::get('/GetCustomers', function (Request $request) { + $customers = Customer::/*where('finance_is_saved', 0)->*/whereNull('finance_code') + ->limit(100) + ->get(['id', 'fname as name', 'lname as family', 'mobile']); + return response()->json([ + 'state' => 'true', + 'data' => $customers, + 'msg' =>'1', + 'result' => 'OK' + ]); + +}); +Route::post('/CustomerConfirm', function (Request $request) { + $customers = $request->input('customers', []); + + + foreach ($customers as $customer) { + $customerRecord = Customer::find($customer['customer_id']); + if ($customerRecord) { + $customerRecord->finance_code = (int)($customer['accounting_id'] ?? 0); + $customerRecord->save(); + } + } + return response()->json([ + 'state' => 'true', + 'data' => $customers, + 'msg' =>'1', + 'result' => 'OK' + ]); +}); + +Route::post('/orders', function (Request $request) { + $OrderIds = $request->input('OrderIds', []); + + try { + foreach ($OrderIds as $orderId) { + Order::where('id', $orderId)->update(['finance_code' => $orderId]); + } + }catch (\Exception $e){ + return $e->getMessage(); + } + + + return response()->json([ + 'state' => true, + 'msg' => 'ذخیره شد', + 'result' => 'OK', + 'duplicated' => [], + 'documents' => [] + ]); +}); + + +Route::get( '/orders', function (Request $request) { + $data = $request->all(); + + $orders = Order::where('sts', 2)->whereNull('finance_code')->limit(100)->get(); + $orders_new = $orders->map(function ($order) { + $customer = Customer::find((int)($order->customer_id ?? 0)); + return [ + 'OrderId' => (string)$order->id, + 'OrderType' => $order->direction == 1 ? 0 : 1, + 'PriceType' => 1, + 'CustomerAccountId' => $customer->finance_code ?? 4, + 'ItemId' => 11, + 'itemName' => 'ابشده', + 'OrderDate' => $order->orders + ? Jalalian::fromCarbon($order->orders)->format('Y/m/d-H:i:s') + : Jalalian::fromCarbon($order->created_at)->format('Y/m/d-H:i:s'), + 'Fee' => $order->price ?? 0, + 'Count' => 0, + 'Weight' => $order->amount ?? 0, + 'Price' => $order->total_price, + 'Carat' => 750, + 'Description' => $order->description ?? '', + ]; + }); + + return response()->json([ + 'state' => 'true', + 'msg' => '', + 'data' => ($orders_new), + 'result' => 'OK', + 'duplicated' => [], + 'documents' => [] + ]); +}); +Route::post('/pdf', function (Request $request) { + + $data = $request->all(); + $head = $request->headers->all(); + $Pargar = new Pargar(); + $Pargar->ip = $request->ip(); // Gets the client IP address + $Pargar->m = 'pdf'; // Gets the client IP address + $Pargar->finance_data = json_encode($data); // Storing request data as JSON + $Pargar->finance_head = json_encode($head); // Storing headers as JSON + $Pargar->save(); // Don't forget to save the model + + Log::info('📋 هدرهای پیدی اف :', $request->headers->all()); + + // 📦 لاگ بدنه‌ی درخواست (Body) + $data = $request->all(); + Log::info('📦 محتوای درخواست ( پیدی اف ):', $data); + + $key = 'wQ12e245d5%rdpb78oBh31Aos*bIdQemiUeeq9e9G!oey23SMXp40Ew2fodjx9J5buKNW0M4@nYMr1PR6d0KtuqhLQlx*K$'; + $auth = $request->header('pargar') ?? $request->header('Authorization'); + if ($auth !== $key && $auth !== 'Bearer ' . $key) { + return response()->json(['auth needed'], 401); + } + finalizeProcessing(); + return response()->json([ + 'state' => 'true', + 'msg' => 'PDF uploaded successfully', +// 'data' => ['fileName' => $fileName], + 'result' => 'OK' + ]); +}); +Route::post('/mande', function (Request $request) { + $data = $request->all(); + + if (!$cu = Customer::where("finance_code",$data['AccountId'])->first()) { + } + if ( $wallet = $cu->wallet->where('fund_id', null)->first()){ + $goldInv = isset($data['GoldInv']) ? ((float)str_replace('/', '.', $data['GoldInv'])) : 0; + $RialInv = isset($data['RialInv']) ? ((float)str_replace('/', '.', $data['RialInv'])) : 0; + $goldDiff = $goldInv - $wallet->gold ; + $rialInvDiff = $RialInv - $wallet->cash ; + }else{ + $goldDiff = isset($data['GoldInv']) ? ((float)str_replace('/', '.', $data['GoldInv'])) : 0; + $rialInvDiff = isset($data['RialInv']) ? ((float)str_replace('/', '.', $data['RialInv'])) : 0; + } + + if (abs($goldDiff) >= 0.01 || abs($rialInvDiff) >= 1) { + $wallet_interface = new WalletInterface($cu->id, 2); + new TransactionInterface($wallet_interface, [ + "cash" => $rialInvDiff, + "gold" =>$goldDiff, + 'expire_at' => now(), + 'active' => true, + 'start_at' => now(), + ], 22,$goldDiff> 0, $rialInvDiff > 0); + } + $cu->gold_balance = $data['GoldInv']; + $cu->rial_balance = $data['RialInv']; + $cu->save(); + return response()->json([ + 'state' => 'true', + 'msg' => "با موفقیت دریافت شد", + 'data' => null, + 'dataWeb' => $cu->id ?? 0, + 'result' => 'OK', + 'duplicated' => [], + 'documents' => [] + ]); +}); +Route::post('/documents', function (Request $request) { + + return response()->json([ + 'state' => true, + 'msg' => "با موفقیت دریافت شد", + 'data' => null, + 'result' => 'OK', + + ]); +}); + +Route::any('{any}', function (Request $request) { +// finalizeProcessing(); + + return response()->json([ + 'state' => false, + 'msg' => "not found", + ]); +})->where('any', '.*'); \ No newline at end of file