Skip to content

Instantly share code, notes, and snippets.

@dura0ok
Created March 23, 2019 08:17
Show Gist options
  • Save dura0ok/7b88db74bab1cdfcba45de6a61399c18 to your computer and use it in GitHub Desktop.
Save dura0ok/7b88db74bab1cdfcba45de6a61399c18 to your computer and use it in GitHub Desktop.
Error
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Webpatser\Uuid\Uuid;
/**
* Class Card
* @package App
* @method static findOrFail() Card
*/
class Card extends Model
{
public $incrementing = true;
private $_subscription = null;
protected $guarded = [];
protected $dates = ['sold_at'];
public function user()
{
return $this->belongsTo('App\User');
}
public function city()
{
return $this->belongsTo(City::class);
}
public function activeSubscription(){
if($this->_subscription)
return $this->_subscription;
$subscription = $this->subscriptions()->where('is_active', true)->orderByDesc('card_subscription.id')->first();
if(!$subscription)
return null;
if($subscription->pivot->created_at->diffInDays(Carbon::now()) > $subscription->length) {
$subscription->pivot->update(['is_active'=> false]);
return null;
}
$this->_subscription = $subscription;
return $subscription;
}
public function hasActiveSubscription(){
return $this->activeSubscription() ? true : false;
}
public function activeSubscriptionLeft(){
if(!$this->activeSubscription())
return false;
$date = $this->activeSubscription()->pivot->created_at;
$dateTill = $date->addDay($this->activeSubscription()->length);
return $dateTill->diffInDays(Carbon::now());
}
public function subscriptions(){
return $this->belongsToMany('App\Subscription','card_subscription')->withTimestamps()->withPivot(['is_active', 'id']);
}
public function discounts(){
return $this->hasManyThrough('App\Discount', 'App\Subscription');
}
public static function getByParcedId($card_id, $no_fail = false){
$card_id = preg_replace('/\s+/', '', $card_id);
if(substr($card_id, 0, 3) === '888'){
$card_code = substr($card_id, 3);
}else{
$card_code = $card_id;
}
return $no_fail ? self::find($card_code) : self::findOrFail($card_code);
}
public function log(){
return $this->hasMany('App\DiscountLog');
}
public function discountsByShops(array $shop_id){
return $this->activeSubscription()->discounts()->whereIn('shop_id', $shop_id)->get();
}
public function discountsByShopsCount(array $shop_id){
return $this->activeSubscription()->discounts()->whereIn('shop_id', $shop_id)->count();
}
public function assignSubscription($subscription){
$sub = Subscription::findOrFail($subscription);
if(!$this->hasActiveSubscription())
$this->subscriptions()->attach($sub->id);
// \DB::table('card_subscription')->insert([
// 'subscription_id' => $sub->id,
// 'card_id' => $this->id,
// 'is_active' => true
// ]);
}
public function discountsAmount()
{
return $this->log()->where('is_validated', 1)->count();
}
public function amountSaved()
{
return $this->log()->where('is_validated', 1)->sum('saved_sum');
}
public function uniqueShopsVisited()
{
return $this->log()->where('is_validated', 1)->distinct()->get(array('shop_id'))->count();
}
public function uniqueShops()
{
return $this->activeSubscription()->discounts()->distinct()->get(array('shop_id'))->count();
}
public function scopeCostFrom(Builder $query, $param = null)
{
if (!$param) return $query;
return $query->where('cost', '>', $param);
}
public function scopeCostTo(Builder $query, $param = null)
{
if (!$param) return $query;
return $query->where('cost', '<', $param);
}
public function scopeActivatedFrom(Builder $query, $param = null)
{
if (!$param) return $query;
return $query->where('activated_at', '>=', Carbon::parse($param));
}
public function scopeActivatedTo(Builder $query, $param = null)
{
if (!$param) return $query;
return $query->where('activated_at', '<=', Carbon::parse($param));
}
}
<?php
namespace App\Http\Controllers\v2;
use App\Card;
use App\Category;
use App\DiscountUse;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class CardController extends Controller
{
public function index ()
{
return view('v2.cards.index');
}
public function show($id)
{
$card = Card::getByParcedId($id);
$validations = collect();
$categories = Category::all();
$discounts = collect();
if ($card->hasActiveSubscription()) {
$cs_id = $card->activeSubscription()->pivot->id;
if (auth()->check() && auth()->user()->hasAnyRole(['shopuser', 'shopadmin'])) {
$validations = DiscountUse::where('is_validated', false)->where('validation_sent', '>', Carbon::parse('-5 minutes'))->where('card_subscription_id', $cs_id)->get();
}
$discounts = collect();
if (!request()->input('category') || request()->input('category') == 'all') {
$discounts = $card->activeSubscription()->discounts()->byCity()->paginate(15)->appends('category');
} else {
DB::listen(function ($query) {
dump(str_replace_array(
$search = '#' . str_random() . '#',
$query->bindings,
preg_replace('/\B\?/', $search, $query->sql))
);
});
//ИНТЕРЕСУЕТ ЭТА СТРОЧКА ELSE!!
$cat = request()->input('category');
$discounts = $card->activeSubscription()->discounts()->
byCity()->byCategory(1)
->paginate(20);
}
}
return view('v2.cards.show')
->with('card', $card)
->with('validation', $validations)
->with('discounts', $discounts)
->with('categories', $categories);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Discount extends Model
{
protected $guarded = [];
public function shop(){
return $this->belongsTo(Shop::class)->where('is_visible', 1);
}
public function subscription(){
return $this->belongsTo(Subscription::class);
}
public function uses(){
return $this->hasMany(DiscountUse::class);
}
public function getAvailableDiscounts($card_subscription_id){
if($this->type !== 'countable')
return 0;
$uses_count = $this->uses()->where('card_subscription_id', $card_subscription_id)->where('is_validated',1)->count();
if($uses_count > $this->amount)
return 0;
if($uses_count > 0)
return $this->amount - $uses_count;
return $this->amount;
}
public function getAvailableDiscountsCount($card_subscription_id){
$uses_count = $this->uses()->where('card_subscription_id', $card_subscription_id)->where('is_validated', 1)->count();
return $uses_count;
}
public function isDiscountAvailable($card_subscription_id){
if($this->type !== 'countable')
return true;
if($this->getAvailableDiscounts($card_subscription_id) > 0)
return true;
return false;
}
public function getReadableTypeAttribute(){
return $this->type == 'countable' ? 'Заканчивающаяся' : 'Бесконечная';
}
public function needsValidation(){
return true;
}
public function printableDiscountCount($activeSubscriptionId) : string
{
return $this->type == 'infinitive' ? '∞' :
$this->getAvailableDiscounts($activeSubscriptionId);
}
public function printableType() : string
{
return $this->type == 'infinitive' ? 'Бесконечная' : 'Кол-во скидок';
}
public function scopeByCity()
{
return $this->whereHas('shop', function ($query) {
$query->where('city_id', request()->hasCookie('loc') ? request()->cookie('loc') : 1);
});
}
public function scopeByCategory($cat)
{
return $this->whereHas('shop', function ($query) use($cat) {
return $query->where('category_id', $cat);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment