File: /var/www/vhost/disk-apps/comfama.sports-crowd.com/app/Http/Controllers/MatchEventsController.php
<?php
namespace App\Http\Controllers;
use \Excel;
use App\Seat;
use App\Team;
use App\User;
use App\Ticket;
use DataTables;
use App\Parameter;
use App\TicketTag;
use Carbon\Carbon;
use App\MatchEvent;
use App\TicketMain;
use App\TicketUserBlock;
use Illuminate\Http\Request;
use App\TicketUserBlockBackup;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Controllers\TicketsController;
use App\Http\Controllers\Exports\ReportTickets;
use App\MatchEventTag;
use App\Tag;
use App\TicketType;
use App\Zone;
use Illuminate\Support\Facades\DB;
class MatchEventsController extends Controller
{
private $__COURTESY_TICKET_TYPE = 3; // TIPO DE BOLETA CORTESIA
private $salesTypes;
public function __construct()
{
$this->salesTypes[] = (object) [
'name' => 'Silla/s seleccionada',
'value' => 'seleccionada'
];
$this->salesTypes[] = (object) [
'name' => 'Silla/s aleatoria',
'value' => 'aleatoria'
];
}
public function index($season_id)
{
$parameters = Parameter::first();
return view('matchevents.list', compact('parameters', 'season_id'));
}
public function create($season_id)
{
$teams = Team::select('id', 'name', 'display_name')->where([['is_main', false], ['active', true]])->orderBy('name', 'asc')->get();
$team_main = Team::select('id', 'name', 'display_name')->where([['is_main', true], ['active', true]])->first();
$multiselectItems = Tag::select('id', 'name')->where('active', true)->get();
$stadiums = Zone::select('id', 'name')->where('active', 1)->whereNull('zone_id')->get();
$salesTypes = $this->salesTypes;
return view('matchevents.create', compact('teams', 'team_main', 'season_id', 'multiselectItems', 'stadiums', 'salesTypes'));
}
public function store(Request $request)
{
try {
if (!MatchEvent::where([['season_id', $request->input('season_id')], ['name', $request->input('name')]])->first()) {
$tags = $request["tags"];
$request->request->remove('tags');
$data = $request->all();
if ($data['zone_id']) {
$stadium = Zone::find($data['zone_id']);
$data['stadium_to_play'] = $stadium->name;
}
if ($model = MatchEvent::create(array_merge($data, ['code' => $this->codeOrder()]))) {
if ($tags != null) {
foreach ($tags as $tagId) {
MatchEventTag::create([
'tag_id' => $tagId,
'match_event_id' => $model->id
]);
}
}
return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.created_successfully'), "data" => $model->id));
} else {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_creating'), "data" => null));
}
} else {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.already_exists', ['name' => $request->input('name')]), "data" => null));
}
} catch (\Exception $e) {
return response(
array(
"r" => false,
"type" => "error",
"title" => "Oops...",
"m" => __($e->getMessage()),
"data" => null
)
);
}
}
public function show($id)
{
return redirect()->back();
}
public function edit($season_id, $id)
{
$event = MatchEvent::findOrFail($id);
$teams = Team::select('id', 'name', 'display_name')->where([['is_main', false], ['active', true]])->orderBy('name', 'asc')->get();
$team_main = Team::select('id', 'name', 'display_name')->where([['is_main', true], ['active', true]])->first();
$multiselectItems = Tag::select('id', 'name')->where('active', true)->get();
$multiselectValues = MatchEventTag::select('tag_id')->where('match_event_id', $id)->get();
$stadiums = Zone::select('id', 'name')->where('active', 1)->whereNull('zone_id')->get();
$salesTypes = $this->salesTypes;
return view('matchevents.edit', compact('event', 'teams', 'team_main', 'season_id', 'multiselectItems', 'multiselectValues', 'stadiums', 'salesTypes'));
}
public function update(Request $request, $season_id, $id)
{
try {
if (!MatchEvent::where([['id', '!=', $id], ['season_id', $request->input('season_id')], ['name', $request->input('name')]])->first()) {
$request->request->remove('_method');
$tags = $request["tags"];
$request->request->remove('tags');
$request->request->remove('generalMultiselect');
$data = $request->all();
if ($data['zone_id']) {
$stadium = Zone::find($data['zone_id']);
$data['stadium_to_play'] = $stadium->name;
}
if (MatchEvent::where('id', $id)->update($data)) {
MatchEventTag::where('match_event_id', $id)->delete();
if ($tags != null) {
foreach ($tags as $tagId) {
MatchEventTag::create([
'tag_id' => $tagId,
'match_event_id' => $id
]);
}
}
return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.updated_successfully'), "data" => $id));
} else {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_updating'), "data" => null));
}
} else {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.already_exists', ['name' => $request->input('name')]), "data" => null));
}
} catch (\Exception $e) {
return response(
array(
"r" => false,
"type" => "error",
"title" => "Oops...",
"m" => __($e->getMessage()),
"data" => null
)
);
}
}
public function destroy($season_id, $id)
{
try {
if (MatchEvent::where('id', $id)->delete()) {
return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.deleted_successfully'), "data" => null));
} else {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_removing'), "data" => null));
}
} catch (\Illuminate\Database\QueryException $e) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.delete_relation_data'), "data" => null));
}
}
public function tableFilter($season_id)
{
DB::statement("SET sql_mode = ''");
$obj = MatchEvent::select(
'match_events.id',
'match_events.name',
'match_events.sales_type',
'match_events.code',
'match_events.date_name',
'match_events.event_start_sale',
'match_events.event_end_sale',
'match_events.event_start',
'match_events.season_id',
'match_events.stadium_to_play',
'match_events.active',
DB::raw('GROUP_CONCAT(DISTINCT(tags.name)) AS segmentation')
)->with('season')
->leftjoin('match_event_tags', 'match_event_tags.match_event_id', '=', 'match_events.id')
->leftjoin('tags', 'tags.id', '=', 'match_event_tags.tag_id')
->where('match_events.season_id', $season_id)
->groupBy('match_events.id');
DB::statement("SET sql_mode = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'");
return DataTables::of($obj)
->addColumn('actions', function ($obj) {
$infoEvents = '<i class="fa fa-ticket iconMini" onClick="clickInfoEvent(' . $obj->id . ')" data-id="' . $obj->id . '" title="Boletas vendidas"></i>';
$infoBlocks = '<i class="fa fa-unlock-alt iconMini" onClick="clickInfoBlocks(' . $obj->id . ')" data-id="' . $obj->id . '" title="Información bloqueos"></i>';
$price = '<i class="fa fa-dollar iconMini" onClick="eventPrice(' . $obj->id . ')" data-id="' . $obj->id . '" title="Precios evento"></i>';
$edit = '<i class="fa fa-pencil iconMini" onClick="clickEdit(' . $obj->id . ', ' . $obj->season_id . ')" data-id="' . $obj->id . '" title="Editar evento"></i>';
$delete = '<i class="fa fa-trash iconMini" onClick="clickDelete(' . $obj->id . ', ' . $obj->season_id . ')" data-id="' . $obj->id . '" title="Eliminar evento"></i>';
$deleteBackups = '<i class="fa fa-close iconMini" onClick="clickDeleteBackups(' . $obj->id . ')" data-id="' . $obj->id . '" title="Eliminar backups"></i>';
$stage = '<i class="fa fa-cogs iconMini" onClick="clickMatchEventStage(' . $obj->id . ')" data-id="' . $obj->id . '" title="Configuraciones"></i>';
if ($this->validateRolePermissions('ticketing', 'administrator') || $this->validateRolePermissions('ticketing', 'supervisor'))
return $stage . $price . $infoEvents . $infoBlocks . $edit . $delete . $deleteBackups;
else if ($this->validateRolePermissions('ticketing', 'seller'))
return $infoEvents . $infoBlocks;
else
return '';
})
->editColumn('active', function ($obj) {
if ($this->validateRolePermissions('ticketing', 'administrator') || $this->validateRolePermissions('ticketing', 'supervisor'))
if ($obj->active == 0) {
return '<div class="switch"><label><div class="checkbox checbox-switch switch-success"> <label> ' . __('messages.no') . ' <input type="checkbox" onChange="chk(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" /> <span></span>' . __('messages.yes') . ' </label></div> </label> </div>';
} else {
return '<div class="switch"><label> <div class="checkbox checbox-switch switch-success"> <label> ' . __('messages.no') . ' <input type="checkbox" onChange="chk(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" checked="" />
<span></span> ' . __('messages.yes') . ' </label> </div> </label> </div>';
}
else
return $obj->active ? 'SI' : 'NO';
})
->editColumn('event_start_sale', function ($obj) {
return $obj->event_start_sale ? \Carbon\Carbon::parse($obj->event_start_sale)->format('Y-m-d h:i:s A') : '';
})
->editColumn('event_end_sale', function ($obj) {
return $obj->event_end_sale ? \Carbon\Carbon::parse($obj->event_end_sale)->format('Y-m-d h:i:s A') : '';
})
->editColumn('event_start', function ($obj) {
return $obj->event_start ? \Carbon\Carbon::parse($obj->event_start)->format('Y-m-d h:i:s A') : '';
})
->editColumn('sales_type', function ($obj) {
$sales_type = [];
if ($obj->sales_type) {
foreach (explode(',', $obj->sales_type) as $item) {
$object = collect($this->salesTypes)->where('value', $item)->first();
if ($object)
$sales_type[] = $object->name;
}
}
return implode(',', $sales_type);
})
->rawColumns(['active', 'actions'])
->make(true);
}
public function activate(Request $request)
{
try {
$id = $request['id'];
$state = $request['state'];
$matchEvent = MatchEvent::find($id);
$matchEvent->active = $state;
$matchEvent->update();
return array('r' => true, 'd' => null, 'm' => __('messages.updated_successfully'));
} catch (\Throwable $th) {
return array('r' => false, 'd' => null, 'm' => __('messages.error_updating'));
}
}
public function detailTicketsBuy($id)
{
$ticketTags = TicketTag::select('id', 'name')->where('active', true)->orderBy('name', 'ASC')->get();
$types = TicketType::select('id', 'name')->where('active', true)->orderBy('name', 'ASC')->get();
$types->prepend((object)[
'id' => 0,
'name' => 'Todos',
]);
$parameters = Parameter::select('presuscription')->first();
$hideDataSeat = $this->validateSaleByCapacity($id) && !$parameters->presuscription;
return view("matcheventTickets.index_match_event_tickets", compact('id', 'ticketTags', 'types', 'hideDataSeat'));
}
public function detailTicketsBlocks($id)
{
return view("matcheventBlocks.index_match_event_blocks", compact('id'));
}
public function detailTicketsBlockInfo($id)
{
return view("matcheventBlocks.index_match_event_block_info", compact('id'));
}
public function getTribunes()
{
$stadiumsZone = Zone::where('active', 1)->whereNull('zone_id')->pluck('id');
return Zone::select('id', 'name')->where('active', 1)->whereIn('zone_id', $stadiumsZone)->get();
}
public function getMatchEventTribunes($matchEventId)
{
$matchEvent = MatchEvent::find($matchEventId);
$stadiumsZone = $matchEvent->zone_id ? [$matchEvent->zone_id] : Zone::where('active', true)->whereNull('zone_id')->pluck('id');
return Zone::select('id', 'name')->where('active', true)->whereIn('zone_id', $stadiumsZone)->get();
}
public function getMatchEventZones($matchEventId)
{
$matchEvent = MatchEvent::find($matchEventId);
$stadiumsZone = $matchEvent->zone_id ? [$matchEvent->zone_id] : Zone::where('active', true)->whereNull('zone_id')->pluck('id');
$tribunes = Zone::where('active', true)->whereIn('zone_id', $stadiumsZone)->pluck('id');
return Zone::select('id', 'name', 'zone_id')->with('zone')->where([['is_saleable', true], ['active', true]])->whereIn('zone_id', $tribunes)->get();
}
public function tableFilterTickets(Request $request)
{
try {
$match_event_id = $request->match_event_id;
$userDeleted = $request->user_deleted;
DB::statement("SET sql_mode = ''");
$obj = Ticket::select('tickets.*')
->where('match_event_id', $match_event_id)
->with(['ticket_main', 'match_event', 'ticket_type', 'seat', 'ticket_status'])
->with(['user' => function ($query) {
$query->withTrashed();
}])
->join('users', 'users.id', '=', 'tickets.user_id')
->leftjoin('seats', 'seats.id', '=', 'tickets.seat_id')
->leftjoin('zones', 'zones.id', '=', 'seats.zone_id')
->leftjoin('zones as tribunes', 'tribunes.id', '=', 'zones.zone_id');
DB::statement("SET sql_mode = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'");
return DataTables::of($obj)
->addColumn('actions', function ($obj) use ($match_event_id) {
$changeStateTicket = '<i class="fa fa-edit iconMini" onClick="changeStateTicket(' . $obj->id . ', ' . $match_event_id . ')" data-id="' . $obj->id . '" title="Cambiar estado"></i>';
$changeSeat = '<i class="fa fa-reply-all iconMini" onClick="changeSeat(' . $obj->id . ', ' . $match_event_id . ')" data-id="' . $obj->id . '" title="Cambiar silla"></i>';
$printTicket = '<a href="/ticket/pdf/' . $obj->code_ticket . '" target="_blank" title="Imprimir"><i class="fa fa-print iconMini"></i></a>';
$sendEmailNotifications = '<i class="fa fa-envelope-o iconMini" onClick="sendEmailNotifications(' . $obj->user->id . ', ' . $match_event_id . ', \'' . $obj->code_ticket . '\')" data-id="' . $obj->user->id . '" title="Enviar notificación"></i>';
$getTicketsUserId = '<i class="fa fa-exchange iconMini" onClick="getTicketsUserid(' . $obj->user->id . ', \'' . $obj->user->email . '\', ' . $match_event_id . ', \'' . $obj->code_ticket . '\', ' . $obj->user->document . ')" data-id="' . $obj->user->id . '" title="Actualizar email"></i>';
$specialTicketModalClick = '<a data-toggle="modal" data-target="#modal_special_tickets"><i class="fa fa-ticket iconMini data-id="' . $obj->id . '" onClick="specialTicketModalClick(' . $obj->id . ')" title="Generar boletas especiales"></i></a>';
if ($this->validateRolePermissions('ticketing', 'administrator'))
return $changeStateTicket . $changeSeat . $printTicket . $sendEmailNotifications . $getTicketsUserId . $specialTicketModalClick;
else if ($this->validateRolePermissions('ticketing', 'supervisor'))
return $changeStateTicket . $changeSeat . $printTicket . $sendEmailNotifications . $getTicketsUserId;
else if ($this->validateRolePermissions('ticketing', 'seller'))
return $changeSeat . $printTicket;
else
return '';
})
->editColumn('created_at', function ($obj) {
return \Carbon\Carbon::parse($obj->created_at)->format('Y-m-d h:i:s A');
})
->rawColumns(['actions', 'created_at'])
->make(true);
} catch (\Throwable $th) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_global'), "data" => $th->getMessage()));
}
}
public function tableFilterBlocks($match_event_id)
{
try {
$obj = TicketMain::whereHas('ticket_user_blocks', function (Builder $query) use ($match_event_id) {
$query->where('match_event_id', $match_event_id);
});
if (Auth::user()->rol->id == $this->__EXTERNAL_OPERATOR_ROL) {
$obj = $obj->whereNotNull('pin_tercero');
}
if (in_array(Auth::user()->rol->id, [$this->__TICKET_OFFICE_ROL, $this->__TICKET_OFFICE_ROL_INTERNAL])) {
$obj = $obj->whereNotNull('pin_internal');
}
// $obj->with('ticket_user_blocks');
$obj->with('ticket_user_blocks.match_event');
$obj->with('ticket_user_blocks.ticket_type');
$obj->with('ticket_user_blocks.user');
return DataTables::of($obj)
->addColumn('actions', function ($obj) {
$approved = '';
if (Auth::user()->rol->id != $this->__EXTERNAL_OPERATOR_ROL) {
$approved = '<i class="fa fa-check-square-o iconMini" onClick="validateTickets(' . $obj->id . ', ' . $obj->season_id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom" style="cursor:pointer;"></i>';
}
return '
<i class="fa fa-eye iconMini" onClick="clickInfoBlockList(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom" style="cursor:pointer;"></i>
' . $approved . '
';
})
->editColumn('created_at', function ($obj) {
return \Carbon\Carbon::parse($obj->created_at)->format('Y-m-d h:i:s A');
})
->rawColumns(['actions', 'created_at'])
->make(true);
} catch (\Throwable $th) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_global'), "data" => $th->getMessage()));
}
}
public function tableFilterBlocksInfo($ticket_main_id)
{
try {
$obj = TicketUserBlock::where([['ticket_main_id', $ticket_main_id], ['is_social_distancing', false]])
->with(['match_event', 'ticket_type', 'seat', 'ticket_main'])
->with(['user' => function ($query) {
$query->withTrashed();
}])
->orderBy('created_at', 'DESC');
return DataTables::of($obj)
->make(true);
} catch (\Throwable $th) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_global'), "data" => $th->getMessage()));
}
}
public function validateTicket(Request $request)
{
try {
// Obtiene bloqueos de este pin.
$pin_tickets = TicketMain::where('id', $request->ticket_main_id)
->with(['ticket_user_blocks' => function ($q) {
$q->where('ticket_user_blocks.is_social_distancing', false);
}])
->first();
if (!$pin_tickets) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => "El pin no existe", "data" => null));
}
if ($pin_tickets->ticket_user_blocks->isEmpty()) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => "El pin ya expiró", "data" => null));
}
$ticketcontroller = new TicketsController;
if ($ticketcontroller->generateTickets($pin_tickets->ticket_user_blocks, $pin_tickets->id)) {
return response(array("r" => true, "type" => "success", "title" => "", "m" => "¡Boletas generadas exitosamente!", "data" => null));
}
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_global'), "data" => null));
} catch (\Throwable $th) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_global'), "data" => $th->getMessage()));
}
}
public function sendEmailNotifications(Request $request)
{
$user = User::find($request["id_user"]);
if ($user) {
$code_ticket = $request["code_ticket"];
$ticket = Ticket::where("code_ticket", $code_ticket)->first();
if ($ticket->ticket_type_id == $this->__COURTESY_TICKET_TYPE) {
$request = new Request([
'user_id' => $user->id,
'ticket_type_id' => $ticket->ticket_type_id,
'match_event_id' => $ticket->match_event_id
]);
$massiveFansController = new MassiveFansController();
$massiveFansController->resendListEmailTickets($request);
} else {
$ticketController = new TicketsController;
$ticketController->sendSingleEmailTicket($user->id, $code_ticket);
}
return array('r' => true, 'm' => trans('bien'));
} else {
return array('r' => false, 'm' => trans('mal'));
}
}
public function deleteBackups($match_event_id)
{
try {
$event = MatchEvent::where('id', $match_event_id)->first();
if ($event) {
if ($event->active || $event->event_start > Carbon::now()->format('Y-m-d H:i:s')) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => "No es posible eliminar, el evento aún es vigente", "data" => null));
}
TicketUserBlockBackup::where('match_event_id', $match_event_id)->delete();
}
return response(array("r" => true, "type" => "success", "title" => "", "m" => "¡Se han eliminado exitosamente los backups!", "data" => null));
} catch (\Throwable $th) {
return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_global'), "data" => $th->getMessage()));
}
}
public function export($id)
{
return Excel::download(new ReportTickets($id), 'MatchEventTickets' . $id . '.xlsx');
}
public function generateSpecialTickets(Request $request)
{
$max_especial_tickets = 4;
$ticked_id = $request['ticket_id'];
$amount = $request['amount'];
if ($amount > $max_especial_tickets) {
return array(
'r' => false,
'd' => null,
'm' => 'Solo puedes generar máximo ' . $max_especial_tickets . ' boletas especiales para este usuario'
);
}
$ticked_id = $request['ticket_id'];
$boughtTicket = Ticket::where('id', $ticked_id)->first();
$specialTickets = Ticket::where('ticket_main_id', $boughtTicket->ticket_main_id)
->whereNotNull('special_text')
->get()
->count();
if ($specialTickets >= $max_especial_tickets) {
return array(
'r' => false,
'd' => null,
'm' => 'Este usuario ya tiene ' . $specialTickets . ' boletas especial(es). No podrás generar boletas adicionales.'
);
}
if ($amount + $specialTickets > $max_especial_tickets) {
return array(
'r' => false,
'd' => null,
'm' => 'Este usuario ya tiene ' . $specialTickets . ' boletas especial(es). Solo podrás generar ' . ($max_especial_tickets - $specialTickets) . ' adicional(es).'
);
}
$seat = Seat::where('id', $boughtTicket->seat_id)->first();
$massiveFansController = new MassiveFansController;
return $massiveFansController->generateRamdomTickets(
$amount,
$boughtTicket->user_id,
$seat->zone_id,
$boughtTicket->match_event_id,
$boughtTicket->ticket_type_id,
0,
$boughtTicket->ticket_main_id,
$request['special_text']
);
}
public function getSaleView($salesType = null)
{
$view = config('app.sales_type');
if ($salesType)
if (str_contains(strtolower($salesType), strtolower('seleccionada'))) {
$view = 'web_ticketing.seatTicketDynamicStadium';
} else if (str_contains(strtolower($salesType), strtolower('aleatoria'))) {
$view = 'web_ticketing.flashTicket';
}
return $view;
}
public function validateSaleByCapacity($matchEventId)
{
$event = MatchEvent::select('sales_type')->find($matchEventId);
if (!$event)
return false;
return $event->sales_type == 'aleatoria';
}
}