'storeCategoryWithID', 'setCourse' => 'setCourse', 'hideMsg' => 'hideMsg'];
use WithFileUploads;
public $sortField = 'id';
public $sortAsc = false;
public $groupMsg = '';
public $type = 'dati';
public $from = '';
public $selectedCourseMember = 0;
protected $messages = [
'birth_nation_id.required' => 'birth_nation_id',
'birth_province_id.required' => 'birth_province_id',
'birth_city_id.required' => 'birth_city_id',
'nation_id.required' => 'nation_id',
'province_id.required' => 'province_id',
'city_id.required' => 'city_id',
'gender' => 'gender'
];
public function change($type)
{
$this->type = $type;
if ($type === 'corsi' && $this->dataId > 0) {
$this->loadMemberCards();
$this->loadMemberCertificates();
// TODO $this->checkCourseAvailability();
}
if ($type === 'presenze') {
$this->loadMemberPresences();
}
$this->dispatchBrowserEvent('scroll-to-top');
}
public function sortBy($field)
{
if ($this->sortField === $field) {
$this->sortAsc = ! $this->sortAsc;
} else {
$this->sortAsc = true;
}
$this->sortField = $field;
}
public $records, $first_name, $last_name, $image, $image_old, $status, $birth_place, $birth_city_id, $birth_province_id, $birth_nation_id, $birth_date, $gender, $no_send_mail, $exclude_from_records, $fiscal_code, $address, $zip_code, $nation_id, $province_id, $city_id, $phone, $phone2, $phone3, $email, $enabled, $dataId, $update = false, $add = false;
public $isSaving = false;
public $importoBorsellino, $father_name, $mother_name, $father_email, $mother_email, $father_phone, $mother_phone, $father_fiscal_code, $mother_fiscal_code, $father_doc_number, $father_doc_type, $mother_doc_number, $mother_doc_type, $mother_document_files, $father_document_files;
public $document_type, $document_number, $document_from, $document_expire_date, $document_files, $document_files_old;
public $selectId = 0;
public $causalId = 0;
public $error_fc = false;
public $under18 = false;
public $money = 0;
public $refreshAfter = 0;
public $checkedAll = false;
public $multipleIds = [];
public $multipleAction = '';
public $isItaly = true;
public $isBirthItaly = true;
public $showDetail = false;
public $currentMember;
public $currentStatus;
public $age = '';
public $disciplines = array();
public $cards = array();
public $categories = array();
public $courses = array();
public $course_names = array();
public $course_levels = array();
// public $course_types = array();
public $course_frequencies = array();
public $course_subscriptions = array();
public $createSubscription = false;
public $payMonths = array();
public $suspendedMonths = array();
public $showCourse = array();
public $searchTxt;
public $search;
public $showReset = false;
public $advanced = false;
public $birthNations = array();
public $birthProvinces = array();
public $birthCities = array();
public $active;
// Card data
public $member_cards = array(), $card_card_id, $card_number, $card_date, $card_accept_date, $card_status, $card_discipline1_id, $card_discipline2_id, $card_discipline3_id, $addCard, $updateCard, $cardDataId;
// Categories data
public $member_categories = array(), $category_category_id;
// Courses data
public $member_courses = array(), $course_course_id, $course_course_type, $course_date_from, $course_date_to, $course_when = array(), $addCourse, $updateCourse, $courseDataId, $course_course_subscription_id, $course_status, $course_note, $course_price, $course_subscription_price, $course_subscribed, $course_months = array(), $course_exist;
public $course_months_list = [];
public $course_price_list = [];
public $course_name, $course_level_id, $course_type_id, $course_frequency_id;
// Certificates data
public $member_certificates = array(), $certificate_type, $certificate_filename_old, $certificate_filename, $certificate_expire_date, $certificate_status, $addCertificate, $updateCertificate, $certificateDataId, $cardCertificateId;
public $filterCard = [];
public $filterCategory = [];
public $filterCertNormal = 0;
public $filterCertAgonistic = 0;
public $filterCertScaduto = 0;
public $filterCertInScadenza = 0;
public $already_existing = false;
private $fileService;
public $hasCertificate = false;
public $presenceYears = [];
public $presenceYearFilter = '';
public $presenceTitle = [];
public $presenceTitleFilter = '';
public $member_presences = [];
public $presenceCourses = [];
public $presenceCourseFilter = '';
public $totals = 0;
public $presenze = 0;
public $assenze = 0;
public $annullate = 0;
public $recuperi = [];
protected $rules = [
'first_name' => 'required',
'last_name' => 'required',
// 'email' => 'required',
// 'phone' => 'required',
'birth_date' => 'before_or_equal:today'
];
/** Cambi Subscription */
public $member_subscriptions = [];
public $subscriptions;
public $subscription_exist;
public $subscription_subscriptions;
public $subscription_id;
public $subscription_course_subscription_id;
public $subscription_price;
public $subscription_subscription_price;
public $subscription_date_from;
public $subscription_date_to;
public $subscription_notes;
/** END - Cambi Subscription */
public function resetFields()
{
$this->dataId = -1;
$this->first_name = '';
$this->last_name = '';
$this->status = '';
$this->birth_city_id = null;
$this->birth_province_id = null;
$this->birth_nation_id = null;
$this->birth_date = null;
$this->birth_place = '';
$this->importoBorsellino = 0;
$this->father_name = '';
$this->mother_name = '';
$this->father_email = '';
$this->mother_email = '';
$this->father_phone = '';
$this->mother_phone = '';
$this->father_fiscal_code = '';
$this->mother_fiscal_code = '';
$this->father_doc_number = '';
$this->mother_doc_number = '';
$this->father_doc_type = '';
$this->mother_doc_type = '';
$this->mother_document_files = array();
$this->father_document_files = array();
$this->gender = null;
$this->no_send_mail = false;
$this->exclude_from_records = false;
$this->fiscal_code = '';
$this->address = '';
$this->zip_code = '';
$this->document_type = '';
$this->document_number = '';
$this->document_from = '';
$this->document_expire_date = null;
$this->document_files = array();
//$this->nation_id = null;
//$this->province_id = null;
$this->nation_id = null;
$this->province_id = null;
$this->city_id = null;
$this->phone = '';
$this->phone2 = '';
$this->phone3 = '';
$this->email = '';
$this->enabled = true;
$this->under18 = false;
$this->hasCertificate = false;
$this->money = 0;
$this->image = null;
$this->age = '';
$this->error_fc = false;
$this->already_existing = false;
$this->isSaving = false;
$this->emit('load-data-table');
}
public function resetCardFields()
{
$this->card_card_id = null;
$this->card_number = '';
$this->card_date = null;
$this->card_accept_date = null;
$this->card_status = 0;
$this->card_discipline1_id = null;
$this->card_discipline2_id = null;
$this->card_discipline3_id = null;
}
public function resetCertificateFields()
{
$this->certificate_type = '';
$this->certificate_filename = '';
$this->certificate_filename_old = '';
$this->certificate_expire_date = date('Y-m-d', strtotime('+1 year'));
$this->certificate_status = 0;
}
public function resetCourseFields()
{
$this->course_course_id = null;
$this->course_course_type = 'standard';
$this->course_months_list = [];
$this->course_price_list = [];
$this->course_when = array();
$this->course_when[] = array('day' => array(), 'from' => '', 'to' => '');
$this->course_date_from = null;
$this->course_date_to = null;
$this->course_course_subscription_id = null;
$this->course_status = 0;
$this->course_price = 0;
$this->course_subscription_price = 0;
$this->course_exist = false;
$this->course_subscribed = false;
$this->course_months = array();
$this->course_note = '';
$this->course_name = '';
$this->course_level_id = '';
$this->course_type_id = '';
$this->course_frequency_id = '';
$this->subscription_id = null;
$this->resetSubscriptionFields();
}
public function resetSubscriptionFields()
{
$this->subscription_exist = false;
$this->subscription_subscriptions = [];
$this->subscription_course_subscription_id = null;
$this->subscription_price = null;
$this->subscription_subscription_price = null;
$this->subscription_date_from = null;
$this->subscription_date_to = null;
$this->subscription_notes = null;
}
public function executeMultipleAction()
{
if ($this->multipleAction == 'delete')
$this->multipleDelete();
}
public function updatedImage()
{
$this->validate([
'image' => 'image|max:1024',
]);
$this->image_old = '';
}
public function updatedCourseName()
{
$this->course_course_id = null;
$this->course_level_id = '';
$this->course_frequency_id = '';
$levels_ids = [];
if ($this->course_name != '') {
list($n, $y) = explode("(", $this->course_name);
$y = trim(str_replace(")", "", $y));
$all = \App\Models\Course::where('name', 'like', '%' . trim($n) . "%")->where('year', $y)->where('enabled', true)->get();
foreach ($all as $a) {
$levels_ids[] = $a->course_level_id;
}
}
$this->course_levels = \App\Models\CourseLevel::select('*')->where('enabled', true)->whereIn('id', $levels_ids)->get();
$this->course_frequencies = [];
}
public function updatedCourseLevelId()
{
$this->course_course_id = null;
$this->course_frequency_id = '';
$frequencies_ids = [];
if ($this->course_level_id != '') {
list($n, $y) = explode("(", $this->course_name);
$y = trim(str_replace(")", "", $y));
$all = \App\Models\Course::where('name', 'like', '%' . trim($n) . "%")->where('year', $y)->where('enabled', true)->where('course_level_id', $this->course_level_id)->get();
foreach ($all as $a) {
$frequencies_ids[] = $a->course_frequency_id;
}
}
$this->course_frequencies = \App\Models\CourseFrequency::select('*')->where('enabled', true)->whereIn('id', $frequencies_ids)->get();
}
/*
public function updatedCourseTypeId()
{
$this->course_course_id = null;
$this->course_frequency_id = '';
$frequencies_ids = [];
if ($this->course_type_id != '') {
list($n, $y) = explode("(", $this->course_name);
$y = trim(str_replace(")", "", $y));
$all = \App\Models\Course::where('name', 'like', '%' . trim($n) . "%")->where('year', $y)->where('enabled', true)->where('course_level_id', $this->course_level_id)->where('course_type_id', $this->course_type_id)->get();
foreach ($all as $a) {
$frequencies_ids[] = $a->course_frequency_id;
}
}
$this->course_frequencies = \App\Models\CourseFrequency::select('*')->where('enabled', true)->whereIn('id', $frequencies_ids)->get();
}*/
public function updatedCourseFrequencyId()
{
$this->course_course_id = null;
if ($this->course_frequency_id != '') {
list($n, $y) = explode("(", $this->course_name);
$y = trim(str_replace(")", "", $y));
$this->course_course_id = \App\Models\Course::where('name', 'like', '%' . trim($n) . "%")->where('year', $y)->where('course_level_id', $this->course_level_id)->where('course_frequency_id', $this->course_frequency_id)->first()->id;
$c = \App\Models\Course::findOrFail($this->course_course_id);
$this->course_price = formatPrice($c->price);
$this->course_subscription_price = formatPrice($c->subscription_price);
// $this->course_date_from = $c->date_from;
$this->course_date_from = date('Y-m-d');
$this->course_date_to = $c->date_to;
// Carico gli abbonamenti e i mesi
$period = \Carbon\CarbonPeriod::create($c->date_from, '1 month', $c->date_to);
$this->course_months_list = [];
foreach ($period as $dt) {
$this->course_months_list[] = $dt->format("m");
}
$course_subscription_ids = [];
$this->course_price_list = [];
if ($c->prices != null) {
foreach (json_decode($c->prices) as $z) {
$this->course_price_list[$z->course_subscription_id] = $z->price;
if ($z->price > 0)
$course_subscription_ids[] = $z->course_subscription_id;
}
}
$this->course_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $course_subscription_ids)->where('enabled', true)->orderBy('name', 'asc')->get();
} else {
$this->course_price = 0;
$this->course_subscription_price = 0;
$this->course_exist = false;
}
}
public function updatedCourseCourseType()
{
$this->course_level_id = '';
$this->course_frequency_id = '';
$this->course_course_id = null;
}
public function updatedCourseCourseSubscriptionId()
{
$this->course_price = 0;
if (isset($this->course_price_list[$this->course_course_subscription_id]))
$this->course_price = $this->course_price_list[$this->course_course_subscription_id];
}
public $documents = [];
public $father_documents = [];
public $mother_documents = [];
public function removeDocument($idx, $type)
{
try {
if ($type == 'father') {
if (isset($this->father_document_files[$idx])) {
$filePath = $this->father_document_files[$idx];
$this->fileService->deleteFile($filePath);
unset($this->father_document_files[$idx]);
$this->father_document_files = array_values($this->father_document_files);
}
} elseif ($type == 'mother') {
if (isset($this->mother_document_files[$idx])) {
$filePath = $this->mother_document_files[$idx];
$this->fileService->deleteFile($filePath);
unset($this->mother_document_files[$idx]);
$this->mother_document_files = array_values($this->mother_document_files);
}
} else {
if (isset($this->document_files[$idx])) {
$filePath = $this->document_files[$idx];
$this->fileService->deleteFile($filePath);
unset($this->document_files[$idx]);
$this->document_files = array_values($this->document_files);
}
}
} catch (\Exception $e) {
session()->flash('error', 'Error removing document: ' . $e->getMessage());
}
}
public function updatedDocuments()
{
try {
foreach ($this->documents as $document) {
if ($this->dataId > 0) {
$s3Path = $this->fileService->uploadDocument($document, $this->dataId, 'self');
$this->document_files[] = $s3Path;
} else {
$name = $document->getClientOriginalName();
$document->storeAs('public', $name);
$this->document_files[] = $name;
}
}
$this->documents = [];
} catch (\Exception $e) {
session()->flash('error', 'Error uploading documents: ' . $e->getMessage());
}
}
public function updatedFatherDocuments()
{
try {
foreach ($this->father_documents as $document) {
if ($this->dataId > 0) {
$s3Path = $this->fileService->uploadDocument($document, $this->dataId, 'father');
$this->father_document_files[] = $s3Path;
} else {
$name = $document->getClientOriginalName();
$document->storeAs('public', $name);
$this->father_document_files[] = $name;
}
}
$this->father_documents = [];
} catch (\Exception $e) {
session()->flash('error', 'Error uploading father documents: ' . $e->getMessage());
}
}
public function updatedMotherDocuments()
{
try {
foreach ($this->mother_documents as $document) {
if ($this->dataId > 0) {
$s3Path = $this->fileService->uploadDocument($document, $this->dataId, 'mother');
$this->mother_document_files[] = $s3Path;
} else {
$name = $document->getClientOriginalName();
$document->storeAs('public', $name);
$this->mother_document_files[] = $name;
}
}
$this->mother_documents = [];
} catch (\Exception $e) {
session()->flash('error', 'Error uploading mother documents: ' . $e->getMessage());
}
}
public function resetCategoryFields()
{
$this->category_category_id = null;
}
public function getCategories($records, $indentation)
{
foreach ($records as $record) {
// $this->categories[] = array('id' => $record->id, 'name' => str_repeat(" / ", $indentation) . $record->name);
$this->categories[] = array('id' => $record->id, 'name' => $record->getTree());
if (count($record->childs))
$this->getCategories($record->childs, $indentation + 1);
}
}
public function getCourses($records, $indentation)
{
foreach ($records as $record) {
// $this->categories[] = array('id' => $record->id, 'name' => str_repeat(" / ", $indentation) . $record->name);
$this->courses[] = array('id' => $record->id, 'name' => $record->getTree());
if (count($record->childs))
$this->getCourses($record->childs, $indentation + 1);
}
}
public function updatedBirthDate()
{
$this->validateOnly('birth_date');
$date1 = new DateTime($this->birth_date);
$date2 = new DateTime("now");
$interval = $date1->diff($date2);
$this->age = $interval->y . " anni";
$this->under18 = $interval->y < 18;
}
public function mount()
{
if (isset($_GET["new"])) {
$this->refreshAfter = 1;
$this->add();
}
if (isset($_GET["from"])) {
$this->from = $_GET["from"];
}
$this->cards = \App\Models\Card::select('id', 'name')->get();
$this->disciplines = \App\Models\Discipline::select('id', 'name')->get();
$this->categories = array();
$this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->orderBy('name')->get(), 0);
$c = \App\Models\Causal::where('type', 'IN')->where('money', true)->first();
if ($c)
$this->causalId = $c->id;
if (isset($_GET["member_detail"])) {
$this->showDetailF($_GET["member_detail"]);
$this->refreshAfter = 1;
}
$this->subscription_id = null;
$this->subscriptions = \App\Models\Subscription::where('enabled', 1)->get();
}
public function boot()
{
$this->fileService = app(\App\Services\MemberFileService::class);
app(abstract: TenantMiddleware::class)->setupTenantConnection();
}
public function updated()
{
if ($this->isSaving) {
$zzz = [];
if ($this->birth_nation_id == null)
$zzz[] = 'birth_nation_id=' . $this->birth_nation_id;
if ($this->isBirthItaly) {
if ($this->birth_province_id == null)
$zzz[] = 'birth_province_id=' . $this->birth_province_id;
if ($this->birth_city_id == null)
$zzz[] = 'birth_city_id=' . $this->birth_city_id;
}
if ($this->nation_id == null)
$zzz[] = 'nation_id=' . $this->nation_id;
if ($this->isItaly) {
if ($this->province_id == null)
$zzz[] = 'province_id=' . $this->province_id;
if ($this->city_id == null)
$zzz[] = 'city_id=' . $this->city_id;
}
$this->emit('setErrorMsg', $zzz);
}
// $this->emit('load-select');
}
public function hydrate()
{
if ($this->isSaving) {
$zzz = [];
if ($this->birth_nation_id == null)
$zzz[] = 'birth_nation_id=' . $this->birth_nation_id;
if ($this->isBirthItaly) {
if ($this->birth_province_id == null)
$zzz[] = 'birth_province_id=' . $this->birth_province_id;
if ($this->birth_city_id == null)
$zzz[] = 'birth_city_id=' . $this->birth_city_id;
}
if ($this->nation_id == null)
$zzz[] = 'nation_id=' . $this->nation_id;
if ($this->isItaly) {
if ($this->province_id == null)
$zzz[] = 'province_id=' . $this->province_id;
if ($this->city_id == null)
$zzz[] = 'city_id=' . $this->city_id;
}
$this->emit('setErrorMsg', $zzz);
}
$this->emit('load-select');
// $this->emit('destroy-data-table');
}
public function checkIsItaly()
{
if ($this->nation_id > 0) {
$n = \App\Models\Nation::findOrFail($this->nation_id);
$this->isItaly = $n->is_italy;
} else {
$this->isItaly = false;
}
}
public function checkIsBirthItaly()
{
if ($this->birth_nation_id > 0) {
$n = \App\Models\Nation::findOrFail($this->birth_nation_id);
$this->isBirthItaly = $n->is_italy;
} else
$this->isBirthItaly = false;
}
public function search()
{
if ($this->searchTxt != '') {
$this->search = $this->searchTxt;
$this->showReset = true;
}
}
public function resetSearch()
{
$this->showReset = false;
$this->searchTxt = '';
$this->search = $this->searchTxt;
}
public function advancedSearch()
{
$this->advanced = true;
}
public function advancedSearchCancel()
{
$this->filterCard = [];
$this->filterCategory = [];
$this->filterCertNormal = 0;
$this->filterCertAgonistic = 0;
$this->filterCertScaduto = 0;
$this->filterCertInScadenza = 0;
$this->advanced = false;
}
public function render()
{
$this->course_names = [];
$allC = \App\Models\Course::where('type', $this->course_course_type)->where('enabled', true)->orderBy('name')->get();
foreach ($allC as $c) {
$cN = $c->name . " (" . $c->year . ")";
if (!in_array($cN, $this->course_names))
$this->course_names[] = $cN;
}
$datas = [];
if (false) {
if (!$this->advanced) {
$this->records = \App\Models\Member::select('id', 'first_name', 'last_name', 'phone')->get();
} else {
$datas = \App\Models\Member::select('members.*')->where('id', '>', 0);
if (sizeof($this->filterCard) > 0) {
$card_ids = \App\Models\MemberCard::whereIn('card_id', $this->filterCard)->pluck('member_id');
$datas = $datas->whereIn('id', $card_ids);
}
if (sizeof($this->filterCategory) > 0) {
$cats_ids = \App\Models\MemberCategory::whereIn('category_id', $this->filterCategory)->pluck('member_id');
$datas = $datas->whereIn('id', $cats_ids);
}
$certs = [];
if ($this->filterCertNormal > 0) {
$normal = \App\Models\MemberCertificate::where('type', 'N')->pluck('member_id');
$datas = $datas->whereIn('id', $normal);;
}
if ($this->filterCertAgonistic > 0) {
$agonistic = \App\Models\MemberCertificate::where('type', 'A')->pluck('member_id');
$datas = $datas->whereIn('id', $agonistic);
}
if ($this->filterCertScaduto > 0) {
$scaduto = \App\Models\MemberCertificate::where('expire_date', '<', date("Y-m-d"))->pluck('member_id');
$datas = $datas->whereIn('id', $scaduto);
}
if ($this->filterCertInScadenza > 0) {
$scaduto = \App\Models\MemberCertificate::whereBetween('expire_date', [date("Y-m-d"), date("Y-m-d", strtotime("+1 month"))])->pluck('member_id');
$datas = $datas->whereIn('id', $scaduto);
}
if (sizeof($certs) > 0) {
$datas = $datas->whereIn('id', $certs);
}
$this->records = $datas->get();
}
foreach ($this->records as $r) {
$r->age = $r->getAge();
$active = $r->isActive();
$r->status = $active["status"];
$r->date = $active["date"];
$r->certificate = $r->hasCertificate()["date"];
$r->state = $r->getStatus()["status"];
}
$this->emit('load-data-table');
}
$this->loadMemberCards();
$this->loadMemberCourses();
$this->loadMemberCategories();
$this->loadMemberCertificates();
$this->courses = \App\Models\Course::select('id', 'name')->where('type', $this->course_course_type)->get();
return view('livewire.member', ['datas' => $datas]);
}
public function updatedCourseCourseId()
{
if ($this->course_course_id > 0) {
$c = \App\Models\Course::findOrFail($this->course_course_id);
$this->course_price = formatPrice($c->price);
$this->course_subscription_price = formatPrice($c->subscription_price);
// $this->course_date_from = $c->date_from;
$this->course_date_from = date('Y-m-d');
$this->course_date_to = $c->date_to;
// Controllo se sono già iscritto la corso
$this->course_exist = \App\Models\MemberCourse::where('course_id', $this->course_course_id)->where('member_id', $this->dataId)->count() > 0;
// Carico gli abbonamenti e i mesi
$period = \Carbon\CarbonPeriod::create($c->date_from, '1 month', $c->date_to);
$this->course_months_list = [];
foreach ($period as $dt) {
$this->course_months_list[] = $dt->format("m");
}
$course_subscription_ids = [];
$this->course_price_list = [];
if ($c->prices != null) {
foreach (json_decode($c->prices) as $z) {
$this->course_price_list[$z->course_subscription_id] = $z->price;
if ($z->price > 0)
$course_subscription_ids[] = $z->course_subscription_id;
}
}
$this->course_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $course_subscription_ids)->where('enabled', true)->orderBy('name', 'asc')->get();
} else {
$this->course_price = 0;
$this->course_subscription_price = 0;
$this->course_exist = false;
}
}
public function updatedSubscriptionId()
{
$this->resetSubscriptionFields();
if ($this->subscription_id > 0 && $this->subscription_id != 'course') {
$subscription = \App\Models\Subscription::findOrFail($this->subscription_id);
$this->subscription_subscription_price = formatPrice($subscription->subscription_price);
// Controllo se l'utente ha già l'abbonamento
// $this->subscription_exist = \App\Models\MemberSubscription::where('subscription_id', $this->subscription_id)->where('member_id', $this->dataId)->count() > 0;
$this->subscription_exist = false;
$subscription_subscription_ids = [];
if ($subscription->prices != null) {
foreach (json_decode($subscription->prices) as $z) {
$subscription_subscription_ids[] = $z->course_subscription_id;
}
}
$this->subscription_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $subscription_subscription_ids)->where('enabled', true)->get();
} else {
$this->subscription_subscription_price = 0;
$this->subscription_exist = false;
}
}
public function updatedSubscriptionCourseSubscriptionId() {
if ($this->subscription_id > 0 && $this->subscription_id != 'course') {
$subscription = \App\Models\Subscription::findOrFail($this->subscription_id);
if ($subscription->prices != null) {
foreach (json_decode($subscription->prices) as $z) {
if ($z->course_subscription_id == $this->subscription_course_subscription_id) {
$this->subscription_price = $z->price;
break;
}
}
}
}
}
public function loadMemberCards()
{
$this->member_cards = \App\Models\MemberCard::where('member_id', $this->dataId)->get();
}
public function loadMemberCourses()
{
$this->member_courses = \App\Models\MemberCourse::where('member_id', $this->dataId)->get();
$this->member_subscriptions = \App\Models\MemberSubscription::join('subscriptions', 'subscription_id', 'subscriptions.id')->where('member_id', $this->dataId)->orderBy('date_from', 'desc')->orderBy('date_to', 'desc')->orderBy('subscriptions.name', 'asc')->get();
}
public function loadMemberCategories()
{
$this->member_categories = [];
$categories = \App\Models\MemberCategory::with('category')->where('member_id', $this->dataId)->get();
foreach ($categories as $category) {
$this->member_categories[$category->category_id] = $category;
}
usort($this->member_categories, function ($a, $b) {
return strcmp($a->category->getTree(), $b->category->getTree());
});
}
public function loadMemberCertificates()
{
$this->member_certificates = \App\Models\MemberCertificate::where('member_id', $this->dataId)->orderBy('expire_date', 'DESC')->get();
}
public function updatedPresenceYearFilter()
{
$this->presenceCourseFilter = '';
$this->loadPresenceCombos();
$this->loadMemberPresences();
}
public function updatedPresenceCourseFilter()
{
$this->loadMemberPresences();
}
public function loadPresenceCombos()
{
$this->presenceYears = [];
$this->presenceCourses = [];
if (!$this->dataId) {
$this->presenceYearFilter = '';
$this->presenceCourseFilter = '';
return;
}
$subscribedCourseIds = \App\Models\MemberCourse::where('member_id', $this->dataId)
->pluck('course_id')
->all();
$makeupCourseIds = \App\Models\Presence::where('member_id', $this->dataId)
->where('status', '<>', 99)
->whereNotNull('motivation_course_id')
->pluck('motivation_course_id')
->all();
$allCourseIds = array_values(array_unique(array_merge($subscribedCourseIds, $makeupCourseIds)));
if (!empty($allCourseIds)) {
$this->presenceYears = \App\Models\Course::whereIn('id', $allCourseIds)
->orderBy('year', 'desc')
->groupBy('year')
->pluck('year')
->map(fn($y) => (string)$y)
->all();
}
if (($this->presenceYearFilter === '' || !in_array((string)$this->presenceYearFilter, $this->presenceYears, true)) && !empty($this->presenceYears)) {
$this->presenceYearFilter = $this->presenceYears[0];
}
if ($this->presenceYearFilter !== '' && !empty($allCourseIds)) {
$this->presenceCourses = \App\Models\Course::whereIn('id', $allCourseIds)
->where('year', $this->presenceYearFilter)
->orderBy('name')
->get(['id', 'name', 'year', 'course_level_id', 'course_type_id', 'course_frequency_id']);
}
$validCourseIds = collect($this->presenceCourses)->pluck('id')->map(fn($id) => (string)$id)->all();
if (($this->presenceCourseFilter === '' || !in_array((string)$this->presenceCourseFilter, $validCourseIds, true)) && !empty($validCourseIds)) {
$this->presenceCourseFilter = $validCourseIds[0];
}
}
public function loadMemberPresences()
{
$mesi = ['Settembre', 'Ottobre', 'Novembre', 'Dicembre', 'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto'];
$valori = array_fill(0, 12, 0);
$monthMap = [9 => 0, 10 => 1, 11 => 2, 12 => 3, 1 => 4, 2 => 5, 3 => 6, 4 => 7, 5 => 8, 6 => 9, 7 => 10, 8 => 11];
// reset output
$this->member_presences = [];
$this->totals = 0;
$this->presenze = 0;
$this->assenze = 0;
$this->annullate = 0;
$this->recuperi = [];
$this->loadPresenceCombos();
if (!$this->dataId || $this->presenceYearFilter === '' || $this->presenceCourseFilter === '') {
$this->emit('load-chart', $mesi, $valori, []);
return;
}
$courseId = (int)$this->presenceCourseFilter;
$chartData = [
0 => ["label" => "Presenze", "backgroundColor" => "#0618be", "data" => array_fill(0, 12, 0), "grouped" => true, "stack" => "chartData", "barThickness" => "flex", "barPercentage" => 0.5, "categoryPercentage" => 0.3],
1 => ["label" => "Assenze", "backgroundColor" => "#ff0000", "data" => array_fill(0, 12, 0), "grouped" => true, "stack" => "chartData", "barThickness" => "flex", "barPercentage" => 0.5, "categoryPercentage" => 0.3],
2 => ["label" => "Annullate", "backgroundColor" => "#808080", "data" => array_fill(0, 12, 0), "grouped" => true, "stack" => "chartData", "barThickness" => "flex", "barPercentage" => 0.5, "categoryPercentage" => 0.3],
];
$course = \App\Models\Course::find($courseId);
$courseWhen = $course?->when;
$calendars = \App\Models\Calendar::whereNull('manual')
->where('course_id', $courseId)
->orderBy('from')
->get(['id', 'from', 'to', 'status']);
$calendarIds = $calendars->pluck('id')->all();
$presencesByCalendar = [];
if (!empty($calendarIds)) {
$presencesByCalendar = \App\Models\Presence::where('member_id', $this->dataId)
->whereIn('calendar_id', $calendarIds)
->with('motivation:id,name,show_in_member_presences')
->get(['calendar_id', 'status', 'motivation_id'])
->keyBy('calendar_id')
->all();
}
$memberCourse = \App\Models\MemberCourse::where('member_id', $this->dataId)
->where('course_id', $courseId)
->first();
$expected = null;
if ($memberCourse) {
$expected = [
'date_from' => $memberCourse->date_from,
'date_to' => $memberCourse->date_to,
'course_when' => $courseWhen,
];
}
$isExpected = function (string $calendarFrom) use ($expected) {
if (!$expected) return false;
if ($calendarFrom < $expected['date_from'] || $calendarFrom > $expected['date_to']) return false;
$days = ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'];
$dow = (int)date('w', strtotime($calendarFrom));
$d = $days[$dow];
$h = date('H:i', strtotime($calendarFrom));
return $this->courseMatchesSlot($expected['course_when'] ?? null, $d, $h);
};
if ($expected) {
foreach ($calendars as $calendar) {
if (!$isExpected($calendar->from)) continue;
$idxMonth = $monthMap[(int)date('n', strtotime($calendar->from))] ?? null;
$presence = $presencesByCalendar[$calendar->id] ?? null;
$calendarCancelled = ((int)$calendar->status === 99);
$presenceCancelled = ($presence && (int)$presence->status === 99);
$statusHtml = '';
$motivationName = null;
if ($calendarCancelled || $presenceCancelled) {
$statusHtml = "Annullata";
$this->annullate++;
if ($idxMonth !== null) $chartData[2]['data'][$idxMonth]++;
} elseif ($presence) {
$statusHtml = "Presenza";
$this->presenze++;
if ($idxMonth !== null) {
$valori[$idxMonth]++;
$chartData[0]['data'][$idxMonth]++;
}
if ($presence->motivation && $presence->motivation->show_in_member_presences) {
$motivationName = ucfirst($presence->motivation->name);
$this->recuperi[$motivationName] = ($this->recuperi[$motivationName] ?? 0) + 1;
}
} else {
if (date('Ymd') > date('Ymd', strtotime($calendar->from))) {
$statusHtml = "Assenza";
$this->assenze++;
if ($idxMonth !== null) $chartData[1]['data'][$idxMonth]++;
} else {
$statusHtml = "";
}
}
$this->member_presences[] = [
'calendar_id' => $calendar->id,
'from' => $calendar->from,
'to' => $calendar->to,
'status' => $statusHtml,
'motivation' => $motivationName,
];
}
}
$makeups = \App\Models\Presence::where('member_id', $this->dataId)
->where('status', '<>', 99)
->where('motivation_course_id', $courseId)
->with([
'calendar:id,from,to,status',
'motivation:id,name,show_in_member_presences',
])
->get(['calendar_id', 'status', 'motivation_id', 'motivation_course_id']);
$alreadyCalendar = array_flip(array_column($this->member_presences, 'calendar_id'));
foreach ($makeups as $p) {
if (!$p->calendar) continue;
if (isset($alreadyCalendar[$p->calendar_id])) continue;
if (!$p->motivation || !$p->motivation->show_in_member_presences) continue;
$idxMonth = $monthMap[(int)date('n', strtotime($p->calendar->from))] ?? null;
if ((int)$p->calendar->status === 99) {
$statusHtml = "Annullata";
$this->annullate++;
if ($idxMonth !== null) $chartData[2]['data'][$idxMonth]++;
} else {
$statusHtml = "Presenza";
$this->presenze++;
if ($idxMonth !== null) {
$valori[$idxMonth]++;
$chartData[0]['data'][$idxMonth]++;
}
$mot = ucfirst($p->motivation->name);
$this->recuperi[$mot] = ($this->recuperi[$mot] ?? 0) + 1;
}
$this->member_presences[] = [
'calendar_id' => $p->calendar->id,
'from' => $p->calendar->from,
'to' => $p->calendar->to,
'status' => $statusHtml,
'motivation' => $p->motivation->name,
];
}
usort($this->member_presences, fn($a, $b) => strcmp($a['from'], $b['from']));
$this->emit('load-chart', $mesi, $valori, $chartData);
}
private function courseMatchesSlot(?string $whenJson, string $day, string $hhmm): bool
{
if (!$whenJson) return false;
$when = json_decode($whenJson, true);
if (!is_array($when)) return false;
foreach ($when as $period) {
$days = $period['day'] ?? [];
$from = $period['from'] ?? null;
if (!$from || empty($days)) continue;
$from = substr((string)$from, 0, 5);
if ($from === $hhmm && in_array($day, $days, true)) {
return true;
}
}
return false;
}
public function showDetailF($id)
{
if (!isset($_GET["from"]) && $this->from == '')
$this->from = 'members';
$this->currentMember = \App\Models\Member::findOrFail($id);
$categories = [];
foreach ($this->currentMember->categories as $category) {
$categories[$category->category_id] = $category;
}
usort($categories, function ($a, $b) {
return strcmp($a->category->getTree(), $b->category->getTree());
});
$this->currentMember->categories = $categories;
$this->currentStatus = $this->currentMember->getStatus();
$this->showDetail = true;
}
public function add()
{
//$this->from = 'members';
$this->emit('load-select');
$this->emit('hide-search');
$this->showDetail = false;
$this->resetFields();
$this->add = true;
$this->update = false;
$this->emit('setEdit', true);
$this->emit('setEditCorso', false);
$this->dispatchBrowserEvent('scroll-to-top');
}
public function store($close)
{
$this->isSaving = true;
$this->emit('load-select');
$this->emit('goToTop');
$rules = [
'first_name' => 'required',
'last_name' => 'required',
'birth_nation_id' => 'required',
// 'email' => 'required',
// 'phone' => 'required',
'address' => 'required',
'zip_code' => 'required',
'nation_id' => 'required',
'birth_date' => 'before_or_equal:today',
'gender' => 'required'
];
if ($this->isBirthItaly) {
$rules['birth_province_id'] = 'required';
$rules['birth_city_id'] = 'required';
$rules['fiscal_code'] = 'required';
} else {
$rules['birth_place'] = 'required';
}
if ($this->isItaly) {
$rules['province_id'] = 'required';
$rules['city_id'] = 'required';
}
$zzz = [];
if ($this->birth_nation_id == null)
$zzz[] = 'birth_nation_id=' . $this->birth_nation_id;
if ($this->isBirthItaly) {
if ($this->birth_province_id == null)
$zzz[] = 'birth_province_id=' . $this->birth_province_id;
if ($this->birth_city_id == null)
$zzz[] = 'birth_city_id=' . $this->birth_city_id;
}
if ($this->nation_id == null)
$zzz[] = 'nation_id=' . $this->nation_id;
if ($this->isItaly) {
if ($this->province_id == null)
$zzz[] = 'province_id=' . $this->province_id;
if ($this->city_id == null)
$zzz[] = 'city_id=' . $this->city_id;
}
$this->emit('setErrorMsg', $zzz);
if (!empty($this->fiscal_code)) {
$existingMember = \App\Models\Member::where('fiscal_code', $this->fiscal_code)->first();
if ($existingMember) {
$this->already_existing = true;
$this->emit('focus-error-field', 'fiscal_code');
return;
}
}
if ($this->under18) {
$rules['father_name'] = 'required_without:mother_name';
$rules['father_email'] = 'required_without:mother_email|email';
$rules['father_fiscal_code'] = 'required_without:mother_fiscal_code';
$rules['mother_name'] = 'required_without:father_name';
$rules['mother_email'] = 'required_without:father_email|email';
$rules['mother_fiscal_code'] = 'required_without:father_fiscal_code';
} else {
$rules['email'] = 'required';
$rules['phone'] = 'required';
}
$std_rules = $rules;
// $rules = [
// 'first_name' => 'required',
// 'last_name' => 'required'
// ];
try {
$this->validate($rules);
} catch (\Illuminate\Validation\ValidationException $e) {
$this->isSaving = false;
$errorFields = array_keys($e->errors());
if (!empty($errorFields)) {
$this->emit('focus-error-field', $errorFields[0]);
}
Log::error('Validation failed', ['errors' => $e->errors()]);
return;
}
try {
$imageName = '';
if ($this->image) {
$imageName = md5($this->image . microtime()) . '.' . $this->image->extension();
$this->image->storeAs('public', $imageName);
}
$docs = implode("|", $this->document_files);
$father_docs = implode("|", $this->father_document_files);
$mother_docs = implode("|", $this->mother_document_files);
$to_complete = false;
// try {
// $this->validate($std_rules);
// } catch(\Illuminate\Validation\ValidationException $e) {
// $to_complete = true;
// } catch (\Exception $e) {
// $to_complete = true;
// }
$member = \App\Models\Member::create([
'first_name' => strtoupper($this->first_name),
'last_name' => strtoupper($this->last_name),
'status' => $this->status,
'birth_city_id' => $this->birth_city_id > 0 ? $this->birth_city_id : null,
'birth_province_id' => $this->birth_province_id > 0 ? $this->birth_province_id : null,
'birth_nation_id' => $this->birth_nation_id > 0 ? $this->birth_nation_id : null,
'birth_date' => $this->birth_date,
'birth_place' => $this->birth_place,
'father_name' => $this->father_name,
'mother_name' => $this->mother_name,
'father_email' => strtolower($this->father_email),
'mother_email' => strtolower($this->mother_email),
'father_phone' => $this->father_phone,
'mother_phone' => $this->mother_phone,
'father_fiscal_code' => $this->father_fiscal_code,
'mother_fiscal_code' => $this->mother_fiscal_code,
'father_doc_number' => $this->father_doc_number,
'father_doc_type' => $this->father_doc_type,
'mother_doc_number' => $this->mother_doc_number,
'mother_doc_type' => $this->mother_doc_type,
'document_type' => $this->document_type,
'document_number' => $this->document_number,
'document_from' => $this->document_from,
'document_expire_date' => $this->document_expire_date,
'document_files' => $docs,
'mother_document_files' => $mother_docs,
'father_document_files' => $father_docs,
'gender' => $this->gender,
'no_send_mail' => $this->no_send_mail,
'exclude_from_records' => $this->exclude_from_records,
'fiscal_code' => $this->fiscal_code,
'address' => $this->address,
'zip_code' => $this->zip_code,
'nation_id' => $this->nation_id > 0 ? $this->nation_id : null,
'province_id' => $this->province_id > 0 ? $this->province_id : null,
'city_id' => $this->city_id > 0 ? $this->city_id : null,
'phone' => $this->phone,
'phone2' => $this->phone2,
'phone3' => $this->phone3,
'email' => strtolower($this->email),
'image' => $imageName,
'to_complete' => $to_complete,
'enabled' => $this->enabled
]);
$this->fileService->createMemberFolders($member->id);
if ($this->image) {
$s3ImagePath = $this->fileService->uploadProfileImage($this->image, $member->id);
$member->update(['image' => $s3ImagePath]);
}
$this->migrateTemporaryFiles($member->id);
session()->flash('success, Tesserato creato');
updateMemberData($member->id);
$this->resetFields();
if ($close) {
$this->add = false;
return redirect()->to('/members');
} else {
$this->edit($member->id);
$this->emit('saved-and-continue', $this->type);
$this->dispatchBrowserEvent('scroll-to-top');
}
$this->emit('setEdit', false);
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
private function migrateTemporaryFiles($memberId)
{
try {
$updatedPaths = [];
// Migrate document files
$newDocumentFiles = [];
foreach ($this->document_files as $filePath) {
if (strpos($filePath, '/members/') === false) {
// This is a temporary local file, move to S3
$localPath = storage_path('app/public/' . $filePath);
if (file_exists($localPath)) {
$uploadedFile = new \Illuminate\Http\UploadedFile(
$localPath,
basename($filePath),
mime_content_type($localPath),
filesize($localPath),
0,
true
);
$s3Path = $this->fileService->uploadDocument($uploadedFile, $memberId, 'self');
$newDocumentFiles[] = $s3Path;
// Delete temporary file
unlink($localPath);
}
} else {
$newDocumentFiles[] = $filePath;
}
}
if (!empty($newDocumentFiles)) {
$updatedPaths['document_files'] = implode('|', $newDocumentFiles);
}
// Migrate father document files
$newFatherFiles = [];
foreach ($this->father_document_files as $filePath) {
if (strpos($filePath, '/members/') === false) {
$localPath = storage_path('app/public/' . $filePath);
if (file_exists($localPath)) {
$uploadedFile = new \Illuminate\Http\UploadedFile(
$localPath,
basename($filePath),
mime_content_type($localPath),
filesize($localPath),
0,
true
);
$s3Path = $this->fileService->uploadDocument($uploadedFile, $memberId, 'father');
$newFatherFiles[] = $s3Path;
unlink($localPath);
}
} else {
$newFatherFiles[] = $filePath;
}
}
if (!empty($newFatherFiles)) {
$updatedPaths['father_document_files'] = implode('|', $newFatherFiles);
}
// Migrate mother document files
$newMotherFiles = [];
foreach ($this->mother_document_files as $filePath) {
if (strpos($filePath, '/members/') === false) {
$localPath = storage_path('app/public/' . $filePath);
if (file_exists($localPath)) {
$uploadedFile = new \Illuminate\Http\UploadedFile(
$localPath,
basename($filePath),
mime_content_type($localPath),
filesize($localPath),
0,
true
);
$s3Path = $this->fileService->uploadDocument($uploadedFile, $memberId, 'mother');
$newMotherFiles[] = $s3Path;
unlink($localPath);
}
} else {
$newMotherFiles[] = $filePath;
}
}
if (!empty($newMotherFiles)) {
$updatedPaths['mother_document_files'] = implode('|', $newMotherFiles);
}
// Update member with new S3 paths
if (!empty($updatedPaths)) {
\App\Models\Member::whereId($memberId)->update($updatedPaths);
}
} catch (\Exception $e) {
Log::error('Error migrating temporary files', [
'member_id' => $memberId,
'error' => $e->getMessage()
]);
}
}
public function duplicate($id)
{
$member = \App\Models\Member::findOrFail($id);
$newMember = $member->replicate();
$newMember->save();
$this->edit($newMember->id);
}
public function edit($id)
{
if (!isset($_GET["from"]) && $this->from == '')
$this->from = 'members';
$this->showDetail = false;
$this->emit('setEdit', true);
$this->emit('setEditCorso', false);
$this->emit('hide-search');
try {
$member = \App\Models\Member::findOrFail($id);
if (!$member) {
session()->flash('error', 'Tesserato non trovato');
} else {
$this->first_name = $member->first_name;
$this->last_name = $member->last_name;
$this->status = $member->status;
$this->birth_city_id = $member->birth_city_id;
$this->birth_province_id = $member->birth_province_id;
$this->birth_nation_id = $member->birth_nation_id;
$this->birth_date = $member->birth_date;
$this->birth_place = $member->birth_place;
$this->father_name = $member->father_name;
$this->mother_name = $member->mother_name;
$this->father_email = strtolower($member->father_email);
$this->mother_email = strtolower($member->mother_email);
$this->father_phone = $member->father_phone;
$this->mother_phone = $member->mother_phone;
$this->father_fiscal_code = $member->father_fiscal_code;
$this->mother_fiscal_code = $member->mother_fiscal_code;
$this->father_doc_number = $member->father_doc_number;
$this->mother_doc_number = $member->mother_doc_number;
$this->father_doc_type = $member->father_doc_type;
$this->mother_doc_type = $member->mother_doc_type;
$this->father_document_files = explode("|", $member->father_document_files);
$this->mother_document_files = explode("|", $member->mother_document_files);
$this->document_type = $member->document_type;
$this->document_number = $member->document_number;
$this->document_from = $member->document_from;
$this->document_expire_date = $member->document_expire_date;
$this->document_files = explode("|", $member->document_files);
$this->gender = $member->gender;
$this->no_send_mail = $member->no_send_mail;
$this->exclude_from_records = $member->exclude_from_records;
$this->fiscal_code = $member->fiscal_code;
$this->address = $member->address;
$this->zip_code = $member->zip_code;
$this->nation_id = $member->nation_id;
$this->province_id = $member->province_id;
$this->city_id = $member->city_id;
$this->phone = $member->phone;
$this->phone2 = $member->phone2;
$this->phone3 = $member->phone3;
$this->email = strtolower($member->email);
$this->image_old = $member->image;
$this->enabled = $member->enabled;
$this->dataId = $member->id;
$this->active = $member->getStatus();
$this->hasCertificate = $member->hasCertificate()["status"];
$this->money = $member->getMoney();
$this->checkIsBirthItaly();
$date1 = new DateTime($this->birth_date);
$date2 = new DateTime("now");
$interval = $date1->diff($date2);
$this->age = $interval->y . " anni";
$this->under18 = $interval->y < 18;
$this->update = true;
$this->add = false;
$this->emit('setIds', $this->nation_id, $this->birth_nation_id);
$this->emit('load-select');
$this->emit('load-provinces', $this->nation_id, 'provinceClass');
$this->emit('load-provinces', $this->birth_nation_id, 'provinceBirthClass');
$this->emit('load-cities', $this->province_id, 'cityClass');
$this->emit('load-cities', $this->birth_province_id, 'cityBirthClass');
$this->dispatchBrowserEvent('scroll-to-top');
}
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function updateAAA($close)
{
$this->emit('goToTop');
$this->isSaving = true;
$this->emit('load-select');
$rules = [
'first_name' => 'required',
'last_name' => 'required',
// 'email' => 'required',
// 'phone' => 'required',
'birth_nation_id' => 'required',
'address' => 'required',
'zip_code' => 'required',
'nation_id' => 'required',
'birth_date' => 'before_or_equal:today'
];
if ($this->isBirthItaly) {
$rules['birth_province_id'] = 'required';
$rules['birth_city_id'] = 'required';
$rules['fiscal_code'] = 'required';
} else {
$rules['birth_place'] = 'required';
}
Log::info('isItaly', ['isItaly' => $this->isItaly]);
$this->isItaly = $this->checkIsItaly();
if ($this->isItaly) {
$rules['province_id'] = 'required';
$rules['city_id'] = 'required';
}
$zzz = [];
if ($this->birth_nation_id == null)
$zzz[] = 'birth_nation_id=' . $this->birth_nation_id;
if ($this->isBirthItaly) {
if ($this->birth_province_id == null)
$zzz[] = 'birth_province_id=' . $this->birth_province_id;
if ($this->birth_city_id == null)
$zzz[] = 'birth_city_id=' . $this->birth_city_id;
}
if ($this->nation_id == null)
$zzz[] = 'nation_id=' . $this->nation_id;
if ($this->isItaly) {
if ($this->province_id == null)
$zzz[] = 'province_id=' . $this->province_id;
if ($this->city_id == null)
$zzz[] = 'city_id=' . $this->city_id;
}
$this->emit('setErrorMsg', $zzz);
if ($this->under18) {
$rules['father_name'] = 'required_without:mother_name';
$rules['father_email'] = 'required_without:mother_email|email';
$rules['father_fiscal_code'] = 'required_without:mother_fiscal_code';
$rules['mother_name'] = 'required_without:father_name';
$rules['mother_email'] = 'required_without:father_email|email';
$rules['mother_fiscal_code'] = 'required_without:father_fiscal_code';
} else {
$rules['email'] = 'required';
$rules['phone'] = 'required';
}
$std_rules = $rules;
// $rules = [
// 'first_name' => 'required',
// 'last_name' => 'required'
// ];
try {
$this->validate($rules);
} catch (\Illuminate\Validation\ValidationException $e) {
$this->isSaving = false;
$errorFields = array_keys($e->errors());
if (!empty($errorFields)) {
$this->emit('focus-error-field', $errorFields[0]);
}
Log::error('Validation failed', ['errors' => $e->errors()]);
return;
}
try {
$imagePath = $this->image_old; // Keep existing if no new image
if ($this->image) {
$imagePath = $this->fileService->uploadProfileImage($this->image, $this->dataId);
}
$docs = implode("|", $this->document_files);
$father_docs = implode("|", $this->father_document_files);
$mother_docs = implode("|", $this->mother_document_files);
$to_complete = false;
// try {
// $this->validate($std_rules);
// } catch(\Illuminate\Validation\ValidationException $e) {
// $to_complete = true;
// } catch (Exception $e) {
// $to_complete = true;
// }
\App\Models\Member::whereId($this->dataId)->update([
'first_name' => strtoupper($this->first_name),
'last_name' => strtoupper($this->last_name),
'status' => $this->status,
'birth_city_id' => $this->birth_city_id > 0 ? $this->birth_city_id : null,
'birth_province_id' => $this->birth_province_id > 0 ? $this->birth_province_id : null,
'birth_nation_id' => $this->birth_nation_id > 0 ? $this->birth_nation_id : null,
'birth_date' => $this->birth_date,
'birth_place' => $this->birth_place,
'father_name' => $this->father_name,
'mother_name' => $this->mother_name,
'father_email' => strtolower($this->father_email),
'mother_email' => strtolower($this->mother_email),
'father_phone' => $this->father_phone,
'mother_phone' => $this->mother_phone,
'father_fiscal_code' => $this->father_fiscal_code,
'mother_fiscal_code' => $this->mother_fiscal_code,
'father_doc_number' => $this->father_doc_number,
'father_doc_type' => $this->father_doc_type,
'mother_doc_number' => $this->mother_doc_number,
'mother_doc_type' => $this->mother_doc_type,
'father_document_files' => $father_docs,
'mother_document_files' => $mother_docs,
'document_type' => $this->document_type,
'document_number' => $this->document_number,
'document_from' => $this->document_from,
'document_expire_date' => $this->document_expire_date,
'document_files' => $docs,
'gender' => $this->gender,
'no_send_mail' => $this->no_send_mail,
'exclude_from_records' => $this->exclude_from_records,
'fiscal_code' => $this->fiscal_code,
'address' => $this->address,
'zip_code' => $this->zip_code,
'nation_id' => $this->nation_id > 0 ? $this->nation_id : null,
'province_id' => $this->province_id > 0 ? $this->province_id : null,
'city_id' => $this->city_id > 0 ? $this->city_id : null,
'image' => $imagePath,
'phone' => $this->phone,
'phone2' => $this->phone2,
'phone3' => $this->phone3,
'email' => strtolower($this->email),
'to_complete' => $to_complete,
'enabled' => $this->enabled
]);
updateMemberData($this->dataId);
session()->flash('success', 'Tesserato aggiornato');
if ($close) {
$this->resetFields();
$this->update = false;
return redirect()->to('/members');
} else {
$this->emit('saved-and-continue', $this->type);
$this->dispatchBrowserEvent('scroll-to-top');
}
$this->emit('setEdit', false);
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function cancel()
{
$this->add = false;
$this->update = false;
$this->showDetail = false;
$this->resetFields();
$this->emit('setEdit', false);
//$this->emit('setEditCorso', false);
$this->emit('reload');
}
public function delete($id)
{
try {
\App\Models\Member::find($id)->delete();
session()->flash('success', "Tesserato eliminato");
$this->emit('reload');
} catch (\Exception $e) {
session()->flash('error', 'Errore (' . $e->getMessage() . ')');
}
}
public function checkUncheckAll()
{
if (!$this->checkedAll) {
$this->multipleIds = array();
} else {
foreach ($this->records as $r) {
$this->multipleIds[] = $r->id;
}
}
}
public function multipleDelete()
{
try {
foreach ($this->multipleIds as $id) {
\App\Models\Member::find($id)->delete();
}
} catch (\Exception $e) {
session()->flash('error', 'Errore (' . $e->getMessage() . ')');
}
$this->multipleAction = '';
}
// Card
public function addCard()
{
$this->resetCardFields();
$this->addCard = true;
$this->updateCard = false;
}
public function storeCard()
{
$this->validate(['card_card_id' => 'required']);
try {
// in base alla card selezionata calcolo la scadenza
$expire_date = null;
if ($this->card_date != '') {
$y = date("Y", strtotime($this->card_date));
$card = \App\Models\Card::findOrFail($this->card_card_id);
if ($card->next_day_expire > 0 && $card->next_month_expire > 0) {
$m = strlen($card->next_month_expire) == 1 ? ('0' . $card->next_month_expire) : $card->next_month_expire;
if (date("md", strtotime($this->card_date)) > ($m . $card->next_day_expire))
$y += 1;
$next_exp = date($y . "-" . $m . "-" . $card->next_day_expire);
if ($next_exp > $this->card_date) {
$expire_date = $next_exp;
} else
$expire_date = date($y . "-" . $card->next_month_expire . "-" . $card->next_day_expire, strtotime(' + 1 years'));
} else {
if ($card->one_year_expire) {
$expire_date = date("Y-m-d", strtotime($this->card_date . ' + 1 years'));
}
}
}
\App\Models\MemberCard::create([
'member_id' => $this->dataId,
'card_id' => $this->card_card_id,
'number' => $this->card_number,
'date' => $this->card_date,
'accept_date' => $this->card_accept_date != '' ? $this->card_accept_date : $this->card_date,
'expire_date' => $expire_date,
'status' => $this->card_status,
'discipline1_id' => $this->card_discipline1_id,
'discipline2_id' => $this->card_discipline2_id,
'discipline3_id' => $this->card_discipline3_id,
]);
updateMemberData($this->dataId);
session()->flash('success, Tesserato creato');
$this->resetCardFields();
$this->addCard = false;
$this->loadMemberCards();
// TODO $this->checkCourseAvailability();
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function editCard($id)
{
try {
$memberCard = \App\Models\MemberCard::findOrFail($id);
if (!$memberCard) {
session()->flash('error', 'Tesserato non trovato');
} else {
$this->card_card_id = $memberCard->card_id;
$this->card_number = $memberCard->number;
$this->card_date = $memberCard->date;
$this->card_accept_date = $memberCard->accept_date;
$this->card_status = $memberCard->status;
$this->card_discipline1_id = $memberCard->discipline1_id;
$this->card_discipline2_id = $memberCard->discipline2_id;
$this->card_discipline3_id = $memberCard->discipline3_id;
$this->cardDataId = $memberCard->id;
$this->updateCard = true;
$this->addCard = false;
}
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function updateCard()
{
$this->validate(['card_card_id' => 'required']);
try {
Log::info('Starting card update', [
'member_id' => $this->dataId,
'card_id' => $this->card_card_id,
'card_number' => $this->card_number
]);
$expire_date = null;
if ($this->card_date != '') {
$card = \App\Models\Card::findOrFail($this->card_card_id);
Log::info('Card details', [
'card_id' => $card->id,
'next_day_expire' => $card->next_day_expire,
'next_month_expire' => $card->next_month_expire,
'one_year_expire' => $card->one_year_expire
]);
if ($card->next_day_expire > 0 && $card->next_month_expire > 0) {
$y = date("Y", strtotime($this->card_date));
$m = strlen($card->next_month_expire) == 1 ? ('0' . $card->next_month_expire) : $card->next_month_expire;
$d = strlen($card->next_day_expire) == 1 ? ('0' . $card->next_day_expire) : $card->next_day_expire;
$next_exp = $y . "-" . $m . "-" . $d;
// Format dates for comparison
$input_date_obj = new \DateTime($this->card_date);
$next_exp_obj = new \DateTime($next_exp);
if ($next_exp_obj > $input_date_obj) {
$expire_date = $next_exp;
} else {
// Add 1 year to the expiration date if the input date is after the expiration date
$next_exp_obj->modify('+1 year');
$expire_date = $next_exp_obj->format('Y-m-d');
}
Log::info('Calculated expiration date (next_day_expire/next_month_expire rule)', [
'input_date' => $this->card_date,
'next_exp' => $next_exp,
'expire_date' => $expire_date,
'comparison' => ($next_exp_obj > $input_date_obj) ? 'next_exp is after input_date' : 'next_exp is before or equal to input_date'
]);
} else {
if ($card->one_year_expire) {
$expire_date = date("Y-m-d", strtotime($this->card_date . ' + 1 years'));
Log::info('Calculated expiration date (one_year_expire rule)', [
'input_date' => $this->card_date,
'expire_date' => $expire_date
]);
}
}
}
Log::info('Updating member card', [
'card_id' => $this->cardDataId,
'member_id' => $this->dataId,
'card_number' => $this->card_number,
'date' => $this->card_date,
'expire_date' => $expire_date,
'status' => $this->card_status
]);
\App\Models\MemberCard::whereId($this->cardDataId)->update([
'member_id' => $this->dataId,
'card_id' => $this->card_card_id,
'number' => $this->card_number,
'date' => $this->card_date,
'accept_date' => $this->card_accept_date != '' ? $this->card_accept_date : $this->card_date,
'expire_date' => $expire_date,
'status' => $this->card_status,
'discipline1_id' => $this->card_discipline1_id,
'discipline2_id' => $this->card_discipline2_id,
'discipline3_id' => $this->card_discipline3_id,
]);
updateMemberData($this->dataId);
Log::info('Card updated successfully', [
'card_id' => $this->cardDataId,
'member_id' => $this->dataId
]);
session()->flash('success', 'Tesserato aggiornato');
$this->resetCardFields();
$this->updateCard = false;
$this->loadMemberCards();
// TODO $this->checkCourseAvailability();
} catch (\Exception $ex) {
Log::error('Error updating card', [
'card_id' => $this->cardDataId,
'member_id' => $this->dataId,
'error_message' => $ex->getMessage(),
'error_trace' => $ex->getTraceAsString()
]);
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function cancelCard()
{
$this->addCard = false;
$this->updateCard = false;
$this->resetCardFields();
}
public function deleteCard($id)
{
try {
\App\Models\MemberCard::find($id)->delete();
session()->flash('success', "Tesserato eliminato");
} catch (\Exception $e) {
session()->flash('error', 'Errore (' . $e->getMessage() . ')');
}
}
public function addCourse()
{
$this->resetCourseFields();
$this->addCourse = true;
$this->updateCourse = false;
$this->emit('setEditCorso', true);
}
public function storeCourse()
{
$this->validate(['course_course_id' => 'required']);
try {
$mc = new \App\Models\MemberCourse();
$mc->member_id = $this->dataId;
$mc->course_id = $this->course_course_id;
$mc->date_from = $this->course_date_from;
$mc->date_to = $this->course_date_to;
$mc->course_subscription_id = $this->course_course_subscription_id;
$mc->status = $this->course_status;
$mc->subscribed = false;
$mc->price = currencyToDouble($this->course_price);
$mc->subscription_price = currencyToDouble($this->course_subscription_price);
$mc->notes = $this->course_note;
$mc->months = json_encode($this->course_months);
$mc->when = json_encode($this->course_when);
$mc->save();
// Se il corso ha associato una categoria iscrivo anche al gruppo
if ($this->course_course_id) {
try {
$c = \App\Models\Course::findOrFail($this->course_course_id);
if ($c) {
if ($c->category_id > 0) {
if (!\App\Models\MemberCategory::where('member_id', $this->dataId)->where('category_id', $c->category_id)->first()) {
\App\Models\MemberCategory::create([
'member_id' => $this->dataId,
'category_id' => $c->category_id,
'date' => \Carbon\Carbon::now()
]);
}
}
}
} catch (\Throwable $e) {
}
}
// Creo i pagamenti in base alla tipologia
if ($this->course_course_subscription_id) {
try {
$r = \App\Models\CourseSubscription::findOrFail($this->course_course_subscription_id);
} catch (\Throwable $e) {
$r = new \App\Models\CourseSubscription();
}
}
$start = $this->course_date_from;
// Creo il pagamento per l'iscrizione
$rate = new \App\Models\Rate();
$rate->member_id = $this->dataId;
$rate->member_course_id = $mc->id;
$rate->course_subscription_id = null;
$rate->price = currencyToDouble($this->course_subscription_price);
$rate->date = $start;
$rate->months = json_encode([]);
$rate->note = '';
$rate->status = 0;
$rate->is_subscription = true;
$rate->save();
$go = true;
while ($go) {
$mms = [];
$mms[] = date("n", strtotime($start));
for ($jj = 1; $jj < $r->months; $jj++) {
if (date('Ymd', strtotime("+" . $jj . " months", strtotime($start))) < date("Ymd", strtotime($this->course_date_to))) {
$mms[] = date('n', strtotime("+" . $jj . " months", strtotime($start)));
} else {
break;
}
}
$rate = new \App\Models\Rate();
$rate->member_id = $this->dataId;
$rate->member_course_id = $mc->id;
$rate->course_subscription_id = $this->course_course_subscription_id;
$rate->price = currencyToDouble($this->course_price);
$rate->date = $start;
$rate->months = json_encode($mms);
$rate->note = '';
$rate->status = 0;
$rate->save();
$start = date('Y-m-d', strtotime("+" . $r->months . " months", strtotime($start)));
if ($start > $this->course_date_to || $r->months == 0) {
$go = false;
break;
}
}
session()->flash('success, Corso creato');
$this->resetCourseFields();
$this->addCourse = false;
$this->emit('setEditCorso', false);
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function editCourse($id)
{
try {
$memberCourse = \App\Models\MemberCourse::findOrFail($id);
if (!$memberCourse) {
session()->flash('error', 'Corso non trovato');
} else {
$this->course_course_id = $memberCourse->course_id;
// Carico i dati relativi alla struttura ad albero
$c = \App\Models\Course::findOrFail($this->course_course_id);
$this->course_name = $c->name . " (" . $c->year . ")";
$this->course_level_id = $c->course_level_id;
$this->course_course_type = $c->type;
$this->course_type_id = $c->course_type_id;
$this->course_frequency_id = $c->course_frequency_id;
$all = \App\Models\Course::where('name', 'like', '%' . $c->name . "%")->where('enabled', true)->get();
foreach ($all as $a) {
$levels_ids[] = $a->course_level_id;
}
$this->course_levels = \App\Models\CourseLevel::select('*')->where('enabled', true)->whereIn('id', $levels_ids)->get();
$all = \App\Models\Course::where('name', 'like', '%' . $c->name . "%")->where('enabled', true)->where('course_level_id', $this->course_level_id)->get();
foreach ($all as $a) {
$types_ids[] = $a->course_type_id;
}
// $this->course_types = \App\Models\CourseType::select('*')->where('enabled', true)->whereIn('id', $types_ids)->get();
$frequencies_ids = [];
$all = \App\Models\Course::where('name', 'like', '%' . $c->name . "%")->where('enabled', true)->where('course_level_id', $this->course_level_id)->where('course_type_id', $this->course_type_id)->get();
foreach ($all as $a) {
$frequencies_ids[] = $a->course_frequency_id;
}
$this->course_frequencies = \App\Models\CourseFrequency::select('*')->where('enabled', true)->whereIn('id', $frequencies_ids)->get();
$this->course_when = array();
$this->course_date_from = $memberCourse->date_from;
$this->course_date_to = $memberCourse->date_to;
foreach (json_decode($memberCourse->when) as $z) {
$this->course_when[] = array("day" => $z->day, "from" => $z->from, "to" => $z->to);
}
//$this->course_when = json_decode($memberCourse->when);
$this->course_course_subscription_id = $memberCourse->course_subscription_id;
$this->course_status = $memberCourse->status;
$this->course_subscribed = $memberCourse->subscribed == 1 ? true : false;
$this->course_price = formatPrice($memberCourse->price);
$this->course_subscription_price = formatPrice($memberCourse->subscription_price);
$this->course_note = $memberCourse->notes;
foreach (json_decode($memberCourse->months) as $z) {
$this->course_months[] = array("m" => $z->m, "status" => $z->status);
}
$course_subscription_ids = [];
$this->course_price_list = [];
if ($c->prices != null) {
foreach (json_decode($c->prices) as $z) {
$this->course_price_list[$z->course_subscription_id] = $z->price;
if ($z->price > 0)
$course_subscription_ids[] = $z->course_subscription_id;
}
}
$this->course_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $course_subscription_ids)->where('enabled', true)->orderBy('name', 'asc')->get();
$this->courseDataId = $memberCourse->id;
$this->updateCourse = true;
$this->addCourse = false;
$this->subscription_id = 'course';
$this->emit('setEditCorso', true);
}
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function updateCourse()
{
//$this->validate();
$this->validate(['course_course_id' => 'required']);
try {
\App\Models\MemberCourse::whereId($this->courseDataId)->update([
'member_id' => $this->dataId,
'course_id' => $this->course_course_id,
'date_from' => $this->course_date_from,
'date_to' => $this->course_date_to,
'course_subscription_id' => $this->course_course_subscription_id,
'status' => $this->course_status,
'price' => currencyToDouble($this->course_price),
'subscription_price' => currencyToDouble($this->course_subscription_price),
'notes' => $this->course_note,
'months' => json_encode($this->course_months),
'when' => json_encode($this->course_when)
]);
session()->flash('success', 'Corso aggiornato');
$this->resetCourseFields();
$this->updateCourse = false;
$this->emit('setEditCorso', false);
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function cancelCourse()
{
$this->addCourse = false;
$this->updateCourse = false;
$this->emit('setEditCorso', false);
$this->resetCourseFields();
}
public function deleteCourse($id)
{
try {
$member_course = \App\Models\MemberCourse::find($id);
$category = \App\Models\Course::findOrFail($member_course->course_id);
if ($category) {
if ($category->category_id > 0) {
\App\Models\MemberCategory::where('member_id', $this->dataId)->where('category_id', $category->category_id)->delete();
}
}
$member_course->delete();
session()->flash('success', "Corso eliminato");
} catch (\Exception $e) {
session()->flash('error', 'Errore (' . $e->getMessage() . ')');
}
}
public function storeSubscription()
{
$this->validate(['subscription_id' => 'required']);
try {
$ms = new \App\Models\MemberSubscription();
$ms->member_id = $this->dataId;
$ms->subscription_id = $this->subscription_id;
$ms->date_from = $this->subscription_date_from;
$ms->date_to = $this->subscription_date_to;
$ms->course_subscription_id = $this->subscription_course_subscription_id;
$ms->price = currencyToDouble($this->subscription_price);
$ms->subscription_price = currencyToDouble($this->subscription_subscription_price);
$ms->notes = $this->subscription_notes;
$ms->save();
// Creo i pagamenti in base alla tipologia
if ($this->subscription_course_subscription_id) {
try {
$r = \App\Models\CourseSubscription::findOrFail($this->subscription_course_subscription_id);
} catch (\Throwable $e) {
$r = new \App\Models\CourseSubscription();
}
}
$start = $this->subscription_date_from;
// Creo il pagamento per l'iscrizione
$rate = new \App\Models\Rate();
$rate->member_id = $this->dataId;
$rate->member_subscription_id = $ms->id;
$rate->price = currencyToDouble($this->subscription_subscription_price);
$rate->date = $start;
$rate->months = json_encode([]);
$rate->note = '';
$rate->status = 0;
$rate->is_subscription = true;
$rate->save();
$go = true;
while ($go) {
$mms = [];
$mms[] = date("n", strtotime($start));
for ($jj = 1; $jj < $r->months; $jj++) {
if (date('Ymd', strtotime("+" . $jj . " months", strtotime($start))) < date("Ymd", strtotime($this->subscription_date_to))) {
$mms[] = date('n', strtotime("+" . $jj . " months", strtotime($start)));
} else {
break;
}
}
$rate = new \App\Models\Rate();
$rate->member_id = $this->dataId;
$rate->member_subscription_id = $ms->id;
$rate->course_subscription_id = $this->subscription_course_subscription_id;
$rate->price = currencyToDouble($this->subscription_price);
$rate->date = $start;
$rate->months = json_encode($mms);
$rate->note = '';
$rate->status = 0;
$rate->save();
$start = date('Y-m-d', strtotime("+" . $r->months . " months", strtotime($start)));
if ($start > $this->subscription_date_to || $r->months == 0) {
$go = false;
break;
}
}
session()->flash('success, Abbonamento creato');
$this->resetCourseFields();
$this->addCourse = false;
$this->emit('setEditCorso', false);
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function editSubscription($id)
{
try {
$memberSubscription = \App\Models\MemberSubscription::findOrFail($id);
if (!$memberSubscription) {
session()->flash('error', 'Abbonamento non trovato');
} else {
$this->subscription_id = $memberSubscription->subscription_id;
$subscription = \App\Models\Subscription::findOrFail($this->subscription_id);
$this->subscription_date_from = $memberSubscription->date_from;
$this->subscription_date_to = $memberSubscription->date_to;
$this->subscription_course_subscription_id = $memberSubscription->course_subscription_id;
$this->subscription_price = formatPrice($memberSubscription->price);
$this->subscription_subscription_price = formatPrice($memberSubscription->subscription_price);
$this->subscription_notes = $memberSubscription->notes;
$subscription_subscription_ids = [];
if ($subscription->prices != null) {
foreach (json_decode($subscription->prices) as $z) {
$subscription_subscription_ids[] = $z->course_subscription_id;
}
}
$this->subscription_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $subscription_subscription_ids)->where('enabled', true)->get();
$this->courseDataId = $memberSubscription->id;
$this->updateCourse = true;
$this->addCourse = false;
$this->emit('setEditCorso', true);
}
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function updateSubscription()
{
$this->validate(['subscription_id' => 'required']);
try {
\App\Models\MemberSubscription::whereId($this->courseDataId)->update([
'member_id' => $this->dataId,
'subscription_id' => $this->subscription_id,
'date_from' => $this->subscription_date_from,
'date_to' => $this->subscription_date_to,
'course_subscription_id' => $this->subscription_course_subscription_id,
'price' => currencyToDouble($this->subscription_price),
'subscription_price' => currencyToDouble($this->subscription_subscription_price),
'notes' => $this->subscription_notes,
]);
session()->flash('success', 'Abbonamento aggiornato');
$this->resetCourseFields();
$this->updateCourse = false;
$this->emit('setEditCorso', false);
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function deleteSubscription($id)
{
try {
$member_subscription = \App\Models\MemberSubscription::find($id);
$member_subscription->delete();
session()->flash('success', "Abbonamento eliminato");
} catch (\Exception $e) {
session()->flash('error', 'Errore (' . $e->getMessage() . ')');
}
}
public function addRow()
{
$this->course_when[] = array('day' => array(), 'from' => '', 'to' => '');
}
public function delRow($idx)
{
unset($this->course_when[$idx]);
}
// Certificates
public function addCertificate()
{
$this->resetCertificateFields();
$this->addCertificate = true;
$this->updateCertificate = false;
}
public function storeCertificate()
{
$this->validate(['certificate_expire_date' => 'required']);
try {
$certificatePath = '';
if ($this->certificate_filename) {
$certificatePath = $this->fileService->uploadCertificate($this->certificate_filename, $this->dataId);
}
if ($this->dataId > -1) {
\App\Models\MemberCertificate::create([
'member_id' => $this->dataId,
'type' => $this->certificate_type,
'filename' => $certificatePath,
'expire_date' => $this->certificate_expire_date,
'status' => $this->certificate_status
]);
updateMemberData($this->dataId);
}
session()->flash('success', 'Certificato creato');
$this->resetCertificateFields();
$this->addCertificate = false;
$this->loadMemberCertificates();
// TODO $this->checkCourseAvailability();
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function editCertificate($id)
{
try {
$memberCertificate = \App\Models\MemberCertificate::findOrFail($id);
if (!$memberCertificate) {
session()->flash('error', 'Tesserato non trovato');
} else {
$this->certificate_type = $memberCertificate->type;
$this->certificate_filename_old = $memberCertificate->filename;
$this->certificate_expire_date = $memberCertificate->expire_date;
$this->certificate_status = $memberCertificate->status;
$this->cardCertificateId = $memberCertificate->id;
$this->updateCertificate = true;
$this->addCertificate = false;
}
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function updateCertificate()
{
$this->validate(['certificate_expire_date' => 'required']);
try {
$certificatePath = $this->certificate_filename_old; // Keep existing if no new file
if ($this->certificate_filename) {
$certificatePath = $this->fileService->uploadCertificate($this->certificate_filename, $this->dataId);
}
\App\Models\MemberCertificate::whereId($this->cardCertificateId)->update([
'member_id' => $this->dataId,
'type' => $this->certificate_type,
'filename' => $certificatePath,
'expire_date' => $this->certificate_expire_date,
'status' => $this->certificate_status
]);
updateMemberData($this->dataId);
session()->flash('success', 'Certificato aggiornato');
$this->resetCertificateFields();
$this->updateCertificate = false;
$this->loadMemberCertificates();
// TODO $this->checkCourseAvailability();
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function getFileUrl($filePath)
{
if (!$filePath) {
return null;
}
return $this->fileService->getFileUrl($filePath);
}
public function cancelCertificate()
{
$this->addCertificate = false;
$this->updateCertificate = false;
$this->resetCertificateFields();
}
public function deleteCertificate($id)
{
try {
\App\Models\MemberCertificate::find($id)->delete();
session()->flash('success', "Tesserato eliminato");
} catch (\Exception $e) {
session()->flash('error', 'Errore (' . $e->getMessage() . ')');
}
}
// Gruppi di appartenenza
public function storeCategory()
{
$this->validate(['category_category_id' => 'required']);
try {
\App\Models\MemberCategory::create([
'member_id' => $this->dataId,
'category_id' => $this->category_category_id,
'date' => \Carbon\Carbon::now()
]);
session()->flash('success, Associazione creato');
$this->resetCategoryFields();
$this->addCard = false;
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function hideMsg()
{
$this->groupMsg = '';
}
public function storeCategoryWithID($id)
{
$this->groupMsg = '';
try {
if (\App\Models\MemberCategory::where('member_id', $this->dataId)->where('category_id', $id)->first()) {
$this->groupMsg = '
Attenzione, l\'utente fa già parte di questo gruppo';
} else {
\App\Models\MemberCategory::create([
'member_id' => $this->dataId,
'category_id' => $id,
'date' => \Carbon\Carbon::now()
]);
session()->flash('success, Associazione creato');
$this->resetCategoryFields();
$this->addCard = false;
}
} catch (\Exception $ex) {
session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
}
}
public function deleteCategory($id)
{
try {
\App\Models\MemberCategory::find($id)->delete();
session()->flash('success', "Associazione eliminata");
} catch (\Exception $e) {
session()->flash('error', 'Errore (' . $e->getMessage() . ')');
}
}
public function setCourse($id)
{
$this->course_course_id = $id;
}
public function getNation($nation)
{
if ($nation > 0) {
$ret = \App\Models\Nation::findOrFail($nation);
return $ret->name;
}
return "";
}
public function getProvince($province)
{
if ($province > 0) {
$ret = \App\Models\Province::findOrFail($province);
return $ret->name;
}
return "";
}
public function getCity($city)
{
if ($city > 0) {
$ret = \App\Models\City::findOrFail($city);
return $ret->name;
}
return "";
}
public function getFiscalCode()
{
$this->error_fc = false;
$cf = new codicefiscale();
$cf->setDateSeparator('-');
if ($this->first_name != '' && $this->last_name != '' && $this->birth_date != '' && $this->gender != '' && $this->birth_city_id > 0) {
$code = '';
if ($this->birth_city_id > 0) {
$code = \App\Models\City::findOrFail($this->birth_city_id)->code;
}
$codice = $cf->calcola($this->first_name, $this->last_name, $this->birth_date, $this->gender, $code);
$this->fiscal_code = $codice;
} else
$this->error_fc = true;
}
public function setMonth($m)
{
$exist = -1;
foreach ($this->course_months as $idx => $x) {
if ($x["m"] == $m) {
$exist = $idx;
break;
}
}
if ($exist > -1) {
array_splice($this->course_months, $exist, 1);
} else {
$this->course_months[] = array("m" => $m, "status" => "");
}
}
public function newPayment($course)
{
$c = \App\Models\Course::findOrFail($course["course_id"]);
$price = $course["price"];
if (sizeof($this->payMonths) == 1) {
$month = $this->payMonths[0];
$records = \App\Models\Record::where('member_course_id', $this->selectedCourseMember)->where('deleted', 0)->get();
foreach ($records as $record) {
if (in_array($month, json_decode($record->months))) {
foreach ($record->rows as $row) {
if ($row->causal_id == $c->causal_id && !str_contains(strtolower($row->note), 'iscrizione')) {
$tot = sizeof(json_decode($row->when));
foreach (json_decode($row->when) as $m) {
$price -= $row->amount / $tot;
}
}
}
}
}
}
$this->emit('setEdit', false);
$this->emit('setEditCorso', false);
return redirect()->to('/in?new=1&memberId=' . $this->dataId . '&causalId=' . $c->causal_id . '&subCausalId=' . $c->sub_causal_id . '&createSubscription=' . $this->createSubscription . (sizeof($this->payMonths) > 0 ? '&months=' . implode("|", $this->payMonths) : "") . '&price=' . $price . '&subscription_price=' . $course["subscription_price"] . "&courseId=" . $course["id"]);
}
public function block($course)
{
$xxx = json_decode($course["months"]);
foreach ($xxx as $idx => $mm) {
if (in_array($mm->m, $this->payMonths)) {
$xxx[$idx]->status = 2;
}
}
$c = \App\Models\MemberCourse::findOrFail($course["id"]);
$c->months = json_encode($xxx);
$c->save();
$this->payMonths = array();
}
public function reactivate($course)
{
$xxx = json_decode($course["months"]);
foreach ($xxx as $idx => $mm) {
if (in_array($mm->m, $this->suspendedMonths)) {
$xxx[$idx]->status = "";
}
}
$c = \App\Models\MemberCourse::findOrFail($course["id"]);
$c->months = json_encode($xxx);
$c->save();
$this->suspendedMonths = array();
}
public function setPayMonth($m, $months, $selectedCourseMember)
{
if ($this->selectedCourseMember != $selectedCourseMember)
$this->payMonths = array();
$this->selectedCourseMember = $selectedCourseMember;
if (in_array($m, $this->payMonths)) {
$i = array_search($m, $this->payMonths);
array_splice($this->payMonths, $i, 1);
} else if (in_array($m, $this->suspendedMonths)) {
$i = array_search($m, $this->suspendedMonths);
array_splice($this->suspendedMonths, $i, 1);
} else {
foreach (json_decode($months) as $mm) {
if ($mm->m == $m) {
if ($mm->status == "")
$this->payMonths[] = $m;
if ($mm->status == "1") {
$mc = \App\Models\MemberCourse::findOrFail($selectedCourseMember);
$price = $mc->price;
$payed = 0;
$extraC = '';
$recordsPayed = \App\Models\Record::where('member_course_id', $selectedCourseMember)->where('deleted', 0)->get();
foreach ($recordsPayed as $record) {
if (in_array($m, json_decode($record->months))) {
foreach ($record->rows as $row) {
if ($row->causal_id == $mc->course->causal_id && !str_contains(strtolower($row->note), 'iscrizione')) {
$tot = sizeof(json_decode($row->when));
$payed += $row->amount / $tot;
}
}
if ($payed < $price)
$this->payMonths[] = $m;
}
}
}
if ($mm->status == "2")
$this->suspendedMonths[] = $m;
}
}
}
if (sizeof($this->payMonths) > 0 && sizeof($this->suspendedMonths) > 0) {
$this->payMonths = array();
$this->suspendedMonths = array();
}
}
public function setCreateSubscription($subscribed, $selectedCourseMember)
{
if ($this->selectedCourseMember != $selectedCourseMember)
$this->payMonths = array();
$this->selectedCourseMember = $selectedCourseMember;
if (!$subscribed)
$this->createSubscription = !$this->createSubscription;
}
public function showHideCourse($id)
{
if (in_array($id, $this->showCourse)) {
$i = array_search($id, $this->showCourse);
array_splice($this->showCourse, $i, 1);
} else {
$this->showCourse[] = $id;
}
}
public function getMonthStatus($m, $months, $selectedCourseMember)
{
$class = "grey";
foreach (json_decode($months) as $mm) {
if ($mm->m == $m) {
if ($mm->status == "") {
if (in_array($m, $this->payMonths) && $this->selectedCourseMember == $selectedCourseMember)
$class = "blue";
else
$class = "orange";
}
if ($mm->status == "1") {
$class = "green";
}
if ($mm->status == "2") {
if (in_array($m, $this->suspendedMonths) && $this->selectedCourseMember == $selectedCourseMember)
$class = "blue";
else
$class = "yellow";
}
if ($class == 'green') {
$mc = \App\Models\MemberCourse::findOrFail($selectedCourseMember);
$price = $mc->price;
$payed = 0;
$extraC = '';
$recordsPayed = \App\Models\Record::where('member_course_id', $selectedCourseMember)->where('deleted', 0)->get();
foreach ($recordsPayed as $record) {
if (in_array($m, json_decode($record->months))) {
foreach ($record->rows as $row) {
if ($row->causal_id == $mc->course->causal_id && !str_contains(strtolower($row->note), 'iscrizione')) {
$tot = sizeof(json_decode($row->when));
$payed += $row->amount / $tot;
}
}
}
}
if ($payed < $price)
$class = 'orange half';
}
}
}
return $class;
}
public function getSubscriptionStatus($subscribed, $selectedCourseMember)
{
$class = "grey";
if ($this->createSubscription && $this->selectedCourseMember == $selectedCourseMember)
$class = "blue";
else
$class = "orange";
if ($subscribed)
$class = "green";
return $class;
}
public function checkMonth($m)
{
$ret = false;
foreach ($this->course_months as $idx => $x) {
if ($x["m"] == $m) {
$ret = true;
break;
}
}
return $ret;
}
public function setDay($idx, $d)
{
if (in_array($d, $this->course_when[$idx]["day"])) {
$i = array_search($d, $this->course_when[$idx]["day"]);
array_splice($this->course_when[$idx]["day"], $i, 1);
} else {
$this->course_when[$idx]["day"][] = $d;
}
}
public function updateBorsellino($importoBorsellino, $s)
{
if ($importoBorsellino > 0) {
$imp = $importoBorsellino;
if ($s == "-")
$imp = $imp * -1;
$money = new \App\Models\Money();
$money->member_id = $this->currentMember->id;
$money->record_id = null;
$money->amount = $imp;
$money->date = date("Y-m-d");
$money->note = 'Forzato ' . $imp;
$money->save();
}
$this->emit('saved');
}
public function getMonth($m)
{
$ret = '';
switch ($m) {
case 1:
$ret = 'Gennaio';
break;
case 2:
$ret = 'Febbraio';
break;
case 3:
$ret = 'Marzo';
break;
case 4:
$ret = 'Aprile';
break;
case 5:
$ret = 'Maggio';
break;
case 6:
$ret = 'Giugno';
break;
case 7:
$ret = 'Luglio';
break;
case 8:
$ret = 'Agosto';
break;
case 9:
$ret = 'Settembre';
break;
case 10:
$ret = 'Ottobre';
break;
case 11:
$ret = 'Novembre';
break;
case 12:
$ret = 'Dicembre';
break;
default:
$ret = '';
break;
}
return $ret;
}
public function archive($id)
{
try {
$member = \App\Models\Member::findOrFail($id);
$member->update([
'is_archived' => true,
'archived_date' => now(),
'status' => 'archived',
'enabled' => false
]);
updateMemberData($id);
session()->flash('success', 'Membro archiviato con successo');
$this->emit('reload');
} catch (\Exception $e) {
session()->flash('error', 'Errore durante l\'archiviazione: ' . $e->getMessage());
Log::error('Archive member error', [
'member_id' => $id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
}
}
}
class codicefiscale
{
/**
* Array delle consonanti
*/
protected $_consonanti = array(
'B',
'C',
'D',
'F',
'G',
'H',
'J',
'K',
'L',
'M',
'N',
'P',
'Q',
'R',
'S',
'T',
'V',
'W',
'X',
'Y',
'Z'
);
/**
* Array delle vocali
*/
protected $_vocali = array(
'A',
'E',
'I',
'O',
'U'
);
/**
* Array per il calcolo della lettera del mese
* Al numero del mese corrisponde una lettera
*/
protected $_mesi = array(
1 => 'A',
2 => 'B',
3 => 'C',
4 => 'D',
5 => 'E',
6 => 'H',
7 => 'L',
8 => 'M',
9 => 'P',
10 => 'R',
11 => 'S',
12 => 'T'
);
protected $_pari = array(
'0' => 0,
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9,
'A' => 0,
'B' => 1,
'C' => 2,
'D' => 3,
'E' => 4,
'F' => 5,
'G' => 6,
'H' => 7,
'I' => 8,
'J' => 9,
'K' => 10,
'L' => 11,
'M' => 12,
'N' => 13,
'O' => 14,
'P' => 15,
'Q' => 16,
'R' => 17,
'S' => 18,
'T' => 19,
'U' => 20,
'V' => 21,
'W' => 22,
'X' => 23,
'Y' => 24,
'Z' => 25
);
protected $_dispari = array(
'0' => 1,
'1' => 0,
'2' => 5,
'3' => 7,
'4' => 9,
'5' => 13,
'6' => 15,
'7' => 17,
'8' => 19,
'9' => 21,
'A' => 1,
'B' => 0,
'C' => 5,
'D' => 7,
'E' => 9,
'F' => 13,
'G' => 15,
'H' => 17,
'I' => 19,
'J' => 21,
'K' => 2,
'L' => 4,
'M' => 18,
'N' => 20,
'O' => 11,
'P' => 3,
'Q' => 6,
'R' => 8,
'S' => 12,
'T' => 14,
'U' => 16,
'V' => 10,
'W' => 22,
'X' => 25,
'Y' => 24,
'Z' => 23
);
protected $_controllo = array(
'0' => 'A',
'1' => 'B',
'2' => 'C',
'3' => 'D',
'4' => 'E',
'5' => 'F',
'6' => 'G',
'7' => 'H',
'8' => 'I',
'9' => 'J',
'10' => 'K',
'11' => 'L',
'12' => 'M',
'13' => 'N',
'14' => 'O',
'15' => 'P',
'16' => 'Q',
'17' => 'R',
'18' => 'S',
'19' => 'T',
'20' => 'U',
'21' => 'V',
'22' => 'W',
'23' => 'X',
'24' => 'Y',
'25' => 'Z'
);
/**
* Stringa di errore
*/
protected $_error = null;
/**
* Separatore per la data di nascita
*/
protected $_dateSeparator = '/';
/**
* Percorso del file del database SQLite
* dei codici catastali
*/
protected $_dbCatastali = null;
/**
* Trasforma la stringa passata in un array di lettere
* e lo incrocia con un ulteriore array
*/
protected function _getLettere($string, array $haystack)
{
$letters = array();
foreach (str_split($string) as $needle) {
if (in_array($needle, $haystack)) {
$letters[] = $needle;
}
}
return $letters;
}
/**
* Ritorna un array con le vocali di una data stringa
*/
protected function _getVocali($string)
{
return $this->_getLettere($string, $this->_vocali);
}
/**
* Ritorna un array con le consonanti di una data stringa
*/
protected function _getConsonanti($string)
{
return $this->_getLettere($string, $this->_consonanti);
}
/**
* Pulisce la stringa filtrando tutti i caratteri che
* non sono lettere. Lo switch $toupper se impostato a TRUE
* converte la stringa risultante in MAIUSCOLO.
*/
protected function _sanitize($string, $toupper = true)
{
$result = preg_replace('/[^A-Za-z]*/', '', $string);
return ($toupper) ? strtoupper($result) : $result;
}
/**
* Se la stringa passata a funzione e' costituita
* da meno di 3 caratteri, rimpiazza le lettere
* mancanti con la lettera X.
*/
protected function _addMissingX($string)
{
$code = $string;
while (strlen($code) < 3) {
$code .= 'X';
}
return $code;
}
/**
* Ottiene il codice identificativo del nome
*/
protected function _calcolaNome($string)
{
$nome = $this->_sanitize($string);
$code = '';
// Se il nome inserito e' piu' corto di 3 lettere
// si aggiungono tante X quanti sono i caratteri
// mancanti.
if (strlen($nome) < 3) {
return $this->_addMissingX($nome);
}
$nome_cons = $this->_getConsonanti($nome);
// Se le consonanti contenute nel nome sono minori
// o uguali a 3 vengono considerate nell'ordine in cui
// compaiono.
if (count($nome_cons) <= 3) {
$code = implode('', $nome_cons);
} else {
// Se invece abbiamo almeno 4 consonanti, prendiamo
// la prima, la terza e la quarta.
for ($i = 0; $i < 4; $i++) {
if ($i == 1) continue;
if (!empty($nome_cons[$i])) {
$code .= $nome_cons[$i];
}
}
}
// Se compaiono meno di 3 consonanti nel nome, si
// utilizzano le vocali, nell'ordine in cui compaiono
// nel nome.
if (strlen($code) < 3) {
$nome_voc = $this->_getVocali($nome);
while (strlen($code) < 3) {
$code .= array_shift($nome_voc);
}
}
return $code;
}
protected function _calcolaCognome($string)
{
$cognome = $this->_sanitize($string);
$code = '';
// Se il cognome inserito e' piu' corto di 3 lettere
// si aggiungono tante X quanti sono i caratteri
// mancanti.
if (strlen($cognome) < 3) {
return $this->_addMissingX($cognome);
}
$cognome_cons = $this->_getConsonanti($cognome);
// Per il calcolo del cognome si prendono le prime
// 3 consonanti.
for ($i = 0; $i < 3; $i++) {
if (array_key_exists($i, $cognome_cons)) {
$code .= $cognome_cons[$i];
}
}
// Se le consonanti non bastano, vengono prese
// le vocali nell'ordine in cui compaiono.
if (strlen($code) < 3) {
$cognome_voc = $this->_getVocali($cognome);
while (strlen($code) < 3) {
$code .= array_shift($cognome_voc);
}
}
return $code;
}
/**
* Imposta il separatore di data ( default: / )
*/
public function setDateSeparator($char)
{
$this->_dateSeparator = $char;
return $this;
}
/**
* Ritorna la parte di codice fiscale corrispondente
* alla data di nascita del soggetto (Forma: AAMGG)
*/
protected function _calcolaDataNascita($data, $sesso)
{
$dn = explode($this->_dateSeparator, $data);
$giorno = (int) @$dn[2];
$mese = (int) @$dn[1];
$anno = (int) @$dn[0];
// Le ultime due cifre dell'anno di nascita
$aa = substr($anno, -2);
// La lettera corrispondente al mese di nascita
$mm = $this->_mesi[$mese];
// Il giorno viene calcolato a seconda del sesso
// del soggetto di cui si calcola il codice:
// se e' Maschio si mette il giorno reale, se e'
// Femmina viene aggiungo 40 a questo numero.
$gg = (strtoupper($sesso) == 'M') ? $giorno : ($giorno + 40);
// Bug #1: Thanks to Luca
if (strlen($gg) < 2) $gg = '0' . $gg;
return $aa . $mm . $gg;
}
/**
* Ritorna la cifra di controllo sulla base dei
* 15 caratteri del codice fiscale calcolati.
*/
protected function _calcolaCifraControllo($codice)
{
$code = str_split($codice);
$sum = 0;
for ($i = 1; $i <= count($code); $i++) {
$cifra = $code[$i - 1];
$sum += ($i % 2) ? $this->_dispari[$cifra] : $this->_pari[$cifra];
}
$sum %= 26;
return $this->_controllo[$sum];
}
/**
* Imposta il messaggio di errore
*/
protected function _setError($string)
{
$this->_error = $string;
}
/**
* Verifica la presenza di un errore.
* Ritorna TRUE se presente, FALSE altrimenti.
*/
public function hasError()
{
return !is_null($this->_error);
}
/**
* Ritorna la stringa di errore
*/
public function getError()
{
return $this->_error;
}
/**
* Ritorna il codice fiscale utilizzando i parametri
* passati a funzione. Se si verifica
*/
public function calcola($nome, $cognome, $data, $sesso, $comune)
{
$codice = $this->_calcolaCognome($cognome) .
$this->_calcolaNome($nome) .
$this->_calcolaDataNascita($data, $sesso) .
$comune;
if ($this->hasError()) {
return false;
}
$codice .= $this->_calcolaCifraControllo($codice);
if (strlen($codice) != 16) {
return 'ERROR';
}
return $codice;
}
}