Файловый менеджер - Редактировать - /home/vielwcom/www3.vielw.com/app/Bitwise/Mixins.tar
Назад
Cashback/CashbackAccounting.php 0000644 00000015630 15102516125 0012471 0 ustar 00 <?php namespace App\Mixins\Cashback; use App\Models\Accounting; use App\Models\CashbackRule; use App\Models\Order; use App\Models\Product; use App\Models\Webinar; use App\User; use Illuminate\Database\Eloquent\Builder; class CashbackAccounting { private $user; private $cashbackRules; public function __construct($user = null) { if (empty($user)) { $user = auth()->user(); } $this->user = $user; $this->cashbackRules = new CashbackRules($user); } public function rechargeWallet($order) { $amount = 0; if (getFeaturesSettings('cashback_active')) { $totalAmount = $order->total_amount; $rules = $this->cashbackRules->getRules('recharge_wallet'); if (!empty($rules) and count($rules)) { foreach ($rules as $rule) { if (empty($rule->min_amount) or $rule->min_amount <= $totalAmount) { $ruleAmount = $rule->getAmount($totalAmount); if (!empty($rule->max_amount) and $rule->max_amount > $ruleAmount) { $amount += $rule->max_amount; } else { $amount += $ruleAmount; } } } } if ($amount > 0) { $description = 'Cashback for recharge wallet'; $this->setAccounting($order->user_id, $amount, $description); } } } public function setAccountingForOrderItems($orderItems) { if (getFeaturesSettings('cashback_active')) { $applyPerItemRules = []; $totalAmount = $orderItems->sum('total_amount'); foreach ($orderItems as $orderItem) { $itemPrice = $orderItem->amount - $orderItem->discount; $rules = $this->cashbackRules->getRulesByItem($orderItem); if (!empty($rules) and count($rules)) { foreach ($rules as $rule) { $amount = 0; if (empty($rule->min_amount) or $rule->min_amount <= $totalAmount) { if ($rule->amount_type == "fixed_amount") { if ($rule->apply_cashback_per_item) { $amount += $rule->amount; } else { $applyPerItemRules[$rule->id] = $rule; } } else if ($rule->amount_type == "percent") { $ruleAmount = $rule->getAmount($itemPrice); if (!empty($rule->max_amount) and $rule->max_amount < $ruleAmount) { $amount += $rule->max_amount; } else { $amount += $ruleAmount; } } } if ($amount > 0) { $itemId = null; $itemName = null; $description = null; if (!empty($orderItem->webinar_id)) { $itemId = $orderItem->webinar_id; $itemName = 'webinar_id'; $description = 'Cashback For Course'; } elseif (!empty($orderItem->reserve_meeting_id)) { $itemId = $orderItem->reserveMeeting ? $orderItem->reserveMeeting->meeting_time_id : null; $itemName = 'meeting_time_id'; $description = 'Cashback For Meeting'; } elseif (!empty($orderItem->subscribe_id)) { $itemId = $orderItem->subscribe_id; $itemName = 'subscribe_id'; $description = 'Cashback For Subscribe'; } elseif (!empty($orderItem->registration_package_id)) { $itemId = $orderItem->registration_package_id; $itemName = 'registration_package_id'; $description = 'Cashback For registration package'; } elseif (!empty($orderItem->product_id)) { $itemId = $orderItem->product_id; $itemName = 'product_id'; $description = 'Cashback For Product'; } elseif (!empty($orderItem->bundle_id)) { $itemId = $orderItem->bundle_id; $itemName = 'bundle_id'; $description = 'Cashback For Bundle'; } $this->setAccounting($orderItem->user_id, $amount, $description, $orderItem->id, $itemId, $itemName); } } } } if (!empty($applyPerItemRules)) { $amount = 0; foreach ($applyPerItemRules as $applyPerItemRule) { $amount += $applyPerItemRule->amount; } if ($amount > 0) { $description = "Cashback For all cart items"; $this->setAccounting($this->user->id, $amount, $description); } } } } private function setAccounting($userId, $amount, $description, $orderItemId = null, $itemId = null, $itemName = null) { $user = User::query()->find($userId); if (!empty($user) and !$user->disable_cashback) { $insert = [ 'user_id' => $userId, 'order_item_id' => $orderItemId ?? null, 'amount' => $amount, 'is_cashback' => true, 'type_account' => Order::$asset, 'type' => Order::$addiction, 'description' => $description, 'created_at' => time() ]; if (!empty($itemName) and !empty($itemId)) { $insert[$itemName] = $itemId; } // User addiction Accounting::create($insert); // System Deduction $insert['type'] = Order::$deduction; $insert['system'] = true; Accounting::create($insert); $this->sendNotification($user, $amount); } } private function sendNotification($user, $amount) { $notifyOptions = [ '[u.name]' => $user->full_name, '[amount]' => handlePrice($amount), ]; sendNotification('user_get_cashback', $notifyOptions, $user->id); sendNotification('user_get_cashback_notification_for_admin', $notifyOptions, 1); } } Cashback/CashbackRules.php 0000644 00000027545 15102516125 0011501 0 ustar 00 <?php namespace App\Mixins\Cashback; use App\Models\CashbackRule; use App\Models\Product; use App\Models\Webinar; use Illuminate\Database\Eloquent\Builder; class CashbackRules { private $user; public function __construct($user = null) { if (empty($user)) { $user = auth()->user(); } $this->user = $user; } public function getRulesByItem($item) // item => Cart or OrderItem { $targetType = null; $itemId = null; $itemType = null; $categoryId = null; $sellerId = null; if (!empty($item->webinar_id)) { $targetType = 'courses'; $course = $item->webinar; if (!empty($course)) { $itemId = $course->id; $itemType = $course->type; $categoryId = $course->category_id; $sellerId = $course->teacher_id; } } elseif (!empty($item->reserve_meeting_id)) { $targetType = 'meetings'; $meeting = $item->reserveMeeting->meeting; if (!empty($meeting)) { $itemId = null; $itemType = null; $categoryId = null; $sellerId = $meeting->creator_id; } } elseif (!empty($item->subscribe_id)) { $targetType = 'subscription_packages'; $subscribe = $item->subscribe; if (!empty($subscribe)) { $itemId = $subscribe->id; $itemType = null; $categoryId = null; $sellerId = null; } } elseif (!empty($item->registration_package_id)) { $targetType = 'registration_packages'; $registrationPackage = $item->registrationPackage; if (!empty($registrationPackage)) { $itemId = $registrationPackage->id; $itemType = null; $categoryId = null; $sellerId = null; } } elseif (!empty($item->product_id) or !empty($item->product_order_id)) { $targetType = 'store_products'; $product = !empty($item->product_id) ? $item->product : $item->productOrder->product; if (!empty($product)) { $itemId = $product->id; $itemType = $product->type; $categoryId = $product->category_id; $sellerId = $product->creator_id; } } elseif (!empty($item->bundle_id)) { $targetType = 'bundles'; $bundle = $item->bundle; if (!empty($bundle)) { $itemId = $bundle->id; $itemType = $bundle->type; $categoryId = $bundle->category_id; $sellerId = $bundle->teacher_id; } } return $this->getRules($targetType, $itemId, $itemType, $categoryId, $sellerId); } public function getRules($targetType, $itemId = null, $itemType = null, $categoryId = null, $instructorId = null, $sellerId = null) { $group = !empty($this->user) ? $this->user->getUserGroup() : null; $groupId = !empty($group) ? $group->id : null; $userId = !empty($this->user) ? $this->user->id : null; $time = time(); $query = CashbackRule::query(); if (!empty($groupId)) { $query->where(function ($query) use ($groupId) { $query->whereDoesntHave('usersAndGroups'); $query->orWhereHas('usersAndGroups', function ($query) use ($groupId) { $query->where('group_id', $groupId); }); }); } if (!empty($userId)) { $query->where(function ($query) use ($userId) { $query->whereDoesntHave('usersAndGroups'); $query->orWhereHas('usersAndGroups', function ($query) use ($userId) { $query->where('user_id', $userId); }); }); } $query->where(function ($query) use ($time) { $query->whereNull('start_date'); $query->orWhere('start_date', '<', $time); }); $query->where(function ($query) use ($time) { $query->whereNull('end_date'); $query->orWhere('end_date', '>', $time); }); $query->where(function (Builder $query) use ($targetType, $itemType, $categoryId, $instructorId, $itemId, $sellerId) { $query->where('target_type', 'all'); $query->orWhere(function (Builder $query) use ($targetType, $itemType, $categoryId, $instructorId, $itemId, $sellerId) { $query->where('target_type', $targetType); if ($targetType == 'courses') { $this->targetCoursesQuery($query, $itemType, $categoryId, $instructorId, $itemId); } else if ($targetType == 'store_products') { $this->targetStoreProductsQuery($query, $itemType, $categoryId, $sellerId, $itemId); } else if ($targetType == 'bundles') { $this->targetBundlesQuery($query, $categoryId, $instructorId, $itemId); } else if ($targetType == 'meetings') { $this->targetMeetingsQuery($query, $instructorId); } else if ($targetType == 'registration_packages') { $this->targetRegistrationPackagesQuery($query, $itemId); } else if ($targetType == 'subscription_packages') { $this->targetSubscriptionPackagesQuery($query, $itemId); } }); }); $query->where('enable', true); return $query->get(); } private function targetCoursesQuery(Builder $query, $courseType, $categoryId, $instructorId, $itemId): Builder { $courseTypeTarget = ($courseType == Webinar::$webinar) ? 'live_classes' : (($courseType == Webinar::$course) ? 'video_courses' : 'text_courses'); $query->where(function (Builder $query) use ($courseTypeTarget, $categoryId, $instructorId, $itemId) { $query->where('target', 'all_courses'); $query->orWhere('target', $courseTypeTarget); // Specific Category $query->orWhere(function (Builder $query) use ($categoryId) { $query->where('target', 'specific_categories'); $query->whereHas('specificationItems', function ($query) use ($categoryId) { $query->where('category_id', $categoryId); }); }); // Specific Instructor $query->orWhere(function (Builder $query) use ($instructorId) { $query->where('target', 'specific_instructors'); $query->whereHas('specificationItems', function ($query) use ($instructorId) { $query->where('instructor_id', $instructorId); }); }); // Specific Course $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_courses'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('webinar_id', $itemId); }); }); }); return $query; } private function targetStoreProductsQuery(Builder $query, $productType, $categoryId, $sellerId, $itemId): Builder { $productTypeTarget = ($productType == Product::$physical) ? 'physical_products' : 'virtual_products'; $query->where(function (Builder $query) use ($productTypeTarget, $categoryId, $sellerId, $itemId) { $query->where('target', 'all_products'); $query->orWhere('target', $productTypeTarget); // Specific Category $query->orWhere(function (Builder $query) use ($categoryId) { $query->where('target', 'specific_categories'); $query->whereHas('specificationItems', function ($query) use ($categoryId) { $query->where('category_id', $categoryId); }); }); // Specific Seller $query->orWhere(function (Builder $query) use ($sellerId) { $query->where('target', 'specific_sellers'); $query->whereHas('specificationItems', function ($query) use ($sellerId) { $query->where('seller_id', $sellerId); }); }); // Specific Product $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_products'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('product_id', $itemId); }); }); }); return $query; } private function targetBundlesQuery(Builder $query, $categoryId, $instructorId, $itemId): Builder { $query->where(function (Builder $query) use ($categoryId, $instructorId, $itemId) { $query->where('target', 'all_bundles'); // Specific Category $query->orWhere(function (Builder $query) use ($categoryId) { $query->where('target', 'specific_categories'); $query->whereHas('specificationItems', function ($query) use ($categoryId) { $query->where('category_id', $categoryId); }); }); // Specific Seller $query->orWhere(function (Builder $query) use ($instructorId) { $query->where('target', 'specific_instructors'); $query->whereHas('specificationItems', function ($query) use ($instructorId) { $query->where('instructor_id', $instructorId); }); }); // Specific Product $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_bundles'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('bundle_id', $itemId); }); }); }); return $query; } private function targetMeetingsQuery(Builder $query, $instructorId): Builder { $query->where(function (Builder $query) use ($instructorId) { $query->where('target', 'all_meetings'); // Specific Instructor $query->orWhere(function (Builder $query) use ($instructorId) { $query->where('target', 'specific_instructors'); $query->whereHas('specificationItems', function ($query) use ($instructorId) { $query->where('instructor_id', $instructorId); }); }); }); return $query; } private function targetRegistrationPackagesQuery(Builder $query, $itemId): Builder { $query->where(function (Builder $query) use ($itemId) { $query->where('target', 'all_packages'); // Specific Package $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_packages'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('registration_package_id', $itemId); }); }); }); return $query; } private function targetSubscriptionPackagesQuery(Builder $query, $itemId): Builder { $query->where(function (Builder $query) use ($itemId) { $query->where('target', 'all_packages'); // Specific Package $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_packages'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('subscribe_id', $itemId); }); }); }); return $query; } } RegistrationBonus/RegistrationBonusAccounting.php 0000644 00000014233 15102516125 0016433 0 ustar 00 <?php namespace App\Mixins\RegistrationBonus; use App\Models\Accounting; use App\Models\Affiliate; use App\Models\Sale; use App\User; use Illuminate\Support\Facades\DB; class RegistrationBonusAccounting { public function __construct() { } public function storeRegistrationBonusInstantly($user) { $registrationBonusSettings = getRegistrationBonusSettings(); if (!$user->enable_registration_bonus or empty($registrationBonusSettings['status']) or empty($registrationBonusSettings['registration_bonus_amount'])) { return false; } $bonusAmount = !empty($user->registration_bonus_amount) ? $user->registration_bonus_amount : $registrationBonusSettings['registration_bonus_amount']; $bonusWallet = $registrationBonusSettings['bonus_wallet']; $typeAccount = ($bonusWallet == 'income_wallet') ? Accounting::$income : Accounting::$asset; if (!empty($registrationBonusSettings['unlock_registration_bonus_instantly'])) { // As soon as the user registers, the bonus will be activated. Accounting::createRegistrationBonusUserAmountAccounting($user->id, $bonusAmount, $typeAccount); } } public function storeRegistrationBonus($user) { $registrationBonusSettings = getRegistrationBonusSettings(); if (!$user->enable_registration_bonus or empty($registrationBonusSettings['status']) or empty($registrationBonusSettings['registration_bonus_amount'])) { return false; } $bonusAmount = !empty($user->registration_bonus_amount) ? $user->registration_bonus_amount : $registrationBonusSettings['registration_bonus_amount']; $bonusWallet = $registrationBonusSettings['bonus_wallet']; $typeAccount = ($bonusWallet == 'income_wallet') ? Accounting::$income : Accounting::$asset; if (empty($registrationBonusSettings['unlock_registration_bonus_instantly'])) { $numberOfReferredUsers = 0; // How many people must register through the link or individual code to unlock the prize $purchaseAmountForUnlockingBonus = 0; $checkJustHasPurchase = false; if (!empty($registrationBonusSettings['unlock_registration_bonus_with_referral']) and !empty($registrationBonusSettings['number_of_referred_users'])) { $numberOfReferredUsers = $registrationBonusSettings['number_of_referred_users']; } if (!empty($registrationBonusSettings['enable_referred_users_purchase']) and !empty($registrationBonusSettings['purchase_amount_for_unlocking_bonus'])) { $purchaseAmountForUnlockingBonus = $registrationBonusSettings['purchase_amount_for_unlocking_bonus']; /* * Users who are referred by the individual link must buy that amount in order for the condition of money release to be established * (this amount is calculated separately for each user). * Also, if this field is empty, it means that the amount is not a criterion for us, * the only thing that matters is that the user has made a purchase. * with any amount (the amount charged to the purchase account is not taken into account) * */ } elseif (!empty($registrationBonusSettings['enable_referred_users_purchase'])) { $checkJustHasPurchase = true; } $unlockedBonus = true; if (!empty($numberOfReferredUsers)) { $referredUsersCount = Affiliate::query()->where('affiliate_user_id', $user->id)->count(); if ($referredUsersCount < $numberOfReferredUsers) { $unlockedBonus = false; } if ($unlockedBonus and (!empty($purchaseAmountForUnlockingBonus) or $checkJustHasPurchase)) { $referredUsersId = Affiliate::query()->where('affiliate_user_id', $user->id) ->pluck('referred_user_id') ->toArray(); if (!empty($referredUsersId)) { $sales = Sale::query()->select('buyer_id', DB::raw('sum(total_amount) as totalAmount')) ->whereIn('buyer_id', $referredUsersId) ->whereNull('refund_at') ->groupBy('buyer_id') ->orderBy('totalAmount', 'desc') ->get(); $reachedCount = 0; foreach ($sales as $sale) { if ($checkJustHasPurchase and $sale->totalAmount > 0) { $reachedCount += 1; } else if (!empty($purchaseAmountForUnlockingBonus) and $sale->totalAmount >= $purchaseAmountForUnlockingBonus) { $reachedCount += 1; } } if ($reachedCount < $numberOfReferredUsers) { $unlockedBonus = false; } } else { $unlockedBonus = false; } } } else { $unlockedBonus = false; } if ($unlockedBonus) { Accounting::createRegistrationBonusUserAmountAccounting($user->id, $bonusAmount, $typeAccount); $notifyOptions = [ '[u.name]' => $user->full_name, '[amount]' => handlePrice($bonusAmount), ]; sendNotification("registration_bonus_unlocked", $notifyOptions, $user->id); sendNotification("registration_bonus_unlocked_for_admin", $notifyOptions, 1); } } } public function checkBonusAfterSale($buyerId) { $checkReferred = Affiliate::query() ->where('referred_user_id', $buyerId) ->first(); if (!empty($checkReferred)) { $affiliateUser = User::query()->where('id', $checkReferred->affiliate_user_id)->first(); if (!empty($affiliateUser)) { $this->storeRegistrationBonus($affiliateUser); } } } } Installment/InstallmentRefund.php 0000644 00000003254 15102516125 0013207 0 ustar 00 <?php namespace App\Mixins\Installment; use App\Models\Accounting; use App\Models\Installment; use App\Models\InstallmentOrderPayment; use App\Models\Product; use App\Models\Webinar; use Illuminate\Database\Eloquent\Builder; class InstallmentRefund { public function refundOrder($order) { $orderPayments = InstallmentOrderPayment::query() ->where('installment_order_id', $order->id) ->where('status', 'paid') ->get(); if ($orderPayments->isNotEmpty()) { foreach ($orderPayments as $payment) { // Buyer Accounting::create([ 'user_id' => $order->user_id, 'amount' => $payment->amount, 'installment_payment_id' => $payment->id, 'type' => Accounting::$addiction, 'type_account' => Accounting::$asset, 'description' => trans('update.installment_refund'), 'created_at' => time() ]); // System Accounting::create([ 'system' => true, 'user_id' => $order->user_id, 'amount' => $payment->amount, 'installment_payment_id' => $payment->id, 'type' => Accounting::$deduction, 'type_account' => Accounting::$income, 'description' => trans('update.installment_refund'), 'created_at' => time() ]); $payment->update([ 'status' => 'refunded' ]); } } return true; } } Installment/InstallmentAccounting.php 0000644 00000012160 15102516125 0014052 0 ustar 00 <?php namespace App\Mixins\Installment; use App\Http\Controllers\Web\CartController; use App\Models\Accounting; use App\Models\Cart; use App\Models\InstallmentOrderPayment; use App\Models\OrderItem; class InstallmentAccounting { public function refundOrder($order) { $orderPayments = InstallmentOrderPayment::query() ->where('installment_order_id', $order->id) ->where('status', 'paid') ->with([ 'sale' ]) ->get(); if ($orderPayments->isNotEmpty()) { foreach ($orderPayments as $payment) { $sale = $payment->sale; if (!empty($sale)) { // Buyer Accounting::create([ 'user_id' => $order->user_id, 'amount' => $sale->total_amount, 'installment_payment_id' => $payment->id, 'type' => Accounting::$addiction, 'type_account' => Accounting::$asset, 'description' => trans('update.installment_refund'), 'created_at' => time() ]); // System Accounting::create([ 'system' => true, 'user_id' => $order->user_id, 'amount' => $sale->total_amount, 'installment_payment_id' => $payment->id, 'type' => Accounting::$deduction, 'type_account' => Accounting::$income, 'description' => trans('update.installment_refund'), 'created_at' => time() ]); $sale->update([ 'refund_at' => time() ]); } $payment->update([ 'status' => 'refunded' ]); } } $order->update([ 'status' => 'canceled' ]); // refund Seller Accounting $this->refundSellerOrder($order); return true; } public function refundSellerOrder($order) { $item = $order->getItem(); if (!empty($item->creator_id)) { $accounting = Accounting::query() ->where('installment_order_id', $order->id) ->where('user_id', $item->creator_id) ->first(); if (!empty($accounting)) { Accounting::create([ 'user_id' => $item->creator_id, 'amount' => $accounting->amount, 'installment_order_id' => $order->id, 'type' => Accounting::$deduction, 'type_account' => Accounting::$income, 'description' => trans('update.installment_refund'), 'created_at' => time() ]); } } } public function createAccountingForSeller($order) { $orderPrices = $this->handleOrderPrices($order); $price = $orderPrices['sub_total']; $totalDiscount = $orderPrices['total_discount']; $tax = $orderPrices['tax']; $taxPrice = $orderPrices['tax_price']; $commission = $orderPrices['commission']; $commissionPrice = $orderPrices['commission_price']; $discountCouponPrice = 0; $allDiscountPrice = $totalDiscount + $discountCouponPrice; $subTotalWithoutDiscount = $price - $allDiscountPrice; $totalAmount = $subTotalWithoutDiscount + $taxPrice; $orderItem = new OrderItem(); $orderItem->user_id = $order->user_id; $orderItem->order_id = 1; // $orderItem->installment_order_id = $order->id; // $orderItem->webinar_id = $order->webinar_id ?? null; $orderItem->bundle_id = $order->bundle_id ?? null; $orderItem->product_id = (!empty($order->product_order_id) and !empty($order->productOrder->product)) ? $order->productOrder->product->id : null; $orderItem->product_order_id = (!empty($order->product_order_id)) ? $order->product_order_id : null; $orderItem->amount = $price; $orderItem->total_amount = $totalAmount; $orderItem->tax = $tax; $orderItem->tax_price = $taxPrice; $orderItem->commission = $commission; $orderItem->commission_price = $commissionPrice; $orderItem->discount = $allDiscountPrice; $orderItem->created_at = time(); Accounting::createAccountingSeller($orderItem); if ($orderItem->commission_price) { Accounting::createAccountingCommission($orderItem); } } private function handleOrderPrices($order) { $cart = new Cart(); $cart->creator_id = $order->user_id; $cart->webinar_id = $order->webinar_id; $cart->bundle_id = $order->bundle_id; $cart->product_order_id = $order->product_order_id; $cart->subscribe_id = $order->subscribe_id; $cartController = new CartController(); return $cartController->handleOrderPrices($cart, $order->user); } } Installment/InstallmentPlans.php 0000644 00000021710 15102516125 0013036 0 ustar 00 <?php namespace App\Mixins\Installment; use App\Models\Installment; use App\Models\Product; use App\Models\Webinar; use Illuminate\Database\Eloquent\Builder; class InstallmentPlans { private $user; public function __construct($user = null) { if (empty($user)) { $user = auth()->user(); } $this->user = $user; } public function getPlans($targetType, $itemId = null, $itemType = null, $categoryId = null, $instructorId = null, $sellerId = null) { $group = !empty($this->user) ? $this->user->getUserGroup() : null; $groupId = !empty($group) ? $group->id : null; $time = time(); $query = Installment::query(); if (!empty($groupId)) { $query->where(function ($query) use ($groupId) { $query->whereDoesntHave('userGroups'); $query->orWhereHas('userGroups', function ($query) use ($groupId) { $query->where('group_id', $groupId); }); }); } $query->where(function ($query) use ($time) { $query->whereNull('start_date'); $query->orWhere('start_date', '<', $time); }); $query->where(function ($query) use ($time) { $query->whereNull('end_date'); $query->orWhere('end_date', '>', $time); }); $query->where(function (Builder $query) use ($targetType, $itemType, $categoryId, $instructorId, $itemId, $sellerId) { $query->where('target_type', 'all'); $query->orWhere(function (Builder $query) use ($targetType, $itemType, $categoryId, $instructorId, $itemId, $sellerId) { $query->where('target_type', $targetType); if ($targetType == 'courses') { $this->targetCoursesQuery($query, $itemType, $categoryId, $instructorId, $itemId); } else if ($targetType == 'store_products') { $this->targetStoreProductsQuery($query, $itemType, $categoryId, $sellerId, $itemId); } else if ($targetType == 'bundles') { $this->targetBundlesQuery($query, $categoryId, $instructorId, $itemId); } else if ($targetType == 'meetings') { $this->targetMeetingsQuery($query, $instructorId); } else if ($targetType == 'registration_packages') { $this->targetRegistrationPackagesQuery($query, $itemId); } else if ($targetType == 'subscription_packages') { $this->targetSubscriptionPackagesQuery($query, $itemId); } }); }); $query->where('enable', true); return $query->get(); } private function targetCoursesQuery(Builder $query, $courseType, $categoryId, $instructorId, $itemId): Builder { $courseTypeTarget = ($courseType == Webinar::$webinar) ? 'live_classes' : (($courseType == Webinar::$course) ? 'video_courses' : 'text_courses'); $query->where(function (Builder $query) use ($courseTypeTarget, $categoryId, $instructorId, $itemId) { $query->where('target', 'all_courses'); $query->orWhere('target', $courseTypeTarget); // Specific Category $query->orWhere(function (Builder $query) use ($categoryId) { $query->where('target', 'specific_categories'); $query->whereHas('specificationItems', function ($query) use ($categoryId) { $query->where('category_id', $categoryId); }); }); // Specific Instructor $query->orWhere(function (Builder $query) use ($instructorId) { $query->where('target', 'specific_instructors'); $query->whereHas('specificationItems', function ($query) use ($instructorId) { $query->where('instructor_id', $instructorId); }); }); // Specific Course $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_courses'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('webinar_id', $itemId); }); }); }); return $query; } private function targetStoreProductsQuery(Builder $query, $productType, $categoryId, $sellerId, $itemId): Builder { $productTypeTarget = ($productType == Product::$physical) ? 'physical_products' : 'virtual_products'; $query->where(function (Builder $query) use ($productTypeTarget, $categoryId, $sellerId, $itemId) { $query->where('target', 'all_products'); $query->orWhere('target', $productTypeTarget); // Specific Category $query->orWhere(function (Builder $query) use ($categoryId) { $query->where('target', 'specific_categories'); $query->whereHas('specificationItems', function ($query) use ($categoryId) { $query->where('category_id', $categoryId); }); }); // Specific Seller $query->orWhere(function (Builder $query) use ($sellerId) { $query->where('target', 'specific_sellers'); $query->whereHas('specificationItems', function ($query) use ($sellerId) { $query->where('seller_id', $sellerId); }); }); // Specific Product $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_products'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('product_id', $itemId); }); }); }); return $query; } private function targetBundlesQuery(Builder $query, $categoryId, $instructorId, $itemId): Builder { $query->where(function (Builder $query) use ($categoryId, $instructorId, $itemId) { $query->where('target', 'all_bundles'); // Specific Category $query->orWhere(function (Builder $query) use ($categoryId) { $query->where('target', 'specific_categories'); $query->whereHas('specificationItems', function ($query) use ($categoryId) { $query->where('category_id', $categoryId); }); }); // Specific Seller $query->orWhere(function (Builder $query) use ($instructorId) { $query->where('target', 'specific_instructors'); $query->whereHas('specificationItems', function ($query) use ($instructorId) { $query->where('instructor_id', $instructorId); }); }); // Specific Product $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_bundles'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('bundle_id', $itemId); }); }); }); return $query; } private function targetMeetingsQuery(Builder $query, $instructorId): Builder { $query->where(function (Builder $query) use ($instructorId) { $query->where('target', 'all_meetings'); // Specific Instructor $query->orWhere(function (Builder $query) use ($instructorId) { $query->where('target', 'specific_instructors'); $query->whereHas('specificationItems', function ($query) use ($instructorId) { $query->where('instructor_id', $instructorId); }); }); }); return $query; } private function targetRegistrationPackagesQuery(Builder $query, $itemId): Builder { $query->where(function (Builder $query) use ($itemId) { $query->where('target', 'all_packages'); // Specific Package $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_packages'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('registration_package_id', $itemId); }); }); }); return $query; } private function targetSubscriptionPackagesQuery(Builder $query, $itemId): Builder { $query->where(function (Builder $query) use ($itemId) { $query->where('target', 'all_packages'); // Specific Package $query->orWhere(function (Builder $query) use ($itemId) { $query->where('target', 'specific_packages'); $query->whereHas('specificationItems', function ($query) use ($itemId) { $query->where('subscribe_id', $itemId); }); }); }); return $query; } } Certificate/MakeCertificate.php 0000644 00000013644 15102516125 0012525 0 ustar 00 <?php namespace App\Mixins\Certificate; use App\Models\Certificate; use App\Models\CertificateTemplate; use App\Models\Reward; use App\Models\RewardAccounting; use \Barryvdh\DomPDF\Facade\Pdf; use Intervention\Image\Facades\Image; class MakeCertificate { public function makeQuizCertificate($quizResult) { $template = CertificateTemplate::where('status', 'publish') ->where('type', 'quiz') ->first(); if (!empty($template)) { $quiz = $quizResult->quiz; $user = $quizResult->user; $userCertificate = $this->saveQuizCertificate($user, $quiz, $quizResult); $body = $this->makeBody( $userCertificate, $user, $template->body, $quiz->webinar ? $quiz->webinar->title : '-', $quizResult->user_grade, $quiz->webinar->teacher->full_name, $quiz->webinar->duration); /*$data = [ 'pageTitle' => trans('public.certificate'), 'image' => public_path($template->image), 'body' => $body, ];*/ $img = $this->makeImage($template, $body); return $img->response('png'); } abort(404); } private function saveQuizCertificate($user, $quiz, $quizResult) { $certificate = Certificate::where('quiz_id', $quiz->id) ->where('student_id', $user->id) ->where('quiz_result_id', $quizResult->id) ->first(); $data = [ 'quiz_id' => $quiz->id, 'student_id' => $user->id, 'quiz_result_id' => $quizResult->id, 'user_grade' => $quizResult->user_grade, 'type' => 'quiz', 'created_at' => time() ]; if (!empty($certificate)) { $certificate->update($data); } else { $certificate = Certificate::create($data); $notifyOptions = [ '[c.title]' => $quiz->webinar ? $quiz->webinar->title : '-', ]; sendNotification('new_certificate', $notifyOptions, $user->id); } return $certificate; } private function makeBody($userCertificate, $user, $body, $courseTitle = null, $userGrade = null, $teacherFullName = null, $duration = null) { $body = str_replace('[student]', $user->full_name, $body); $body = str_replace('[course]', $courseTitle, $body); $body = str_replace('[grade]', $userGrade, $body); $body = str_replace('[certificate_id]', $userCertificate->id, $body); $body = str_replace('[date]', dateTimeFormat($userCertificate->created_at, 'j M Y | H:i'), $body); $body = str_replace('[instructor_name]', $teacherFullName, $body); $body = str_replace('[duration]', $duration, $body); $userCertificateAdditional = $user->userMetas->where('name', 'certificate_additional')->first(); $userCertificateAdditionalValue = !empty($userCertificateAdditional) ? $userCertificateAdditional->value : null; $body = str_replace('[user_certificate_additional]', $userCertificateAdditionalValue, $body); return $body; } private function makeImage($certificateTemplate, $body) { $img = Image::make(public_path($certificateTemplate->image)); if ($certificateTemplate->rtl) { $Arabic = new \I18N_Arabic('Glyphs'); $body = $Arabic->utf8Glyphs($body); } $img->text($body, $certificateTemplate->position_x, $certificateTemplate->position_y, function ($font) use ($certificateTemplate) { $font->file($certificateTemplate->rtl ? public_path('assets/default/fonts/vazir/Vazir-Medium.ttf') : public_path('assets/default/fonts/Montserrat-Medium.ttf')); $font->size($certificateTemplate->font_size); $font->color($certificateTemplate->text_color); $font->align($certificateTemplate->rtl ? 'right' : 'left'); }); return $img; } public function makeCourseCertificate($certificate) { $template = CertificateTemplate::where('status', 'publish') ->where('type', 'course') ->first(); $course = $certificate->webinar; if (!empty($template) and !empty($course)) { $user = $certificate->student; $userCertificate = $this->saveCourseCertificate($user, $course); $body = $this->makeBody( $userCertificate, $user, $template->body, $course->title, null, $course->teacher->full_name, $course->duration); /*$data = [ 'pageTitle' => trans('public.certificate'), 'image' => public_path($template->image), 'body' => $body, ]; $pdf = Pdf::loadView('web.default.certificate_template.index', $data); return $pdf->setPaper('a4', 'landscape') ->setWarnings(false) ->stream('course_certificate.pdf');*/ $img = $this->makeImage($template, $body); return $img->response('png'); } abort(404); } public function saveCourseCertificate($user, $course) { $certificate = Certificate::where('webinar_id', $course->id) ->where('student_id', $user->id) ->first(); $data = [ 'webinar_id' => $course->id, 'student_id' => $user->id, 'type' => 'course', 'created_at' => time() ]; if (!empty($certificate)) { $certificate->update($data); } else { $certificate = Certificate::create($data); $notifyOptions = [ '[c.title]' => $course->title, ]; sendNotification('new_certificate', $notifyOptions, $user->id); } return $certificate; } } Financial/MultiCurrency.php 0000644 00000002563 15102516125 0011752 0 ustar 00 <?php namespace App\Mixins\Financial; use App\Models\Currency; use Illuminate\Support\Collection; class MultiCurrency { public function getCurrencies(): Collection { $defaultCurrency = $this->getDefaultCurrency(); $currencies = Currency::query()->orderBy('order', 'asc')->get(); if ($currencies->isNotEmpty()) { $currencies->prepend($defaultCurrency); return $currencies; } return collect(); } public function getSpecificCurrency($currencySign) { $specificCurrency = null; $currencies = $this->getCurrencies(); foreach ($currencies as $currency) { if ($currency->currency == $currencySign) { $specificCurrency = $currency; } } return $specificCurrency; } public function getDefaultCurrency() { $settings = getFinancialCurrencySettings(); $defaultCurrency = new Currency(); $defaultCurrency->currency = $settings['currency'] ?? 'USD'; $defaultCurrency->currency_position = $settings['currency_position'] ?? 'left'; $defaultCurrency->currency_separator = $settings['currency_separator'] ?? 'dot'; $defaultCurrency->currency_decimal = $settings['currency_decimal'] ?? 0; $defaultCurrency->exchange_rate = null; return $defaultCurrency; } } Geo/Geo.php 0000644 00000007155 15102516125 0006507 0 ustar 00 <?php class Geo { static public function get_geo_text($array, $type) { $geoWKT = ""; switch ($type) { case "MULTIPOLYGON": $tmpPolygons = array(); foreach ($array as $polygonsWKA) { $tmpPoint = array(); foreach ($polygonsWKA as $pointWKA) $tmpPoint[] = implode(" ", $pointWKA); $tmpPolygons[] = "((" . implode(",", $tmpPoint) . "))"; } $geoWKT = "MULTIPOLYGON(" . implode(",", $tmpPolygons) . ")"; break; case "MULTIPOINT": $tmpPoint = array(); foreach ($array as $pointWKA) $tmpPoint[] = implode(" ", $pointWKA); $geoWKT = "MULTIPOINT(" . implode(",", $tmpPoint) . ")"; break; case "POINT": case "point": $geoWKT = "POINT(" . implode(" ", $array) . ")"; break; case "POLYGON": $polyPoints = array(); foreach ($array as $tmpPolyPoint) $polyPoints[] .= implode(" ", $tmpPolyPoint); $geoWKT = "POLYGON((" . implode(",", $polyPoints) . "))"; break; } return $geoWKT; } static public function get_geo_array($text) { $geoWKA = array(); if (strstr($text, "MULTIPOLYGON((")) { $geoWKA = array(); $geoText = trim(trim($text, "MULTIPOLYGON((("), ")))"); if (!empty($geoText)) { $geoText = "($geoText)"; $tmpGeoWKTs = explode("),(", $geoText); foreach ($tmpGeoWKTs as $tmpPolygonWKT) { $tmpGeoText = trim(trim($tmpPolygonWKT, "("), ")"); $tmpGeoWKAs = explode(",", $tmpGeoText); $polygonWKA = array(); foreach ($tmpGeoWKAs as $tmpPolyPoint) $polygonWKA[] = explode(" ", trim($tmpPolyPoint)); $geoWKA[] = $polygonWKA; } } } elseif (strstr($text, "MULTIPOINT(")) { $geoWKA = array(); $geoText = trim(trim($text, "MULTIPOINT("), ")"); if (!empty($geoText)) { $tmpGeoWKAs = explode(",", $geoText); foreach ($tmpGeoWKAs as $tmpGeoWKA) $geoWKA[] = explode(" ", trim($tmpGeoWKA)); } } elseif (strstr($text, "POINT(")) { $geoText = trim(trim($text, "POINT("), ")"); if (!empty($geoText)) $geoWKA = explode(" ", $geoText); } elseif (strstr($text, "point(")) { $geoText = trim(trim($text, "point("), ")"); if (!empty($geoText)) $geoWKA = explode(",", $geoText); } elseif (strstr($text, "POLYGON((")) { $geoText = trim(trim($text, "POLYGON(("), "))"); if (!empty($geoText)) { $tmpPolyPoints = explode(",", $geoText); foreach ($tmpPolyPoints as $tmpPolyPoint) $geoWKA[] = explode(" ", $tmpPolyPoint); } } return $geoWKA; } static function getST_AsTextFromBinary($binary) { // like => POINT(36.36822190085111 59.52341079711915) $coordinates = unpack('x/x/x/x/corder/Ltype/dlat/dlon', $binary); try { $point = 'POINT('; $point .= $coordinates['lat']; $point .= ' ' . $coordinates['lon']; $point .= ')'; return $point; } catch (Exception $e) { } } } RegistrationPackage/UserPackage.php 0000644 00000017005 15102516125 0013376 0 ustar 00 <?php namespace App\Mixins\RegistrationPackage; use App\Models\GroupRegistrationPackage; use App\Models\Product; use App\Models\Sale; use App\Models\Webinar; class UserPackage { public $package_id; public $instructors_count; public $students_count; public $courses_capacity; public $courses_count; public $meeting_count; public $product_count; public $title; public $activation_date; public $days_remained; private $user; public function __construct($user = null) { if (empty($user)) { $user = auth()->user(); } $this->user = $user; $this->title = trans('update.default'); $this->activation_date = $user->created_at; } private function make($data = null, $type = null): UserPackage { $package = new UserPackage(); $checkAccountRestrictions = $this->checkAccountRestrictions(); if ($checkAccountRestrictions) { $package->instructors_count = (!empty($data) and isset($data->instructors_count)) ? $data->instructors_count : null; $package->students_count = (!empty($data) and isset($data->students_count)) ? $data->students_count : null; $package->courses_capacity = (!empty($data) and isset($data->courses_capacity)) ? $data->courses_capacity : null; $package->courses_count = (!empty($data) and isset($data->courses_count)) ? $data->courses_count : null; $package->meeting_count = (!empty($data) and isset($data->meeting_count)) ? $data->meeting_count : null; $package->product_count = (!empty($data) and isset($data->product_count)) ? $data->product_count : null; if ($type == 'package') { $package->package_id = $data->id; $package->title = $data->title; $package->activation_date = $data->activation_date; $package->days_remained = $data->days_remained; } } return $package; } private function checkAccountRestrictions(): bool { if ($this->user->isOrganization()) { $settings = getRegistrationPackagesOrganizationsSettings(); } else { $settings = getRegistrationPackagesInstructorsSettings(); } return (!empty($settings) and !empty($settings['status']) and $settings['status']); } public function getDefaultPackage($role = null): UserPackage { if ($this->user->isOrganization() or ($role == 'organizations')) { $settings = getRegistrationPackagesOrganizationsSettings(); } else { $settings = getRegistrationPackagesInstructorsSettings(); } if (!empty($settings)) { $settings = (!empty($settings['status']) and $settings['status']) ? (object)$settings : null; } return $this->make($settings); } private function getLastPurchasedPackage() { $user = $this->user; $lastSalePackage = Sale::where('buyer_id', $user->id) ->where('type', Sale::$registrationPackage) ->whereNotNull('registration_package_id') ->whereNull('refund_at') ->latest('created_at') ->first(); $package = null; if (!empty($lastSalePackage)) { $registrationPackage = $lastSalePackage->registrationPackage; $countDayOfSale = (int)diffTimestampDay(time(), $lastSalePackage->created_at); if ($registrationPackage->days >= $countDayOfSale) { $registrationPackage->activation_date = $lastSalePackage->created_at; $registrationPackage->days_remained = $registrationPackage->days - $countDayOfSale; $package = $registrationPackage; } else { $registrationPackageExpire = $lastSalePackage->created_at + ($registrationPackage->days * 24 * 60 * 60); $notifyOptions = [ '[item_title]' => $registrationPackage->title, '[time.date]' => dateTimeFormat($registrationPackageExpire, 'j M Y') ]; sendNotification("registration_package_expired", $notifyOptions, $user->id); } } return $package; } public function getPackage(): UserPackage { $user = $this->user; $registrationPackage = null; $registrationPackageType = null; $checkAccountRestrictions = $this->checkAccountRestrictions(); if ($checkAccountRestrictions) { $userRegistrationPackage = $user->userRegistrationPackage()->where('status', 'active')->first(); if (!empty($userRegistrationPackage)) { $registrationPackage = $userRegistrationPackage; $registrationPackageType = 'user'; } else { $userGroup = $user->userGroup; $groupRegistrationPackage = null; if (!empty($userGroup)) { $groupRegistrationPackage = GroupRegistrationPackage::where('group_id', $userGroup->group_id) ->where('status', 'active') ->first(); } if (!empty($groupRegistrationPackage)) { $registrationPackage = $groupRegistrationPackage; $registrationPackageType = 'group'; } else { $registrationPackage = $this->getLastPurchasedPackage(); $registrationPackageType = 'package'; } } } if ($registrationPackage) { return $this->make($registrationPackage, $registrationPackageType); } return $this->getDefaultPackage(); } /** * @param $type => instructors_count, students_count, courses_capacity, courses_count, meeting_count, product_count * */ public function checkPackageLimit($type, $count = null) { $user = $this->user; $package = $this->getPackage(); $result = false; // no limit $usedCount = 0; if (!empty($package) and !is_null($package->{$type})) { switch ($type) { case 'instructors_count': $usedCount = $user->getOrganizationTeachers()->count(); break; case 'students_count': $usedCount = $user->getOrganizationStudents()->count(); break; case 'courses_capacity': $usedCount = $count; break; case 'courses_count': $usedCount = Webinar::where('creator_id', $user->id)->count(); break; case 'meeting_count': $userMeeting = $user->meeting; if (!empty($userMeeting)) { $usedCount = $userMeeting->meetingTimes()->count(); } break; case 'product_count': $usedCount = Product::where('creator_id', $user->id)->count(); break; } if (is_null($usedCount) and !empty($package->{$type}) or $usedCount >= $package->{$type}) { $resultData = [ 'type' => $type, 'currentCount' => $package->{$type} ]; $result = (string)view()->make('web.default.panel.financial.package_limitation_modal', $resultData); $result = str_replace(array("\r\n", "\n", " "), '', $result); } } return $result; } } Cart/CartItemInfo.php 0000644 00000014050 15102516125 0010470 0 ustar 00 <?php namespace App\Mixins\Cart; class CartItemInfo { public function getItemInfo($cart) { if (!empty($cart->webinar_id)) { $webinar = $cart->webinar; return $this->getCourseInfo($cart, $webinar); } elseif (!empty($cart->bundle_id)) { $bundle = $cart->bundle; return $this->getBundleInfo($cart, $bundle); } elseif (!empty($cart->productOrder) and !empty($cart->productOrder->product)) { $product = $cart->productOrder->product; return $this->getProductInfo($cart, $product); } elseif (!empty($cart->reserve_meeting_id)) { $creator = $cart->reserveMeeting->meeting->creator; return $this->getReserveMeetingInfo($cart, $creator); } elseif (!empty($cart->installment_payment_id)) { $installmentPayment = $cart->installmentPayment; return $this->getInstallmentOrderInfo($cart, $installmentPayment); } } private function getCourseInfo($cart, $webinar) { $info = []; $info['imgPath'] = $webinar->getImage(); $info['itemUrl'] = $webinar->getUrl(); $info['title'] = $webinar->title; $info['profileUrl'] = $webinar->teacher->getProfileUrl(); $info['teacherName'] = $webinar->teacher->full_name; $info['rate'] = $webinar->getRate(); $info['price'] = $webinar->price; $info['discountPrice'] = $webinar->getDiscount($cart->ticket) ? ($webinar->price - $webinar->getDiscount($cart->ticket)) : null; return $info; } private function getBundleInfo($cart, $bundle) { $info = []; $info['imgPath'] = $bundle->getImage(); $info['itemUrl'] = $bundle->getUrl(); $info['title'] = $bundle->title; $info['profileUrl'] = $bundle->teacher->getProfileUrl(); $info['teacherName'] = $bundle->teacher->full_name; $info['rate'] = $bundle->getRate(); $info['price'] = $bundle->price; $info['discountPrice'] = $bundle->getDiscount($cart->ticket) ? ($bundle->price - $bundle->getDiscount($cart->ticket)) : null; return $info; } private function getProductInfo($cart, $product) { $info = []; $info['isProduct'] = true; $info['imgPath'] = $product->thumbnail; $info['itemUrl'] = $product->getUrl(); $info['title'] = $product->title; $info['profileUrl'] = $product->creator->getProfileUrl(); $info['teacherName'] = $product->creator->full_name; $info['rate'] = $product->getRate(); $info['quantity'] = $cart->productOrder ? $cart->productOrder->quantity : 1; $info['price'] = $product->price; $info['discountPrice'] = ($product->getPriceWithActiveDiscountPrice() < $product->price) ? $product->getPriceWithActiveDiscountPrice() : null; return $info; } private function getReserveMeetingInfo($cart, $creator) { $info = []; $info['imgPath'] = $creator->getAvatar(150); $info['itemUrl'] = null; $info['title'] = trans('meeting.reservation_appointment') . ' ' . ((!empty($cart->reserveMeeting->student_count) and $cart->reserveMeeting->student_count > 1) ? '(' . trans('update.reservation_appointment_student_count', ['count' => $cart->reserveMeeting->student_count]) . ')' : ''); $info['profileUrl'] = $creator->getProfileUrl(); $info['teacherName'] = $creator->full_name; $info['rate'] = $creator->rates(); $info['price'] = $cart->reserveMeeting->paid_amount; return $info; } private function getSubscribeInfo($cart, $subscribe) { $info = []; $info['imgPath'] = $subscribe->icon; $info['itemUrl'] = null; $info['title'] = $subscribe->title; $info['profileUrl'] = null; $info['teacherName'] = null; $info['extraHint'] = trans('public.subscribe'); $info['rate'] = null; $info['quantity'] = null; $info['price'] = $subscribe->price; $info['discountPrice'] = null; return $info; } private function getRegistrationPackageInfo($cart, $registrationPackage) { $info = []; $info['imgPath'] = $registrationPackage->icon; $info['itemUrl'] = null; $info['title'] = $registrationPackage->title; $info['profileUrl'] = null; $info['teacherName'] = null; $info['extraHint'] = trans('update.registration_package'); $info['rate'] = null; $info['quantity'] = null; $info['price'] = $registrationPackage->price; $info['discountPrice'] = null; return $info; } private function getInstallmentOrderInfo($cart, $installmentPayment) { $info = []; $installmentOrder = $installmentPayment->installmentOrder; if (!empty($installmentOrder)) { if (!empty($installmentOrder->webinar_id)) { $webinar = $installmentOrder->webinar; $info = $this->getCourseInfo($cart, $webinar); } elseif (!empty($installmentOrder->bundle_id)) { $bundle = $installmentOrder->bundle; $info = $this->getBundleInfo($cart, $bundle); } elseif (!empty($installmentOrder->product_id)) { $product = $installmentOrder->product; $info = $this->getProductInfo($cart, $product); } elseif (!empty($installmentOrder->subscribe_id)) { $subscribe = $installmentOrder->subscribe; $info = $this->getSubscribeInfo($cart, $subscribe); } elseif (!empty($installmentOrder->registration_package_id)) { $registrationPackage = $installmentOrder->registrationPackage; $info = $this->getRegistrationPackageInfo($cart, $registrationPackage); } $info['price'] = $installmentPayment->amount; $info['discountPrice'] = 0; $info['extraPriceHint'] = ($installmentPayment->type == 'upfront') ? trans('update.installment_upfront') : trans('update.installment'); } return $info; } } BunnyCDN/BunnyVideoStream.php 0000644 00000012043 15102516125 0012131 0 ustar 00 <?php namespace App\Mixins\BunnyCDN; use GuzzleHttp\Exception\GuzzleException; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Storage; use ToshY\BunnyNet\VideoStreamRequest; class BunnyVideoStream { protected $client; protected $bunnyStream; protected $libraryId; protected $hostname; protected $accessKey; protected $tokenAuthenticationKey; public function __construct() { $this->client = new \GuzzleHttp\Client(); $settings = getFeaturesSettings('bunny_configs'); $this->libraryId = (!empty($settings) and !empty($settings['library_id'])) ? $settings['library_id'] : null; $this->hostname = (!empty($settings) and !empty($settings['hostname'])) ? $settings['hostname'] : null; $this->accessKey = (!empty($settings) and !empty($settings['access_key'])) ? $settings['access_key'] : null; $this->tokenAuthenticationKey = (!empty($settings) and !empty($settings['token_authentication_key'])) ? $settings['token_authentication_key'] : null; $this->bunnyStream = new VideoStreamRequest($this->accessKey); } /** * @throws GuzzleException */ public function createCollection($name, $checkDuplicate = false) { if ($checkDuplicate) { $response = $this->bunnyStream->getCollectionList($this->libraryId, [ 'page' => 1, 'itemsPerPage' => 100, 'search' => $name, 'orderBy' => 'date', ]); $oldCollectionId = null; if (!empty($response['content']) and !empty($response['content']['items'])) { foreach ($response['content']['items'] as $item) { if ($item and $item['name'] == $name) { $oldCollectionId = $item['guid']; } } } if (!empty($oldCollectionId)) { return $oldCollectionId; } } $response = $this->client->request('POST', "https://video.bunnycdn.com/library/{$this->libraryId}/collections", [ 'body' => '{"name": "' . $name . '"}', 'headers' => [ 'AccessKey' => "{$this->accessKey}", 'accept' => 'application/json', 'content-type' => 'application/*+json', ], ]); if ($response->getStatusCode() == 200) { $body = json_decode($response->getBody(), true); return $body['guid']; } return null; } public function uploadVideo($title, $collectionId, UploadedFile $file) { $videoId = $this->createVideo($title, $collectionId); if ($videoId) { // create tmp directory Storage::disk('public')->makeDirectory('bunny_tmp'); // upload to tmp directory $filename = time() . $file->getClientOriginalName(); $fileLocation = Storage::disk('public')->putFileAs( 'bunny_tmp', $file, $filename ); $filePath = public_path("/store/$fileLocation"); $body = $this->bunnyStream->uploadVideo($this->libraryId, $videoId, $filePath); $url = null; if (!empty($body['status']) and $body['status']['code'] == 200) { //$url = $body['status']["info"]['url']; $url = "https://iframe.mediadelivery.net/embed/{$this->libraryId}/{$videoId}"; $sha256 = Hash::make("{$this->tokenAuthenticationKey}" . "$videoId"); $url .= "?token=" . $sha256; } // remove tmp directory Storage::disk('public')->deleteDirectory('bunny_tmp'); return $url; } } private function createVideo($title, $collectionId = null) { $response = $this->bunnyStream->createVideo($this->libraryId, [ 'title' => $title, 'collectionId' => $collectionId ]); if ($response and $response['status']['code'] == 200) { return $response['content']['guid']; } return false; } private function getLibraryIdAndVideoIdFromPath($path) { if (empty($path)) { return false; } $path = str_replace('https://iframe.mediadelivery.net/embed/', '', $path); $path = explode('?', $path)[0]; $path = explode('/', $path); if (count($path) < 2) { return false; } $libraryId = $path[0]; $videoId = $path[1]; return [ 'libraryId' => $libraryId, 'videoId' => $videoId, ]; } public function deleteVideo($path) { $getLibraryIdAndVideoIdFromPath = $this->getLibraryIdAndVideoIdFromPath($path); if ($getLibraryIdAndVideoIdFromPath) { $libraryId = $getLibraryIdAndVideoIdFromPath['libraryId']; $videoId = $getLibraryIdAndVideoIdFromPath['videoId']; $this->bunnyStream->deleteVideo($libraryId, $videoId); } } }
| ver. 1.4 |
Github
|
.
| PHP 8.0.30 | Генерация страницы: 0 |
proxy
|
phpinfo
|
Настройка