Member.php 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Livewire\Attributes\Url;
  5. use Livewire\WithFileUploads;
  6. use Livewire\WithPagination;
  7. use Illuminate\Support\Facades\Log;
  8. use App\Http\Middleware\TenantMiddleware;
  9. use DateTime;
  10. class Member extends Component
  11. {
  12. use WithPagination;
  13. protected $paginationTheme = 'bootstrap';
  14. protected $listeners = ['storeCategoryWithID' => 'storeCategoryWithID', 'setCourse' => 'setCourse', 'hideMsg' => 'hideMsg'];
  15. use WithFileUploads;
  16. public $sortField = 'id';
  17. public $sortAsc = false;
  18. public $groupMsg = '';
  19. public $type = 'dati';
  20. public $from = '';
  21. public $selectedCourseMember = 0;
  22. protected $messages = [
  23. 'birth_nation_id.required' => 'birth_nation_id',
  24. 'birth_province_id.required' => 'birth_province_id',
  25. 'birth_city_id.required' => 'birth_city_id',
  26. 'nation_id.required' => 'nation_id',
  27. 'province_id.required' => 'province_id',
  28. 'city_id.required' => 'city_id',
  29. 'gender' => 'gender'
  30. ];
  31. public function change($type)
  32. {
  33. $this->type = $type;
  34. if ($type === 'corsi' && $this->dataId > 0) {
  35. $this->loadMemberCards();
  36. $this->loadMemberCertificates();
  37. // TODO $this->checkCourseAvailability();
  38. }
  39. $this->dispatchBrowserEvent('scroll-to-top');
  40. }
  41. public function sortBy($field)
  42. {
  43. if ($this->sortField === $field) {
  44. $this->sortAsc = ! $this->sortAsc;
  45. } else {
  46. $this->sortAsc = true;
  47. }
  48. $this->sortField = $field;
  49. }
  50. 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;
  51. public $isSaving = false;
  52. 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;
  53. public $document_type, $document_number, $document_from, $document_expire_date, $document_files, $document_files_old;
  54. public $selectId = 0;
  55. public $causalId = 0;
  56. public $error_fc = false;
  57. public $under18 = false;
  58. public $money = 0;
  59. public $refreshAfter = 0;
  60. public $checkedAll = false;
  61. public $multipleIds = [];
  62. public $multipleAction = '';
  63. public $isItaly = true;
  64. public $isBirthItaly = true;
  65. public $showDetail = false;
  66. public $currentMember;
  67. public $currentStatus;
  68. public $age = '';
  69. public $disciplines = array();
  70. public $cards = array();
  71. public $categories = array();
  72. public $courses = array();
  73. public $course_names = array();
  74. public $course_levels = array();
  75. // public $course_types = array();
  76. public $course_frequencies = array();
  77. public $course_subscriptions = array();
  78. public $createSubscription = false;
  79. public $payMonths = array();
  80. public $suspendedMonths = array();
  81. public $showCourse = array();
  82. public $searchTxt;
  83. public $search;
  84. public $showReset = false;
  85. public $advanced = false;
  86. public $birthNations = array();
  87. public $birthProvinces = array();
  88. public $birthCities = array();
  89. public $active;
  90. // Card data
  91. 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;
  92. // Categories data
  93. public $member_categories = array(), $category_category_id;
  94. // Courses data
  95. 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;
  96. public $course_months_list = [];
  97. public $course_price_list = [];
  98. public $course_name, $course_level_id, $course_type_id, $course_frequency_id;
  99. // Certificates data
  100. public $member_certificates = array(), $certificate_type, $certificate_filename_old, $certificate_filename, $certificate_expire_date, $certificate_status, $addCertificate, $updateCertificate, $certificateDataId, $cardCertificateId;
  101. public $filterCard = [];
  102. public $filterCategory = [];
  103. public $filterCertNormal = 0;
  104. public $filterCertAgonistic = 0;
  105. public $filterCertScaduto = 0;
  106. public $filterCertInScadenza = 0;
  107. public $already_existing = false;
  108. private $fileService;
  109. public $hasCertificate = false;
  110. protected $rules = [
  111. 'first_name' => 'required',
  112. 'last_name' => 'required',
  113. // 'email' => 'required',
  114. // 'phone' => 'required',
  115. 'birth_date' => 'before_or_equal:today'
  116. ];
  117. public function resetFields()
  118. {
  119. $this->dataId = -1;
  120. $this->first_name = '';
  121. $this->last_name = '';
  122. $this->status = '';
  123. $this->birth_city_id = null;
  124. $this->birth_province_id = null;
  125. $this->birth_nation_id = null;
  126. $this->birth_date = null;
  127. $this->birth_place = '';
  128. $this->importoBorsellino = 0;
  129. $this->father_name = '';
  130. $this->mother_name = '';
  131. $this->father_email = '';
  132. $this->mother_email = '';
  133. $this->father_phone = '';
  134. $this->mother_phone = '';
  135. $this->father_fiscal_code = '';
  136. $this->mother_fiscal_code = '';
  137. $this->father_doc_number = '';
  138. $this->mother_doc_number = '';
  139. $this->father_doc_type = '';
  140. $this->mother_doc_type = '';
  141. $this->mother_document_files = array();
  142. $this->father_document_files = array();
  143. $this->gender = null;
  144. $this->no_send_mail = false;
  145. $this->exclude_from_records = false;
  146. $this->fiscal_code = '';
  147. $this->address = '';
  148. $this->zip_code = '';
  149. $this->document_type = '';
  150. $this->document_number = '';
  151. $this->document_from = '';
  152. $this->document_expire_date = null;
  153. $this->document_files = array();
  154. //$this->nation_id = null;
  155. //$this->province_id = null;
  156. $this->nation_id = null;
  157. $this->province_id = null;
  158. $this->city_id = null;
  159. $this->phone = '';
  160. $this->phone2 = '';
  161. $this->phone3 = '';
  162. $this->email = '';
  163. $this->enabled = true;
  164. $this->under18 = false;
  165. $this->hasCertificate = false;
  166. $this->money = 0;
  167. $this->image = null;
  168. $this->age = '';
  169. $this->error_fc = false;
  170. $this->already_existing = false;
  171. $this->isSaving = false;
  172. $this->emit('load-data-table');
  173. }
  174. public function resetCardFields()
  175. {
  176. $this->card_card_id = null;
  177. $this->card_number = '';
  178. $this->card_date = null;
  179. $this->card_accept_date = null;
  180. $this->card_status = 0;
  181. $this->card_discipline1_id = null;
  182. $this->card_discipline2_id = null;
  183. $this->card_discipline3_id = null;
  184. }
  185. public function resetCertificateFields()
  186. {
  187. $this->certificate_type = '';
  188. $this->certificate_filename = '';
  189. $this->certificate_filename_old = '';
  190. $this->certificate_expire_date = date('Y-m-d', strtotime('+1 year'));
  191. $this->certificate_status = 0;
  192. }
  193. public function resetCourseFields()
  194. {
  195. $this->course_course_id = null;
  196. $this->course_course_type = 'standard';
  197. $this->course_months_list = [];
  198. $this->course_price_list = [];
  199. $this->course_when = array();
  200. $this->course_when[] = array('day' => array(), 'from' => '', 'to' => '');
  201. $this->course_date_from = null;
  202. $this->course_date_to = null;
  203. $this->course_course_subscription_id = null;
  204. $this->course_status = 0;
  205. $this->course_price = 0;
  206. $this->course_subscription_price = 0;
  207. $this->course_exist = false;
  208. $this->course_subscribed = false;
  209. $this->course_months = array();
  210. $this->course_note = '';
  211. $this->course_name = '';
  212. $this->course_level_id = '';
  213. $this->course_type_id = '';
  214. $this->course_frequency_id = '';
  215. }
  216. public function executeMultipleAction()
  217. {
  218. if ($this->multipleAction == 'delete')
  219. $this->multipleDelete();
  220. }
  221. public function updatedImage()
  222. {
  223. $this->validate([
  224. 'image' => 'image|max:1024',
  225. ]);
  226. $this->image_old = '';
  227. }
  228. public function updatedCourseName()
  229. {
  230. $this->course_course_id = null;
  231. $this->course_level_id = '';
  232. $this->course_frequency_id = '';
  233. $levels_ids = [];
  234. if ($this->course_name != '') {
  235. list($n, $y) = explode("(", $this->course_name);
  236. $y = trim(str_replace(")", "", $y));
  237. $all = \App\Models\Course::where('name', 'like', '%' . trim($n) . "%")->where('year', $y)->where('enabled', true)->get();
  238. foreach ($all as $a) {
  239. $levels_ids[] = $a->course_level_id;
  240. }
  241. }
  242. $this->course_levels = \App\Models\CourseLevel::select('*')->where('enabled', true)->whereIn('id', $levels_ids)->get();
  243. $this->course_frequencies = [];
  244. }
  245. public function updatedCourseLevelId()
  246. {
  247. $this->course_course_id = null;
  248. $this->course_frequency_id = '';
  249. $frequencies_ids = [];
  250. if ($this->course_level_id != '') {
  251. list($n, $y) = explode("(", $this->course_name);
  252. $y = trim(str_replace(")", "", $y));
  253. $all = \App\Models\Course::where('name', 'like', '%' . trim($n) . "%")->where('year', $y)->where('enabled', true)->where('course_level_id', $this->course_level_id)->get();
  254. foreach ($all as $a) {
  255. $frequencies_ids[] = $a->course_frequency_id;
  256. }
  257. }
  258. $this->course_frequencies = \App\Models\CourseFrequency::select('*')->where('enabled', true)->whereIn('id', $frequencies_ids)->get();
  259. }
  260. /*
  261. public function updatedCourseTypeId()
  262. {
  263. $this->course_course_id = null;
  264. $this->course_frequency_id = '';
  265. $frequencies_ids = [];
  266. if ($this->course_type_id != '') {
  267. list($n, $y) = explode("(", $this->course_name);
  268. $y = trim(str_replace(")", "", $y));
  269. $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();
  270. foreach ($all as $a) {
  271. $frequencies_ids[] = $a->course_frequency_id;
  272. }
  273. }
  274. $this->course_frequencies = \App\Models\CourseFrequency::select('*')->where('enabled', true)->whereIn('id', $frequencies_ids)->get();
  275. }*/
  276. public function updatedCourseFrequencyId()
  277. {
  278. $this->course_course_id = null;
  279. if ($this->course_frequency_id != '') {
  280. list($n, $y) = explode("(", $this->course_name);
  281. $y = trim(str_replace(")", "", $y));
  282. $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;
  283. $c = \App\Models\Course::findOrFail($this->course_course_id);
  284. $this->course_price = formatPrice($c->price);
  285. $this->course_subscription_price = formatPrice($c->subscription_price);
  286. $this->course_date_from = $c->date_from;
  287. $this->course_date_to = $c->date_to;
  288. // Carico gli abbonamenti e i mesi
  289. $period = \Carbon\CarbonPeriod::create($c->date_from, '1 month', $c->date_to);
  290. $this->course_months_list = [];
  291. foreach ($period as $dt) {
  292. $this->course_months_list[] = $dt->format("m");
  293. }
  294. $course_subscription_ids = [];
  295. $this->course_price_list = [];
  296. if ($c->prices != null) {
  297. foreach (json_decode($c->prices) as $z) {
  298. $this->course_price_list[$z->course_subscription_id] = $z->price;
  299. if ($z->price > 0)
  300. $course_subscription_ids[] = $z->course_subscription_id;
  301. }
  302. }
  303. $this->course_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $course_subscription_ids)->where('enabled', true)->get();
  304. } else {
  305. $this->course_price = 0;
  306. $this->course_subscription_price = 0;
  307. $this->course_exist = false;
  308. }
  309. }
  310. public function updatedCourseCourseType()
  311. {
  312. $this->course_level_id = '';
  313. $this->course_frequency_id = '';
  314. $this->course_course_id = null;
  315. }
  316. public function updatedCourseCourseSubscriptionId()
  317. {
  318. $this->course_price = 0;
  319. if (isset($this->course_price_list[$this->course_course_subscription_id]))
  320. $this->course_price = $this->course_price_list[$this->course_course_subscription_id];
  321. }
  322. public $documents = [];
  323. public $father_documents = [];
  324. public $mother_documents = [];
  325. public function removeDocument($idx, $type)
  326. {
  327. try {
  328. if ($type == 'father') {
  329. if (isset($this->father_document_files[$idx])) {
  330. $filePath = $this->father_document_files[$idx];
  331. $this->fileService->deleteFile($filePath);
  332. unset($this->father_document_files[$idx]);
  333. $this->father_document_files = array_values($this->father_document_files);
  334. }
  335. } elseif ($type == 'mother') {
  336. if (isset($this->mother_document_files[$idx])) {
  337. $filePath = $this->mother_document_files[$idx];
  338. $this->fileService->deleteFile($filePath);
  339. unset($this->mother_document_files[$idx]);
  340. $this->mother_document_files = array_values($this->mother_document_files);
  341. }
  342. } else {
  343. if (isset($this->document_files[$idx])) {
  344. $filePath = $this->document_files[$idx];
  345. $this->fileService->deleteFile($filePath);
  346. unset($this->document_files[$idx]);
  347. $this->document_files = array_values($this->document_files);
  348. }
  349. }
  350. } catch (\Exception $e) {
  351. session()->flash('error', 'Error removing document: ' . $e->getMessage());
  352. }
  353. }
  354. public function updatedDocuments()
  355. {
  356. try {
  357. foreach ($this->documents as $document) {
  358. if ($this->dataId > 0) {
  359. $s3Path = $this->fileService->uploadDocument($document, $this->dataId, 'self');
  360. $this->document_files[] = $s3Path;
  361. } else {
  362. $name = $document->getClientOriginalName();
  363. $document->storeAs('public', $name);
  364. $this->document_files[] = $name;
  365. }
  366. }
  367. $this->documents = [];
  368. } catch (\Exception $e) {
  369. session()->flash('error', 'Error uploading documents: ' . $e->getMessage());
  370. }
  371. }
  372. public function updatedFatherDocuments()
  373. {
  374. try {
  375. foreach ($this->father_documents as $document) {
  376. if ($this->dataId > 0) {
  377. $s3Path = $this->fileService->uploadDocument($document, $this->dataId, 'father');
  378. $this->father_document_files[] = $s3Path;
  379. } else {
  380. $name = $document->getClientOriginalName();
  381. $document->storeAs('public', $name);
  382. $this->father_document_files[] = $name;
  383. }
  384. }
  385. $this->father_documents = [];
  386. } catch (\Exception $e) {
  387. session()->flash('error', 'Error uploading father documents: ' . $e->getMessage());
  388. }
  389. }
  390. public function updatedMotherDocuments()
  391. {
  392. try {
  393. foreach ($this->mother_documents as $document) {
  394. if ($this->dataId > 0) {
  395. $s3Path = $this->fileService->uploadDocument($document, $this->dataId, 'mother');
  396. $this->mother_document_files[] = $s3Path;
  397. } else {
  398. $name = $document->getClientOriginalName();
  399. $document->storeAs('public', $name);
  400. $this->mother_document_files[] = $name;
  401. }
  402. }
  403. $this->mother_documents = [];
  404. } catch (\Exception $e) {
  405. session()->flash('error', 'Error uploading mother documents: ' . $e->getMessage());
  406. }
  407. }
  408. public function resetCategoryFields()
  409. {
  410. $this->category_category_id = null;
  411. }
  412. public function getCategories($records, $indentation)
  413. {
  414. foreach ($records as $record) {
  415. // $this->categories[] = array('id' => $record->id, 'name' => str_repeat(" / ", $indentation) . $record->name);
  416. $this->categories[] = array('id' => $record->id, 'name' => $record->getTree());
  417. if (count($record->childs))
  418. $this->getCategories($record->childs, $indentation + 1);
  419. }
  420. }
  421. public function getCourses($records, $indentation)
  422. {
  423. foreach ($records as $record) {
  424. // $this->categories[] = array('id' => $record->id, 'name' => str_repeat(" / ", $indentation) . $record->name);
  425. $this->courses[] = array('id' => $record->id, 'name' => $record->getTree());
  426. if (count($record->childs))
  427. $this->getCourses($record->childs, $indentation + 1);
  428. }
  429. }
  430. public function updatedBirthDate()
  431. {
  432. $this->validateOnly('birth_date');
  433. $date1 = new DateTime($this->birth_date);
  434. $date2 = new DateTime("now");
  435. $interval = $date1->diff($date2);
  436. $this->age = $interval->y . " anni";
  437. $this->under18 = $interval->y < 18;
  438. }
  439. public function mount()
  440. {
  441. if (isset($_GET["new"])) {
  442. $this->refreshAfter = 1;
  443. $this->add();
  444. }
  445. if (isset($_GET["from"])) {
  446. $this->from = $_GET["from"];
  447. }
  448. $this->cards = \App\Models\Card::select('id', 'name')->get();
  449. $this->disciplines = \App\Models\Discipline::select('id', 'name')->get();
  450. $this->categories = array();
  451. $this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->orderBy('name')->get(), 0);
  452. $c = \App\Models\Causal::where('type', 'IN')->where('money', true)->first();
  453. if ($c)
  454. $this->causalId = $c->id;
  455. if (isset($_GET["member_detail"])) {
  456. $this->showDetailF($_GET["member_detail"]);
  457. $this->refreshAfter = 1;
  458. }
  459. }
  460. public function boot(){
  461. $this->fileService = app(\App\Services\MemberFileService::class);
  462. app(abstract: TenantMiddleware::class)->setupTenantConnection();
  463. }
  464. public function updated()
  465. {
  466. if ($this->isSaving) {
  467. $zzz = [];
  468. if ($this->birth_nation_id == null)
  469. $zzz[] = 'birth_nation_id=' . $this->birth_nation_id;
  470. if ($this->isBirthItaly) {
  471. if ($this->birth_province_id == null)
  472. $zzz[] = 'birth_province_id=' . $this->birth_province_id;
  473. if ($this->birth_city_id == null)
  474. $zzz[] = 'birth_city_id=' . $this->birth_city_id;
  475. }
  476. if ($this->nation_id == null)
  477. $zzz[] = 'nation_id=' . $this->nation_id;
  478. if ($this->isItaly) {
  479. if ($this->province_id == null)
  480. $zzz[] = 'province_id=' . $this->province_id;
  481. if ($this->city_id == null)
  482. $zzz[] = 'city_id=' . $this->city_id;
  483. }
  484. $this->emit('setErrorMsg', $zzz);
  485. }
  486. // $this->emit('load-select');
  487. }
  488. public function hydrate()
  489. {
  490. if ($this->isSaving) {
  491. $zzz = [];
  492. if ($this->birth_nation_id == null)
  493. $zzz[] = 'birth_nation_id=' . $this->birth_nation_id;
  494. if ($this->isBirthItaly) {
  495. if ($this->birth_province_id == null)
  496. $zzz[] = 'birth_province_id=' . $this->birth_province_id;
  497. if ($this->birth_city_id == null)
  498. $zzz[] = 'birth_city_id=' . $this->birth_city_id;
  499. }
  500. if ($this->nation_id == null)
  501. $zzz[] = 'nation_id=' . $this->nation_id;
  502. if ($this->isItaly) {
  503. if ($this->province_id == null)
  504. $zzz[] = 'province_id=' . $this->province_id;
  505. if ($this->city_id == null)
  506. $zzz[] = 'city_id=' . $this->city_id;
  507. }
  508. $this->emit('setErrorMsg', $zzz);
  509. }
  510. $this->emit('load-select');
  511. // $this->emit('destroy-data-table');
  512. }
  513. public function checkIsItaly()
  514. {
  515. if ($this->nation_id > 0) {
  516. $n = \App\Models\Nation::findOrFail($this->nation_id);
  517. $this->isItaly = $n->is_italy;
  518. } else {
  519. $this->isItaly = false;
  520. }
  521. }
  522. public function checkIsBirthItaly()
  523. {
  524. if ($this->birth_nation_id > 0) {
  525. $n = \App\Models\Nation::findOrFail($this->birth_nation_id);
  526. $this->isBirthItaly = $n->is_italy;
  527. } else
  528. $this->isBirthItaly = false;
  529. }
  530. public function search()
  531. {
  532. if ($this->searchTxt != '') {
  533. $this->search = $this->searchTxt;
  534. $this->showReset = true;
  535. }
  536. }
  537. public function resetSearch()
  538. {
  539. $this->showReset = false;
  540. $this->searchTxt = '';
  541. $this->search = $this->searchTxt;
  542. }
  543. public function advancedSearch()
  544. {
  545. $this->advanced = true;
  546. }
  547. public function advancedSearchCancel()
  548. {
  549. $this->filterCard = [];
  550. $this->filterCategory = [];
  551. $this->filterCertNormal = 0;
  552. $this->filterCertAgonistic = 0;
  553. $this->filterCertScaduto = 0;
  554. $this->filterCertInScadenza = 0;
  555. $this->advanced = false;
  556. }
  557. public function render()
  558. {
  559. $this->course_names = [];
  560. $allC = \App\Models\Course::where('type', $this->course_course_type)->where('enabled', true)->orderBy('name')->get();
  561. foreach ($allC as $c) {
  562. $cN = $c->name . " (" . $c->year . ")";
  563. if (!in_array($cN, $this->course_names))
  564. $this->course_names[] = $cN;
  565. }
  566. $datas = [];
  567. if (false) {
  568. if (!$this->advanced) {
  569. $this->records = \App\Models\Member::select('id', 'first_name', 'last_name', 'phone')->get();
  570. } else {
  571. $datas = \App\Models\Member::select('members.*')->where('id', '>', 0);
  572. if (sizeof($this->filterCard) > 0) {
  573. $card_ids = \App\Models\MemberCard::whereIn('card_id', $this->filterCard)->pluck('member_id');
  574. $datas = $datas->whereIn('id', $card_ids);
  575. }
  576. if (sizeof($this->filterCategory) > 0) {
  577. $cats_ids = \App\Models\MemberCategory::whereIn('category_id', $this->filterCategory)->pluck('member_id');
  578. $datas = $datas->whereIn('id', $cats_ids);
  579. }
  580. $certs = [];
  581. if ($this->filterCertNormal > 0) {
  582. $normal = \App\Models\MemberCertificate::where('type', 'N')->pluck('member_id');
  583. $datas = $datas->whereIn('id', $normal);;
  584. }
  585. if ($this->filterCertAgonistic > 0) {
  586. $agonistic = \App\Models\MemberCertificate::where('type', 'A')->pluck('member_id');
  587. $datas = $datas->whereIn('id', $agonistic);
  588. }
  589. if ($this->filterCertScaduto > 0) {
  590. $scaduto = \App\Models\MemberCertificate::where('expire_date', '<', date("Y-m-d"))->pluck('member_id');
  591. $datas = $datas->whereIn('id', $scaduto);
  592. }
  593. if ($this->filterCertInScadenza > 0) {
  594. $scaduto = \App\Models\MemberCertificate::whereBetween('expire_date', [date("Y-m-d"), date("Y-m-d", strtotime("+1 month"))])->pluck('member_id');
  595. $datas = $datas->whereIn('id', $scaduto);
  596. }
  597. if (sizeof($certs) > 0) {
  598. $datas = $datas->whereIn('id', $certs);
  599. }
  600. $this->records = $datas->get();
  601. }
  602. foreach ($this->records as $r) {
  603. $r->age = $r->getAge();
  604. $active = $r->isActive();
  605. $r->status = $active["status"];
  606. $r->date = $active["date"];
  607. $r->certificate = $r->hasCertificate()["date"];
  608. $r->state = $r->getStatus()["status"];
  609. }
  610. $this->emit('load-data-table');
  611. }
  612. $this->loadMemberCards();
  613. $this->loadMemberCourses();
  614. $this->loadMemberCategories();
  615. $this->loadMemberCertificates();
  616. $this->courses = \App\Models\Course::select('id', 'name')->where('type', $this->course_course_type)->get();
  617. return view('livewire.member', ['datas' => $datas]);
  618. }
  619. public function updatedCourseCourseId()
  620. {
  621. if ($this->course_course_id > 0) {
  622. $c = \App\Models\Course::findOrFail($this->course_course_id);
  623. $this->course_price = formatPrice($c->price);
  624. $this->course_subscription_price = formatPrice($c->subscription_price);
  625. $this->course_date_from = $c->date_from;
  626. $this->course_date_to = $c->date_to;
  627. // Controllo se sono già iscritto la corso
  628. $this->course_exist = \App\Models\MemberCourse::where('course_id', $this->course_course_id)->where('member_id', $this->dataId)->count() > 0;
  629. // Carico gli abbonamenti e i mesi
  630. $period = \Carbon\CarbonPeriod::create($c->date_from, '1 month', $c->date_to);
  631. $this->course_months_list = [];
  632. foreach ($period as $dt) {
  633. $this->course_months_list[] = $dt->format("m");
  634. }
  635. $course_subscription_ids = [];
  636. $this->course_price_list = [];
  637. if ($c->prices != null) {
  638. foreach (json_decode($c->prices) as $z) {
  639. $this->course_price_list[$z->course_subscription_id] = $z->price;
  640. if ($z->price > 0)
  641. $course_subscription_ids[] = $z->course_subscription_id;
  642. }
  643. }
  644. $this->course_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $course_subscription_ids)->where('enabled', true)->get();
  645. } else {
  646. $this->course_price = 0;
  647. $this->course_subscription_price = 0;
  648. $this->course_exist = false;
  649. }
  650. }
  651. public function loadMemberCards()
  652. {
  653. $this->member_cards = \App\Models\MemberCard::where('member_id', $this->dataId)->get();
  654. }
  655. public function loadMemberCourses()
  656. {
  657. $this->member_courses = \App\Models\MemberCourse::where('member_id', $this->dataId)->get();
  658. }
  659. public function loadMemberCategories()
  660. {
  661. $this->member_categories = [];
  662. $categories = \App\Models\MemberCategory::with('category')->where('member_id', $this->dataId)->get();
  663. foreach ($categories as $category) {
  664. $this->member_categories[$category->category_id] = $category;
  665. }
  666. usort($this->member_categories, function($a, $b){
  667. return strcmp($a->category->getTree(), $b->category->getTree());
  668. });
  669. }
  670. public function loadMemberCertificates()
  671. {
  672. $this->member_certificates = \App\Models\MemberCertificate::where('member_id', $this->dataId)->orderBy('expire_date', 'DESC')->get();
  673. }
  674. public function showDetailF($id)
  675. {
  676. if (!isset($_GET["from"]) && $this->from == '')
  677. $this->from = 'members';
  678. $this->currentMember = \App\Models\Member::findOrFail($id);
  679. $this->currentStatus = $this->currentMember->getStatus();
  680. $this->showDetail = true;
  681. }
  682. public function add()
  683. {
  684. //$this->from = 'members';
  685. $this->emit('load-select');
  686. $this->emit('hide-search');
  687. $this->showDetail = false;
  688. $this->resetFields();
  689. $this->add = true;
  690. $this->update = false;
  691. $this->emit('setEdit', true);
  692. $this->emit('setEditCorso', false);
  693. $this->dispatchBrowserEvent('scroll-to-top');
  694. }
  695. public function store($close)
  696. {
  697. $this->isSaving = true;
  698. $this->emit('load-select');
  699. $this->emit('goToTop');
  700. $rules = [
  701. 'first_name' => 'required',
  702. 'last_name' => 'required',
  703. 'birth_nation_id' => 'required',
  704. // 'email' => 'required',
  705. // 'phone' => 'required',
  706. 'address' => 'required',
  707. 'zip_code' => 'required',
  708. 'nation_id' => 'required',
  709. 'birth_date' => 'before_or_equal:today',
  710. 'gender' => 'required'
  711. ];
  712. if ($this->isBirthItaly) {
  713. $rules['birth_province_id'] = 'required';
  714. $rules['birth_city_id'] = 'required';
  715. $rules['fiscal_code'] = 'required';
  716. } else {
  717. $rules['birth_place'] = 'required';
  718. }
  719. if ($this->isItaly) {
  720. $rules['province_id'] = 'required';
  721. $rules['city_id'] = 'required';
  722. }
  723. $zzz = [];
  724. if ($this->birth_nation_id == null)
  725. $zzz[] = 'birth_nation_id=' . $this->birth_nation_id;
  726. if ($this->isBirthItaly) {
  727. if ($this->birth_province_id == null)
  728. $zzz[] = 'birth_province_id=' . $this->birth_province_id;
  729. if ($this->birth_city_id == null)
  730. $zzz[] = 'birth_city_id=' . $this->birth_city_id;
  731. }
  732. if ($this->nation_id == null)
  733. $zzz[] = 'nation_id=' . $this->nation_id;
  734. if ($this->isItaly) {
  735. if ($this->province_id == null)
  736. $zzz[] = 'province_id=' . $this->province_id;
  737. if ($this->city_id == null)
  738. $zzz[] = 'city_id=' . $this->city_id;
  739. }
  740. $this->emit('setErrorMsg', $zzz);
  741. if (!empty($this->fiscal_code)) {
  742. $existingMember = \App\Models\Member::where('fiscal_code', $this->fiscal_code)->first();
  743. if ($existingMember) {
  744. $this->already_existing = true;
  745. $this->emit('focus-error-field', 'fiscal_code');
  746. return;
  747. }
  748. }
  749. if ($this->under18) {
  750. $rules['father_name'] = 'required_without:mother_name';
  751. $rules['father_email'] = 'required_without:mother_email|email';
  752. $rules['father_fiscal_code'] = 'required_without:mother_fiscal_code';
  753. $rules['mother_name'] = 'required_without:father_name';
  754. $rules['mother_email'] = 'required_without:father_email|email';
  755. $rules['mother_fiscal_code'] = 'required_without:father_fiscal_code';
  756. } else {
  757. $rules['email'] = 'required';
  758. $rules['phone'] = 'required';
  759. }
  760. $std_rules = $rules;
  761. // $rules = [
  762. // 'first_name' => 'required',
  763. // 'last_name' => 'required'
  764. // ];
  765. try {
  766. $this->validate($rules);
  767. } catch (\Illuminate\Validation\ValidationException $e) {
  768. $this->isSaving = false;
  769. $errorFields = array_keys($e->errors());
  770. if (!empty($errorFields)) {
  771. $this->emit('focus-error-field', $errorFields[0]);
  772. }
  773. Log::error('Validation failed', ['errors' => $e->errors()]);
  774. return;
  775. }
  776. try {
  777. $imageName = '';
  778. if ($this->image) {
  779. $imageName = md5($this->image . microtime()) . '.' . $this->image->extension();
  780. $this->image->storeAs('public', $imageName);
  781. }
  782. $docs = implode("|", $this->document_files);
  783. $father_docs = implode("|", $this->father_document_files);
  784. $mother_docs = implode("|", $this->mother_document_files);
  785. $to_complete = false;
  786. // try {
  787. // $this->validate($std_rules);
  788. // } catch(\Illuminate\Validation\ValidationException $e) {
  789. // $to_complete = true;
  790. // } catch (\Exception $e) {
  791. // $to_complete = true;
  792. // }
  793. $member = \App\Models\Member::create([
  794. 'first_name' => strtoupper($this->first_name),
  795. 'last_name' => strtoupper($this->last_name),
  796. 'status' => $this->status,
  797. 'birth_city_id' => $this->birth_city_id > 0 ? $this->birth_city_id : null,
  798. 'birth_province_id' => $this->birth_province_id > 0 ? $this->birth_province_id : null,
  799. 'birth_nation_id' => $this->birth_nation_id > 0 ? $this->birth_nation_id : null,
  800. 'birth_date' => $this->birth_date,
  801. 'birth_place' => $this->birth_place,
  802. 'father_name' => $this->father_name,
  803. 'mother_name' => $this->mother_name,
  804. 'father_email' => strtolower($this->father_email),
  805. 'mother_email' => strtolower($this->mother_email),
  806. 'father_phone' => $this->father_phone,
  807. 'mother_phone' => $this->mother_phone,
  808. 'father_fiscal_code' => $this->father_fiscal_code,
  809. 'mother_fiscal_code' => $this->mother_fiscal_code,
  810. 'father_doc_number' => $this->father_doc_number,
  811. 'father_doc_type' => $this->father_doc_type,
  812. 'mother_doc_number' => $this->mother_doc_number,
  813. 'mother_doc_type' => $this->mother_doc_type,
  814. 'document_type' => $this->document_type,
  815. 'document_number' => $this->document_number,
  816. 'document_from' => $this->document_from,
  817. 'document_expire_date' => $this->document_expire_date,
  818. 'document_files' => $docs,
  819. 'mother_document_files' => $mother_docs,
  820. 'father_document_files' => $father_docs,
  821. 'gender' => $this->gender,
  822. 'no_send_mail' => $this->no_send_mail,
  823. 'exclude_from_records' => $this->exclude_from_records,
  824. 'fiscal_code' => $this->fiscal_code,
  825. 'address' => $this->address,
  826. 'zip_code' => $this->zip_code,
  827. 'nation_id' => $this->nation_id > 0 ? $this->nation_id : null,
  828. 'province_id' => $this->province_id > 0 ? $this->province_id : null,
  829. 'city_id' => $this->city_id > 0 ? $this->city_id : null,
  830. 'phone' => $this->phone,
  831. 'phone2' => $this->phone2,
  832. 'phone3' => $this->phone3,
  833. 'email' => strtolower($this->email),
  834. 'image' => $imageName,
  835. 'to_complete' => $to_complete,
  836. 'enabled' => $this->enabled
  837. ]);
  838. $this->fileService->createMemberFolders($member->id);
  839. if ($this->image) {
  840. $s3ImagePath = $this->fileService->uploadProfileImage($this->image, $member->id);
  841. $member->update(['image' => $s3ImagePath]);
  842. }
  843. $this->migrateTemporaryFiles($member->id);
  844. session()->flash('success, Tesserato creato');
  845. updateMemberData($member->id);
  846. $this->resetFields();
  847. if ($close) {
  848. $this->add = false;
  849. return redirect()->to('/members');
  850. } else {
  851. $this->edit($member->id);
  852. $this->emit('saved-and-continue', $this->type);
  853. $this->dispatchBrowserEvent('scroll-to-top');
  854. }
  855. $this->emit('setEdit', false);
  856. } catch (\Exception $ex) {
  857. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  858. }
  859. }
  860. private function migrateTemporaryFiles($memberId)
  861. {
  862. try {
  863. $updatedPaths = [];
  864. // Migrate document files
  865. $newDocumentFiles = [];
  866. foreach ($this->document_files as $filePath) {
  867. if (strpos($filePath, '/members/') === false) {
  868. // This is a temporary local file, move to S3
  869. $localPath = storage_path('app/public/' . $filePath);
  870. if (file_exists($localPath)) {
  871. $uploadedFile = new \Illuminate\Http\UploadedFile(
  872. $localPath,
  873. basename($filePath),
  874. mime_content_type($localPath),
  875. filesize($localPath),
  876. 0,
  877. true
  878. );
  879. $s3Path = $this->fileService->uploadDocument($uploadedFile, $memberId, 'self');
  880. $newDocumentFiles[] = $s3Path;
  881. // Delete temporary file
  882. unlink($localPath);
  883. }
  884. } else {
  885. $newDocumentFiles[] = $filePath;
  886. }
  887. }
  888. if (!empty($newDocumentFiles)) {
  889. $updatedPaths['document_files'] = implode('|', $newDocumentFiles);
  890. }
  891. // Migrate father document files
  892. $newFatherFiles = [];
  893. foreach ($this->father_document_files as $filePath) {
  894. if (strpos($filePath, '/members/') === false) {
  895. $localPath = storage_path('app/public/' . $filePath);
  896. if (file_exists($localPath)) {
  897. $uploadedFile = new \Illuminate\Http\UploadedFile(
  898. $localPath,
  899. basename($filePath),
  900. mime_content_type($localPath),
  901. filesize($localPath),
  902. 0,
  903. true
  904. );
  905. $s3Path = $this->fileService->uploadDocument($uploadedFile, $memberId, 'father');
  906. $newFatherFiles[] = $s3Path;
  907. unlink($localPath);
  908. }
  909. } else {
  910. $newFatherFiles[] = $filePath;
  911. }
  912. }
  913. if (!empty($newFatherFiles)) {
  914. $updatedPaths['father_document_files'] = implode('|', $newFatherFiles);
  915. }
  916. // Migrate mother document files
  917. $newMotherFiles = [];
  918. foreach ($this->mother_document_files as $filePath) {
  919. if (strpos($filePath, '/members/') === false) {
  920. $localPath = storage_path('app/public/' . $filePath);
  921. if (file_exists($localPath)) {
  922. $uploadedFile = new \Illuminate\Http\UploadedFile(
  923. $localPath,
  924. basename($filePath),
  925. mime_content_type($localPath),
  926. filesize($localPath),
  927. 0,
  928. true
  929. );
  930. $s3Path = $this->fileService->uploadDocument($uploadedFile, $memberId, 'mother');
  931. $newMotherFiles[] = $s3Path;
  932. unlink($localPath);
  933. }
  934. } else {
  935. $newMotherFiles[] = $filePath;
  936. }
  937. }
  938. if (!empty($newMotherFiles)) {
  939. $updatedPaths['mother_document_files'] = implode('|', $newMotherFiles);
  940. }
  941. // Update member with new S3 paths
  942. if (!empty($updatedPaths)) {
  943. \App\Models\Member::whereId($memberId)->update($updatedPaths);
  944. }
  945. } catch (\Exception $e) {
  946. Log::error('Error migrating temporary files', [
  947. 'member_id' => $memberId,
  948. 'error' => $e->getMessage()
  949. ]);
  950. }
  951. }
  952. public function duplicate($id)
  953. {
  954. $member = \App\Models\Member::findOrFail($id);
  955. $newMember = $member->replicate();
  956. $newMember->save();
  957. $this->edit($newMember->id);
  958. }
  959. public function edit($id)
  960. {
  961. if (!isset($_GET["from"]) && $this->from == '')
  962. $this->from = 'members';
  963. $this->showDetail = false;
  964. $this->emit('setEdit', true);
  965. $this->emit('setEditCorso', false);
  966. $this->emit('hide-search');
  967. try {
  968. $member = \App\Models\Member::findOrFail($id);
  969. if (!$member) {
  970. session()->flash('error', 'Tesserato non trovato');
  971. } else {
  972. $this->first_name = $member->first_name;
  973. $this->last_name = $member->last_name;
  974. $this->status = $member->status;
  975. $this->birth_city_id = $member->birth_city_id;
  976. $this->birth_province_id = $member->birth_province_id;
  977. $this->birth_nation_id = $member->birth_nation_id;
  978. $this->birth_date = $member->birth_date;
  979. $this->birth_place = $member->birth_place;
  980. $this->father_name = $member->father_name;
  981. $this->mother_name = $member->mother_name;
  982. $this->father_email = strtolower($member->father_email);
  983. $this->mother_email = strtolower($member->mother_email);
  984. $this->father_phone = $member->father_phone;
  985. $this->mother_phone = $member->mother_phone;
  986. $this->father_fiscal_code = $member->father_fiscal_code;
  987. $this->mother_fiscal_code = $member->mother_fiscal_code;
  988. $this->father_doc_number = $member->father_doc_number;
  989. $this->mother_doc_number = $member->mother_doc_number;
  990. $this->father_doc_type = $member->father_doc_type;
  991. $this->mother_doc_type = $member->mother_doc_type;
  992. $this->father_document_files = explode("|", $member->father_document_files);
  993. $this->mother_document_files = explode("|", $member->mother_document_files);
  994. $this->document_type = $member->document_type;
  995. $this->document_number = $member->document_number;
  996. $this->document_from = $member->document_from;
  997. $this->document_expire_date = $member->document_expire_date;
  998. $this->document_files = explode("|", $member->document_files);
  999. $this->gender = $member->gender;
  1000. $this->no_send_mail = $member->no_send_mail;
  1001. $this->exclude_from_records = $member->exclude_from_records;
  1002. $this->fiscal_code = $member->fiscal_code;
  1003. $this->address = $member->address;
  1004. $this->zip_code = $member->zip_code;
  1005. $this->nation_id = $member->nation_id;
  1006. $this->province_id = $member->province_id;
  1007. $this->city_id = $member->city_id;
  1008. $this->phone = $member->phone;
  1009. $this->phone2 = $member->phone2;
  1010. $this->phone3 = $member->phone3;
  1011. $this->email = strtolower($member->email);
  1012. $this->image_old = $member->image;
  1013. $this->enabled = $member->enabled;
  1014. $this->dataId = $member->id;
  1015. $this->active = $member->getStatus();
  1016. $this->hasCertificate = $member->hasCertificate()["status"];
  1017. $this->money = $member->getMoney();
  1018. $this->checkIsBirthItaly();
  1019. $date1 = new DateTime($this->birth_date);
  1020. $date2 = new DateTime("now");
  1021. $interval = $date1->diff($date2);
  1022. $this->age = $interval->y . " anni";
  1023. $this->under18 = $interval->y < 18;
  1024. $this->update = true;
  1025. $this->add = false;
  1026. $this->emit('setIds', $this->nation_id, $this->birth_nation_id);
  1027. $this->emit('load-select');
  1028. $this->emit('load-provinces', $this->nation_id, 'provinceClass');
  1029. $this->emit('load-provinces', $this->birth_nation_id, 'provinceBirthClass');
  1030. $this->emit('load-cities', $this->province_id, 'cityClass');
  1031. $this->emit('load-cities', $this->birth_province_id, 'cityBirthClass');
  1032. $this->dispatchBrowserEvent('scroll-to-top');
  1033. }
  1034. } catch (\Exception $ex) {
  1035. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1036. }
  1037. }
  1038. public function updateAAA($close)
  1039. {
  1040. $this->emit('goToTop');
  1041. $this->isSaving = true;
  1042. $this->emit('load-select');
  1043. $rules = [
  1044. 'first_name' => 'required',
  1045. 'last_name' => 'required',
  1046. // 'email' => 'required',
  1047. // 'phone' => 'required',
  1048. 'birth_nation_id' => 'required',
  1049. 'address' => 'required',
  1050. 'zip_code' => 'required',
  1051. 'nation_id' => 'required',
  1052. 'birth_date' => 'before_or_equal:today'
  1053. ];
  1054. if ($this->isBirthItaly) {
  1055. $rules['birth_province_id'] = 'required';
  1056. $rules['birth_city_id'] = 'required';
  1057. $rules['fiscal_code'] = 'required';
  1058. } else {
  1059. $rules['birth_place'] = 'required';
  1060. }
  1061. Log::info('isItaly', ['isItaly' => $this->isItaly]);
  1062. $this->isItaly = $this->checkIsItaly();
  1063. if ($this->isItaly) {
  1064. $rules['province_id'] = 'required';
  1065. $rules['city_id'] = 'required';
  1066. }
  1067. $zzz = [];
  1068. if ($this->birth_nation_id == null)
  1069. $zzz[] = 'birth_nation_id=' . $this->birth_nation_id;
  1070. if ($this->isBirthItaly) {
  1071. if ($this->birth_province_id == null)
  1072. $zzz[] = 'birth_province_id=' . $this->birth_province_id;
  1073. if ($this->birth_city_id == null)
  1074. $zzz[] = 'birth_city_id=' . $this->birth_city_id;
  1075. }
  1076. if ($this->nation_id == null)
  1077. $zzz[] = 'nation_id=' . $this->nation_id;
  1078. if ($this->isItaly) {
  1079. if ($this->province_id == null)
  1080. $zzz[] = 'province_id=' . $this->province_id;
  1081. if ($this->city_id == null)
  1082. $zzz[] = 'city_id=' . $this->city_id;
  1083. }
  1084. $this->emit('setErrorMsg', $zzz);
  1085. if ($this->under18) {
  1086. $rules['father_name'] = 'required_without:mother_name';
  1087. $rules['father_email'] = 'required_without:mother_email|email';
  1088. $rules['father_fiscal_code'] = 'required_without:mother_fiscal_code';
  1089. $rules['mother_name'] = 'required_without:father_name';
  1090. $rules['mother_email'] = 'required_without:father_email|email';
  1091. $rules['mother_fiscal_code'] = 'required_without:father_fiscal_code';
  1092. } else {
  1093. $rules['email'] = 'required';
  1094. $rules['phone'] = 'required';
  1095. }
  1096. $std_rules = $rules;
  1097. // $rules = [
  1098. // 'first_name' => 'required',
  1099. // 'last_name' => 'required'
  1100. // ];
  1101. try {
  1102. $this->validate($rules);
  1103. } catch (\Illuminate\Validation\ValidationException $e) {
  1104. $this->isSaving = false;
  1105. $errorFields = array_keys($e->errors());
  1106. if (!empty($errorFields)) {
  1107. $this->emit('focus-error-field', $errorFields[0]);
  1108. }
  1109. Log::error('Validation failed', ['errors' => $e->errors()]);
  1110. return;
  1111. }
  1112. try {
  1113. $imagePath = $this->image_old; // Keep existing if no new image
  1114. if ($this->image) {
  1115. $imagePath = $this->fileService->uploadProfileImage($this->image, $this->dataId);
  1116. }
  1117. $docs = implode("|", $this->document_files);
  1118. $father_docs = implode("|", $this->father_document_files);
  1119. $mother_docs = implode("|", $this->mother_document_files);
  1120. $to_complete = false;
  1121. // try {
  1122. // $this->validate($std_rules);
  1123. // } catch(\Illuminate\Validation\ValidationException $e) {
  1124. // $to_complete = true;
  1125. // } catch (Exception $e) {
  1126. // $to_complete = true;
  1127. // }
  1128. \App\Models\Member::whereId($this->dataId)->update([
  1129. 'first_name' => strtoupper($this->first_name),
  1130. 'last_name' => strtoupper($this->last_name),
  1131. 'status' => $this->status,
  1132. 'birth_city_id' => $this->birth_city_id > 0 ? $this->birth_city_id : null,
  1133. 'birth_province_id' => $this->birth_province_id > 0 ? $this->birth_province_id : null,
  1134. 'birth_nation_id' => $this->birth_nation_id > 0 ? $this->birth_nation_id : null,
  1135. 'birth_date' => $this->birth_date,
  1136. 'birth_place' => $this->birth_place,
  1137. 'father_name' => $this->father_name,
  1138. 'mother_name' => $this->mother_name,
  1139. 'father_email' => strtolower($this->father_email),
  1140. 'mother_email' => strtolower($this->mother_email),
  1141. 'father_phone' => $this->father_phone,
  1142. 'mother_phone' => $this->mother_phone,
  1143. 'father_fiscal_code' => $this->father_fiscal_code,
  1144. 'mother_fiscal_code' => $this->mother_fiscal_code,
  1145. 'father_doc_number' => $this->father_doc_number,
  1146. 'father_doc_type' => $this->father_doc_type,
  1147. 'mother_doc_number' => $this->mother_doc_number,
  1148. 'mother_doc_type' => $this->mother_doc_type,
  1149. 'father_document_files' => $father_docs,
  1150. 'mother_document_files' => $mother_docs,
  1151. 'document_type' => $this->document_type,
  1152. 'document_number' => $this->document_number,
  1153. 'document_from' => $this->document_from,
  1154. 'document_expire_date' => $this->document_expire_date,
  1155. 'document_files' => $docs,
  1156. 'gender' => $this->gender,
  1157. 'no_send_mail' => $this->no_send_mail,
  1158. 'exclude_from_records' => $this->exclude_from_records,
  1159. 'fiscal_code' => $this->fiscal_code,
  1160. 'address' => $this->address,
  1161. 'zip_code' => $this->zip_code,
  1162. 'nation_id' => $this->nation_id > 0 ? $this->nation_id : null,
  1163. 'province_id' => $this->province_id > 0 ? $this->province_id : null,
  1164. 'city_id' => $this->city_id > 0 ? $this->city_id : null,
  1165. 'image' => $imagePath,
  1166. 'phone' => $this->phone,
  1167. 'phone2' => $this->phone2,
  1168. 'phone3' => $this->phone3,
  1169. 'email' => strtolower($this->email),
  1170. 'to_complete' => $to_complete,
  1171. 'enabled' => $this->enabled
  1172. ]);
  1173. updateMemberData($this->dataId);
  1174. session()->flash('success', 'Tesserato aggiornato');
  1175. if ($close) {
  1176. $this->resetFields();
  1177. $this->update = false;
  1178. return redirect()->to('/members');
  1179. } else {
  1180. $this->emit('saved-and-continue', $this->type);
  1181. $this->dispatchBrowserEvent('scroll-to-top');
  1182. }
  1183. $this->emit('setEdit', false);
  1184. } catch (\Exception $ex) {
  1185. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1186. }
  1187. }
  1188. public function cancel()
  1189. {
  1190. $this->add = false;
  1191. $this->update = false;
  1192. $this->showDetail = false;
  1193. $this->resetFields();
  1194. $this->emit('setEdit', false);
  1195. //$this->emit('setEditCorso', false);
  1196. $this->emit('reload');
  1197. }
  1198. public function delete($id)
  1199. {
  1200. try {
  1201. \App\Models\Member::find($id)->delete();
  1202. session()->flash('success', "Tesserato eliminato");
  1203. $this->emit('reload');
  1204. } catch (\Exception $e) {
  1205. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  1206. }
  1207. }
  1208. public function checkUncheckAll()
  1209. {
  1210. if (!$this->checkedAll) {
  1211. $this->multipleIds = array();
  1212. } else {
  1213. foreach ($this->records as $r) {
  1214. $this->multipleIds[] = $r->id;
  1215. }
  1216. }
  1217. }
  1218. public function multipleDelete()
  1219. {
  1220. try {
  1221. foreach ($this->multipleIds as $id) {
  1222. \App\Models\Member::find($id)->delete();
  1223. }
  1224. } catch (\Exception $e) {
  1225. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  1226. }
  1227. $this->multipleAction = '';
  1228. }
  1229. // Card
  1230. public function addCard()
  1231. {
  1232. $this->resetCardFields();
  1233. $this->addCard = true;
  1234. $this->updateCard = false;
  1235. }
  1236. public function storeCard()
  1237. {
  1238. $this->validate(['card_card_id' => 'required']);
  1239. try {
  1240. // in base alla card selezionata calcolo la scadenza
  1241. $expire_date = null;
  1242. if ($this->card_date != '') {
  1243. $y = date("Y", strtotime($this->card_date));
  1244. $card = \App\Models\Card::findOrFail($this->card_card_id);
  1245. if ($card->next_day_expire > 0 && $card->next_month_expire > 0) {
  1246. $m = strlen($card->next_month_expire) == 1 ? ('0' . $card->next_month_expire) : $card->next_month_expire;
  1247. if (date("md", strtotime($this->card_date)) > ($m . $card->next_day_expire))
  1248. $y += 1;
  1249. $next_exp = date($y . "-" . $m . "-" . $card->next_day_expire);
  1250. if ($next_exp > $this->card_date) {
  1251. $expire_date = $next_exp;
  1252. } else
  1253. $expire_date = date($y . "-" . $card->next_month_expire . "-" . $card->next_day_expire, strtotime(' + 1 years'));
  1254. } else {
  1255. if ($card->one_year_expire) {
  1256. $expire_date = date("Y-m-d", strtotime($this->card_date . ' + 1 years'));
  1257. }
  1258. }
  1259. }
  1260. \App\Models\MemberCard::create([
  1261. 'member_id' => $this->dataId,
  1262. 'card_id' => $this->card_card_id,
  1263. 'number' => $this->card_number,
  1264. 'date' => $this->card_date,
  1265. 'accept_date' => $this->card_accept_date != '' ? $this->card_accept_date : $this->card_date,
  1266. 'expire_date' => $expire_date,
  1267. 'status' => $this->card_status,
  1268. 'discipline1_id' => $this->card_discipline1_id,
  1269. 'discipline2_id' => $this->card_discipline2_id,
  1270. 'discipline3_id' => $this->card_discipline3_id,
  1271. ]);
  1272. updateMemberData($this->dataId);
  1273. session()->flash('success, Tesserato creato');
  1274. $this->resetCardFields();
  1275. $this->addCard = false;
  1276. $this->loadMemberCards();
  1277. // TODO $this->checkCourseAvailability();
  1278. } catch (\Exception $ex) {
  1279. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1280. }
  1281. }
  1282. public function editCard($id)
  1283. {
  1284. try {
  1285. $memberCard = \App\Models\MemberCard::findOrFail($id);
  1286. if (!$memberCard) {
  1287. session()->flash('error', 'Tesserato non trovato');
  1288. } else {
  1289. $this->card_card_id = $memberCard->card_id;
  1290. $this->card_number = $memberCard->number;
  1291. $this->card_date = $memberCard->date;
  1292. $this->card_accept_date = $memberCard->accept_date;
  1293. $this->card_status = $memberCard->status;
  1294. $this->card_discipline1_id = $memberCard->discipline1_id;
  1295. $this->card_discipline2_id = $memberCard->discipline2_id;
  1296. $this->card_discipline3_id = $memberCard->discipline3_id;
  1297. $this->cardDataId = $memberCard->id;
  1298. $this->updateCard = true;
  1299. $this->addCard = false;
  1300. }
  1301. } catch (\Exception $ex) {
  1302. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1303. }
  1304. }
  1305. public function updateCard()
  1306. {
  1307. $this->validate(['card_card_id' => 'required']);
  1308. try {
  1309. Log::info('Starting card update', [
  1310. 'member_id' => $this->dataId,
  1311. 'card_id' => $this->card_card_id,
  1312. 'card_number' => $this->card_number
  1313. ]);
  1314. $expire_date = null;
  1315. if ($this->card_date != '') {
  1316. $card = \App\Models\Card::findOrFail($this->card_card_id);
  1317. Log::info('Card details', [
  1318. 'card_id' => $card->id,
  1319. 'next_day_expire' => $card->next_day_expire,
  1320. 'next_month_expire' => $card->next_month_expire,
  1321. 'one_year_expire' => $card->one_year_expire
  1322. ]);
  1323. if ($card->next_day_expire > 0 && $card->next_month_expire > 0) {
  1324. $y = date("Y", strtotime($this->card_date));
  1325. $m = strlen($card->next_month_expire) == 1 ? ('0' . $card->next_month_expire) : $card->next_month_expire;
  1326. $d = strlen($card->next_day_expire) == 1 ? ('0' . $card->next_day_expire) : $card->next_day_expire;
  1327. $next_exp = $y . "-" . $m . "-" . $d;
  1328. // Format dates for comparison
  1329. $input_date_obj = new \DateTime($this->card_date);
  1330. $next_exp_obj = new \DateTime($next_exp);
  1331. if ($next_exp_obj > $input_date_obj) {
  1332. $expire_date = $next_exp;
  1333. } else {
  1334. // Add 1 year to the expiration date if the input date is after the expiration date
  1335. $next_exp_obj->modify('+1 year');
  1336. $expire_date = $next_exp_obj->format('Y-m-d');
  1337. }
  1338. Log::info('Calculated expiration date (next_day_expire/next_month_expire rule)', [
  1339. 'input_date' => $this->card_date,
  1340. 'next_exp' => $next_exp,
  1341. 'expire_date' => $expire_date,
  1342. 'comparison' => ($next_exp_obj > $input_date_obj) ? 'next_exp is after input_date' : 'next_exp is before or equal to input_date'
  1343. ]);
  1344. } else {
  1345. if ($card->one_year_expire) {
  1346. $expire_date = date("Y-m-d", strtotime($this->card_date . ' + 1 years'));
  1347. Log::info('Calculated expiration date (one_year_expire rule)', [
  1348. 'input_date' => $this->card_date,
  1349. 'expire_date' => $expire_date
  1350. ]);
  1351. }
  1352. }
  1353. }
  1354. Log::info('Updating member card', [
  1355. 'card_id' => $this->cardDataId,
  1356. 'member_id' => $this->dataId,
  1357. 'card_number' => $this->card_number,
  1358. 'date' => $this->card_date,
  1359. 'expire_date' => $expire_date,
  1360. 'status' => $this->card_status
  1361. ]);
  1362. \App\Models\MemberCard::whereId($this->cardDataId)->update([
  1363. 'member_id' => $this->dataId,
  1364. 'card_id' => $this->card_card_id,
  1365. 'number' => $this->card_number,
  1366. 'date' => $this->card_date,
  1367. 'accept_date' => $this->card_accept_date != '' ? $this->card_accept_date : $this->card_date,
  1368. 'expire_date' => $expire_date,
  1369. 'status' => $this->card_status,
  1370. 'discipline1_id' => $this->card_discipline1_id,
  1371. 'discipline2_id' => $this->card_discipline2_id,
  1372. 'discipline3_id' => $this->card_discipline3_id,
  1373. ]);
  1374. updateMemberData($this->dataId);
  1375. Log::info('Card updated successfully', [
  1376. 'card_id' => $this->cardDataId,
  1377. 'member_id' => $this->dataId
  1378. ]);
  1379. session()->flash('success', 'Tesserato aggiornato');
  1380. $this->resetCardFields();
  1381. $this->updateCard = false;
  1382. $this->loadMemberCards();
  1383. // TODO $this->checkCourseAvailability();
  1384. } catch (\Exception $ex) {
  1385. Log::error('Error updating card', [
  1386. 'card_id' => $this->cardDataId,
  1387. 'member_id' => $this->dataId,
  1388. 'error_message' => $ex->getMessage(),
  1389. 'error_trace' => $ex->getTraceAsString()
  1390. ]);
  1391. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1392. }
  1393. }
  1394. public function cancelCard()
  1395. {
  1396. $this->addCard = false;
  1397. $this->updateCard = false;
  1398. $this->resetCardFields();
  1399. }
  1400. public function deleteCard($id)
  1401. {
  1402. try {
  1403. \App\Models\MemberCard::find($id)->delete();
  1404. session()->flash('success', "Tesserato eliminato");
  1405. } catch (\Exception $e) {
  1406. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  1407. }
  1408. }
  1409. public function addCourse()
  1410. {
  1411. $this->resetCourseFields();
  1412. $this->addCourse = true;
  1413. $this->updateCourse = false;
  1414. $this->emit('setEditCorso', true);
  1415. }
  1416. public function storeCourse()
  1417. {
  1418. $this->validate(['course_course_id' => 'required']);
  1419. try {
  1420. $mc = new \App\Models\MemberCourse();
  1421. $mc->member_id = $this->dataId;
  1422. $mc->course_id = $this->course_course_id;
  1423. $mc->date_from = $this->course_date_from;
  1424. $mc->date_to = $this->course_date_to;
  1425. $mc->course_subscription_id = $this->course_course_subscription_id;
  1426. $mc->status = $this->course_status;
  1427. $mc->subscribed = false;
  1428. $mc->price = currencyToDouble($this->course_price);
  1429. $mc->subscription_price = currencyToDouble($this->course_subscription_price);
  1430. $mc->notes = $this->course_note;
  1431. $mc->months = json_encode($this->course_months);
  1432. $mc->when = json_encode($this->course_when);
  1433. $mc->save();
  1434. // Se il corso ha associato una categoria iscrivo anche al gruppo
  1435. $c = \App\Models\Course::findOrFail($this->course_course_id);
  1436. if ($c) {
  1437. if ($c->category_id > 0) {
  1438. if (!\App\Models\MemberCategory::where('member_id', $this->dataId)->where('category_id', $c->category_id)->first()) {
  1439. \App\Models\MemberCategory::create([
  1440. 'member_id' => $this->dataId,
  1441. 'category_id' => $c->category_id,
  1442. 'date' => \Carbon\Carbon::now()
  1443. ]);
  1444. }
  1445. }
  1446. }
  1447. // Creo i pagamenti in base alla tipologia
  1448. $r = \App\Models\CourseSubscription::findOrFail($this->course_course_subscription_id);
  1449. $start = $this->course_date_from;
  1450. // Creo il pagamento per l'iscrizione
  1451. $rate = new \App\Models\Rate();
  1452. $rate->member_id = $this->dataId;
  1453. $rate->member_course_id = $mc->id;
  1454. $rate->course_subscription_id = null;
  1455. $rate->price = currencyToDouble($this->course_subscription_price);
  1456. $rate->date = $start;
  1457. $rate->months = json_encode([]);
  1458. $rate->note = '';
  1459. $rate->status = 0;
  1460. $rate->is_subscription = true;
  1461. $rate->save();
  1462. $go = true;
  1463. while ($go) {
  1464. $mms = [];
  1465. $mms[] = date("n", strtotime($start));
  1466. for ($jj = 1; $jj < $r->months; $jj++) {
  1467. if (date('Ymd', strtotime("+" . $jj . " months", strtotime($start))) < date("Ymd", strtotime($this->course_date_to)))
  1468. {
  1469. $mms[] = date('n', strtotime("+" . $jj . " months", strtotime($start)));
  1470. }
  1471. else
  1472. {
  1473. break;
  1474. }
  1475. }
  1476. $rate = new \App\Models\Rate();
  1477. $rate->member_id = $this->dataId;
  1478. $rate->member_course_id = $mc->id;
  1479. $rate->course_subscription_id = $this->course_course_subscription_id;
  1480. $rate->price = currencyToDouble($this->course_price);
  1481. $rate->date = $start;
  1482. $rate->months = json_encode($mms);
  1483. $rate->note = '';
  1484. $rate->status = 0;
  1485. $rate->save();
  1486. $start = date('Y-m-d', strtotime("+" . $r->months . " months", strtotime($start)));
  1487. if ($start > $this->course_date_to) {
  1488. $go = false;
  1489. break;
  1490. }
  1491. }
  1492. session()->flash('success, Corso creato');
  1493. $this->resetCourseFields();
  1494. $this->addCourse = false;
  1495. $this->emit('setEditCorso', false);
  1496. } catch (\Exception $ex) {
  1497. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1498. }
  1499. }
  1500. public function editCourse($id)
  1501. {
  1502. try {
  1503. $memberCourse = \App\Models\MemberCourse::findOrFail($id);
  1504. if (!$memberCourse) {
  1505. session()->flash('error', 'Corso non trovato');
  1506. } else {
  1507. $this->course_course_id = $memberCourse->course_id;
  1508. // Carico i dati relativi alla struttura ad albero
  1509. $c = \App\Models\Course::findOrFail($this->course_course_id);
  1510. $this->course_name = $c->name . " (" . $c->year . ")";
  1511. $this->course_level_id = $c->course_level_id;
  1512. $this->course_course_type = $c->type;
  1513. $this->course_type_id = $c->course_type_id;
  1514. $this->course_frequency_id = $c->course_frequency_id;
  1515. $all = \App\Models\Course::where('name', 'like', '%' . $c->name . "%")->where('enabled', true)->get();
  1516. foreach ($all as $a) {
  1517. $levels_ids[] = $a->course_level_id;
  1518. }
  1519. $this->course_levels = \App\Models\CourseLevel::select('*')->where('enabled', true)->whereIn('id', $levels_ids)->get();
  1520. $all = \App\Models\Course::where('name', 'like', '%' . $c->name . "%")->where('enabled', true)->where('course_level_id', $this->course_level_id)->get();
  1521. foreach ($all as $a) {
  1522. $types_ids[] = $a->course_type_id;
  1523. }
  1524. // $this->course_types = \App\Models\CourseType::select('*')->where('enabled', true)->whereIn('id', $types_ids)->get();
  1525. $frequencies_ids = [];
  1526. $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();
  1527. foreach ($all as $a) {
  1528. $frequencies_ids[] = $a->course_frequency_id;
  1529. }
  1530. $this->course_frequencies = \App\Models\CourseFrequency::select('*')->where('enabled', true)->whereIn('id', $frequencies_ids)->get();
  1531. $this->course_when = array();
  1532. $this->course_date_from = $memberCourse->date_from;
  1533. $this->course_date_to = $memberCourse->date_to;
  1534. foreach (json_decode($memberCourse->when) as $z) {
  1535. $this->course_when[] = array("day" => $z->day, "from" => $z->from, "to" => $z->to);
  1536. }
  1537. //$this->course_when = json_decode($memberCourse->when);
  1538. $this->course_course_subscription_id = $memberCourse->course_subscription_id;
  1539. $this->course_status = $memberCourse->status;
  1540. $this->course_subscribed = $memberCourse->subscribed == 1 ? true : false;
  1541. $this->course_price = formatPrice($memberCourse->price);
  1542. $this->course_subscription_price = formatPrice($memberCourse->subscription_price);
  1543. $this->course_note = $memberCourse->notes;
  1544. foreach (json_decode($memberCourse->months) as $z) {
  1545. $this->course_months[] = array("m" => $z->m, "status" => $z->status);
  1546. }
  1547. $course_subscription_ids = [];
  1548. $this->course_price_list = [];
  1549. if ($c->prices != null) {
  1550. foreach (json_decode($c->prices) as $z) {
  1551. $this->course_price_list[$z->course_subscription_id] = $z->price;
  1552. if ($z->price > 0)
  1553. $course_subscription_ids[] = $z->course_subscription_id;
  1554. }
  1555. }
  1556. $this->course_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $course_subscription_ids)->where('enabled', true)->get();
  1557. $this->courseDataId = $memberCourse->id;
  1558. $this->updateCourse = true;
  1559. $this->addCourse = false;
  1560. $this->emit('setEditCorso', true);
  1561. }
  1562. } catch (\Exception $ex) {
  1563. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1564. }
  1565. }
  1566. public function updateCourse()
  1567. {
  1568. //$this->validate();
  1569. $this->validate(['course_course_id' => 'required']);
  1570. try {
  1571. \App\Models\MemberCourse::whereId($this->courseDataId)->update([
  1572. 'member_id' => $this->dataId,
  1573. 'course_id' => $this->course_course_id,
  1574. 'date_from' => $this->course_date_from,
  1575. 'date_to' => $this->course_date_to,
  1576. 'course_subscription_id' => $this->course_course_subscription_id,
  1577. 'status' => $this->course_status,
  1578. 'price' => currencyToDouble($this->course_price),
  1579. 'subscription_price' => currencyToDouble($this->course_subscription_price),
  1580. 'notes' => $this->course_note,
  1581. 'months' => json_encode($this->course_months),
  1582. 'when' => json_encode($this->course_when)
  1583. ]);
  1584. session()->flash('success', 'Corso aggiornato');
  1585. $this->resetCourseFields();
  1586. $this->updateCourse = false;
  1587. $this->emit('setEditCorso', false);
  1588. } catch (\Exception $ex) {
  1589. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1590. }
  1591. }
  1592. public function cancelCourse()
  1593. {
  1594. $this->addCourse = false;
  1595. $this->updateCourse = false;
  1596. $this->emit('setEditCorso', false);
  1597. $this->resetCourseFields();
  1598. }
  1599. public function deleteCourse($id)
  1600. {
  1601. try {
  1602. $member_course = \App\Models\MemberCourse::find($id);
  1603. $category = \App\Models\Course::findOrFail($member_course->course_id);
  1604. if ($category) {
  1605. if ($category->category_id > 0) {
  1606. \App\Models\MemberCategory::where('member_id', $this->dataId)->where('category_id', $category->category_id)->delete();
  1607. }
  1608. }
  1609. $member_course->delete();
  1610. session()->flash('success', "Corso eliminato");
  1611. } catch (\Exception $e) {
  1612. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  1613. }
  1614. }
  1615. public function addRow()
  1616. {
  1617. $this->course_when[] = array('day' => array(), 'from' => '', 'to' => '');
  1618. }
  1619. public function delRow($idx)
  1620. {
  1621. unset($this->course_when[$idx]);
  1622. }
  1623. // Certificates
  1624. public function addCertificate()
  1625. {
  1626. $this->resetCertificateFields();
  1627. $this->addCertificate = true;
  1628. $this->updateCertificate = false;
  1629. }
  1630. public function storeCertificate()
  1631. {
  1632. $this->validate(['certificate_expire_date' => 'required']);
  1633. try {
  1634. $certificatePath = '';
  1635. if ($this->certificate_filename) {
  1636. $certificatePath = $this->fileService->uploadCertificate($this->certificate_filename, $this->dataId);
  1637. }
  1638. if ($this->dataId > -1) {
  1639. \App\Models\MemberCertificate::create([
  1640. 'member_id' => $this->dataId,
  1641. 'type' => $this->certificate_type,
  1642. 'filename' => $certificatePath,
  1643. 'expire_date' => $this->certificate_expire_date,
  1644. 'status' => $this->certificate_status
  1645. ]);
  1646. updateMemberData($this->dataId);
  1647. }
  1648. session()->flash('success', 'Certificato creato');
  1649. $this->resetCertificateFields();
  1650. $this->addCertificate = false;
  1651. $this->loadMemberCertificates();
  1652. // TODO $this->checkCourseAvailability();
  1653. } catch (\Exception $ex) {
  1654. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1655. }
  1656. }
  1657. public function editCertificate($id)
  1658. {
  1659. try {
  1660. $memberCertificate = \App\Models\MemberCertificate::findOrFail($id);
  1661. if (!$memberCertificate) {
  1662. session()->flash('error', 'Tesserato non trovato');
  1663. } else {
  1664. $this->certificate_type = $memberCertificate->type;
  1665. $this->certificate_filename_old = $memberCertificate->filename;
  1666. $this->certificate_expire_date = $memberCertificate->expire_date;
  1667. $this->certificate_status = $memberCertificate->status;
  1668. $this->cardCertificateId = $memberCertificate->id;
  1669. $this->updateCertificate = true;
  1670. $this->addCertificate = false;
  1671. }
  1672. } catch (\Exception $ex) {
  1673. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1674. }
  1675. }
  1676. public function updateCertificate()
  1677. {
  1678. $this->validate(['certificate_expire_date' => 'required']);
  1679. try {
  1680. $certificatePath = $this->certificate_filename_old; // Keep existing if no new file
  1681. if ($this->certificate_filename) {
  1682. $certificatePath = $this->fileService->uploadCertificate($this->certificate_filename, $this->dataId);
  1683. }
  1684. \App\Models\MemberCertificate::whereId($this->cardCertificateId)->update([
  1685. 'member_id' => $this->dataId,
  1686. 'type' => $this->certificate_type,
  1687. 'filename' => $certificatePath,
  1688. 'expire_date' => $this->certificate_expire_date,
  1689. 'status' => $this->certificate_status
  1690. ]);
  1691. updateMemberData($this->dataId);
  1692. session()->flash('success', 'Certificato aggiornato');
  1693. $this->resetCertificateFields();
  1694. $this->updateCertificate = false;
  1695. $this->loadMemberCertificates();
  1696. // TODO $this->checkCourseAvailability();
  1697. } catch (\Exception $ex) {
  1698. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1699. }
  1700. }
  1701. public function getFileUrl($filePath)
  1702. {
  1703. if (!$filePath) {
  1704. return null;
  1705. }
  1706. return $this->fileService->getFileUrl($filePath);
  1707. }
  1708. public function cancelCertificate()
  1709. {
  1710. $this->addCertificate = false;
  1711. $this->updateCertificate = false;
  1712. $this->resetCertificateFields();
  1713. }
  1714. public function deleteCertificate($id)
  1715. {
  1716. try {
  1717. \App\Models\MemberCertificate::find($id)->delete();
  1718. session()->flash('success', "Tesserato eliminato");
  1719. } catch (\Exception $e) {
  1720. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  1721. }
  1722. }
  1723. // Gruppi di appartenenza
  1724. public function storeCategory()
  1725. {
  1726. $this->validate(['category_category_id' => 'required']);
  1727. try {
  1728. \App\Models\MemberCategory::create([
  1729. 'member_id' => $this->dataId,
  1730. 'category_id' => $this->category_category_id,
  1731. 'date' => \Carbon\Carbon::now()
  1732. ]);
  1733. session()->flash('success, Associazione creato');
  1734. $this->resetCategoryFields();
  1735. $this->addCard = false;
  1736. } catch (\Exception $ex) {
  1737. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1738. }
  1739. }
  1740. public function hideMsg()
  1741. {
  1742. $this->groupMsg = '';
  1743. }
  1744. public function storeCategoryWithID($id)
  1745. {
  1746. $this->groupMsg = '';
  1747. try {
  1748. if (\App\Models\MemberCategory::where('member_id', $this->dataId)->where('category_id', $id)->first()) {
  1749. $this->groupMsg = '<br>Attenzione, l\'utente fa già parte di questo gruppo';
  1750. } else {
  1751. \App\Models\MemberCategory::create([
  1752. 'member_id' => $this->dataId,
  1753. 'category_id' => $id,
  1754. 'date' => \Carbon\Carbon::now()
  1755. ]);
  1756. session()->flash('success, Associazione creato');
  1757. $this->resetCategoryFields();
  1758. $this->addCard = false;
  1759. }
  1760. } catch (\Exception $ex) {
  1761. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  1762. }
  1763. }
  1764. public function deleteCategory($id)
  1765. {
  1766. try {
  1767. \App\Models\MemberCategory::find($id)->delete();
  1768. session()->flash('success', "Associazione eliminata");
  1769. } catch (\Exception $e) {
  1770. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  1771. }
  1772. }
  1773. public function setCourse($id)
  1774. {
  1775. $this->course_course_id = $id;
  1776. }
  1777. public function getNation($nation)
  1778. {
  1779. if ($nation > 0) {
  1780. $ret = \App\Models\Nation::findOrFail($nation);
  1781. return $ret->name;
  1782. }
  1783. return "";
  1784. }
  1785. public function getProvince($province)
  1786. {
  1787. if ($province > 0) {
  1788. $ret = \App\Models\Province::findOrFail($province);
  1789. return $ret->name;
  1790. }
  1791. return "";
  1792. }
  1793. public function getCity($city)
  1794. {
  1795. if ($city > 0) {
  1796. $ret = \App\Models\City::findOrFail($city);
  1797. return $ret->name;
  1798. }
  1799. return "";
  1800. }
  1801. public function getFiscalCode()
  1802. {
  1803. $this->error_fc = false;
  1804. $cf = new codicefiscale();
  1805. $cf->setDateSeparator('-');
  1806. if ($this->first_name != '' && $this->last_name != '' && $this->birth_date != '' && $this->gender != '' && $this->birth_city_id > 0) {
  1807. $code = '';
  1808. if ($this->birth_city_id > 0) {
  1809. $code = \App\Models\City::findOrFail($this->birth_city_id)->code;
  1810. }
  1811. $codice = $cf->calcola($this->first_name, $this->last_name, $this->birth_date, $this->gender, $code);
  1812. $this->fiscal_code = $codice;
  1813. } else
  1814. $this->error_fc = true;
  1815. }
  1816. public function setMonth($m)
  1817. {
  1818. $exist = -1;
  1819. foreach ($this->course_months as $idx => $x) {
  1820. if ($x["m"] == $m) {
  1821. $exist = $idx;
  1822. break;
  1823. }
  1824. }
  1825. if ($exist > -1) {
  1826. array_splice($this->course_months, $exist, 1);
  1827. } else {
  1828. $this->course_months[] = array("m" => $m, "status" => "");
  1829. }
  1830. }
  1831. public function newPayment($course)
  1832. {
  1833. $c = \App\Models\Course::findOrFail($course["course_id"]);
  1834. $price = $course["price"];
  1835. if (sizeof($this->payMonths) == 1) {
  1836. $month = $this->payMonths[0];
  1837. $records = \App\Models\Record::where('member_course_id', $this->selectedCourseMember)->where('deleted', 0)->get();
  1838. foreach ($records as $record) {
  1839. if (in_array($month, json_decode($record->months))) {
  1840. foreach ($record->rows as $row) {
  1841. if ($row->causal_id == $c->causal_id && !str_contains(strtolower($row->note), 'iscrizione')) {
  1842. $tot = sizeof(json_decode($row->when));
  1843. foreach (json_decode($row->when) as $m) {
  1844. $price -= $row->amount / $tot;
  1845. }
  1846. }
  1847. }
  1848. }
  1849. }
  1850. }
  1851. $this->emit('setEdit', false);
  1852. $this->emit('setEditCorso', false);
  1853. 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"]);
  1854. }
  1855. public function block($course)
  1856. {
  1857. $xxx = json_decode($course["months"]);
  1858. foreach ($xxx as $idx => $mm) {
  1859. if (in_array($mm->m, $this->payMonths)) {
  1860. $xxx[$idx]->status = 2;
  1861. }
  1862. }
  1863. $c = \App\Models\MemberCourse::findOrFail($course["id"]);
  1864. $c->months = json_encode($xxx);
  1865. $c->save();
  1866. $this->payMonths = array();
  1867. }
  1868. public function reactivate($course)
  1869. {
  1870. $xxx = json_decode($course["months"]);
  1871. foreach ($xxx as $idx => $mm) {
  1872. if (in_array($mm->m, $this->suspendedMonths)) {
  1873. $xxx[$idx]->status = "";
  1874. }
  1875. }
  1876. $c = \App\Models\MemberCourse::findOrFail($course["id"]);
  1877. $c->months = json_encode($xxx);
  1878. $c->save();
  1879. $this->suspendedMonths = array();
  1880. }
  1881. public function setPayMonth($m, $months, $selectedCourseMember)
  1882. {
  1883. if ($this->selectedCourseMember != $selectedCourseMember)
  1884. $this->payMonths = array();
  1885. $this->selectedCourseMember = $selectedCourseMember;
  1886. if (in_array($m, $this->payMonths)) {
  1887. $i = array_search($m, $this->payMonths);
  1888. array_splice($this->payMonths, $i, 1);
  1889. } else if (in_array($m, $this->suspendedMonths)) {
  1890. $i = array_search($m, $this->suspendedMonths);
  1891. array_splice($this->suspendedMonths, $i, 1);
  1892. } else {
  1893. foreach (json_decode($months) as $mm) {
  1894. if ($mm->m == $m) {
  1895. if ($mm->status == "")
  1896. $this->payMonths[] = $m;
  1897. if ($mm->status == "1") {
  1898. $mc = \App\Models\MemberCourse::findOrFail($selectedCourseMember);
  1899. $price = $mc->price;
  1900. $payed = 0;
  1901. $extraC = '';
  1902. $recordsPayed = \App\Models\Record::where('member_course_id', $selectedCourseMember)->where('deleted', 0)->get();
  1903. foreach ($recordsPayed as $record) {
  1904. if (in_array($m, json_decode($record->months))) {
  1905. foreach ($record->rows as $row) {
  1906. if ($row->causal_id == $mc->course->causal_id && !str_contains(strtolower($row->note), 'iscrizione')) {
  1907. $tot = sizeof(json_decode($row->when));
  1908. $payed += $row->amount / $tot;
  1909. }
  1910. }
  1911. if ($payed < $price)
  1912. $this->payMonths[] = $m;
  1913. }
  1914. }
  1915. }
  1916. if ($mm->status == "2")
  1917. $this->suspendedMonths[] = $m;
  1918. }
  1919. }
  1920. }
  1921. if (sizeof($this->payMonths) > 0 && sizeof($this->suspendedMonths) > 0) {
  1922. $this->payMonths = array();
  1923. $this->suspendedMonths = array();
  1924. }
  1925. }
  1926. public function setCreateSubscription($subscribed, $selectedCourseMember)
  1927. {
  1928. if ($this->selectedCourseMember != $selectedCourseMember)
  1929. $this->payMonths = array();
  1930. $this->selectedCourseMember = $selectedCourseMember;
  1931. if (!$subscribed)
  1932. $this->createSubscription = !$this->createSubscription;
  1933. }
  1934. public function showHideCourse($id)
  1935. {
  1936. if (in_array($id, $this->showCourse)) {
  1937. $i = array_search($id, $this->showCourse);
  1938. array_splice($this->showCourse, $i, 1);
  1939. } else {
  1940. $this->showCourse[] = $id;
  1941. }
  1942. }
  1943. public function getMonthStatus($m, $months, $selectedCourseMember)
  1944. {
  1945. $class = "grey";
  1946. foreach (json_decode($months) as $mm) {
  1947. if ($mm->m == $m) {
  1948. if ($mm->status == "") {
  1949. if (in_array($m, $this->payMonths) && $this->selectedCourseMember == $selectedCourseMember)
  1950. $class = "blue";
  1951. else
  1952. $class = "orange";
  1953. }
  1954. if ($mm->status == "1") {
  1955. $class = "green";
  1956. }
  1957. if ($mm->status == "2") {
  1958. if (in_array($m, $this->suspendedMonths) && $this->selectedCourseMember == $selectedCourseMember)
  1959. $class = "blue";
  1960. else
  1961. $class = "yellow";
  1962. }
  1963. if ($class == 'green') {
  1964. $mc = \App\Models\MemberCourse::findOrFail($selectedCourseMember);
  1965. $price = $mc->price;
  1966. $payed = 0;
  1967. $extraC = '';
  1968. $recordsPayed = \App\Models\Record::where('member_course_id', $selectedCourseMember)->where('deleted', 0)->get();
  1969. foreach ($recordsPayed as $record) {
  1970. if (in_array($m, json_decode($record->months))) {
  1971. foreach ($record->rows as $row) {
  1972. if ($row->causal_id == $mc->course->causal_id && !str_contains(strtolower($row->note), 'iscrizione')) {
  1973. $tot = sizeof(json_decode($row->when));
  1974. $payed += $row->amount / $tot;
  1975. }
  1976. }
  1977. }
  1978. }
  1979. if ($payed < $price)
  1980. $class = 'orange half';
  1981. }
  1982. }
  1983. }
  1984. return $class;
  1985. }
  1986. public function getSubscriptionStatus($subscribed, $selectedCourseMember)
  1987. {
  1988. $class = "grey";
  1989. if ($this->createSubscription && $this->selectedCourseMember == $selectedCourseMember)
  1990. $class = "blue";
  1991. else
  1992. $class = "orange";
  1993. if ($subscribed)
  1994. $class = "green";
  1995. return $class;
  1996. }
  1997. public function checkMonth($m)
  1998. {
  1999. $ret = false;
  2000. foreach ($this->course_months as $idx => $x) {
  2001. if ($x["m"] == $m) {
  2002. $ret = true;
  2003. break;
  2004. }
  2005. }
  2006. return $ret;
  2007. }
  2008. public function setDay($idx, $d)
  2009. {
  2010. if (in_array($d, $this->course_when[$idx]["day"])) {
  2011. $i = array_search($d, $this->course_when[$idx]["day"]);
  2012. array_splice($this->course_when[$idx]["day"], $i, 1);
  2013. } else {
  2014. $this->course_when[$idx]["day"][] = $d;
  2015. }
  2016. }
  2017. public function updateBorsellino($importoBorsellino, $s)
  2018. {
  2019. if ($importoBorsellino > 0) {
  2020. $imp = $importoBorsellino;
  2021. if ($s == "-")
  2022. $imp = $imp * -1;
  2023. $money = new \App\Models\Money();
  2024. $money->member_id = $this->currentMember->id;
  2025. $money->record_id = null;
  2026. $money->amount = $imp;
  2027. $money->date = date("Y-m-d");
  2028. $money->note = 'Forzato ' . $imp;
  2029. $money->save();
  2030. }
  2031. $this->emit('saved');
  2032. }
  2033. public function getMonth($m)
  2034. {
  2035. $ret = '';
  2036. switch ($m) {
  2037. case 1:
  2038. $ret = 'Gennaio';
  2039. break;
  2040. case 2:
  2041. $ret = 'Febbraio';
  2042. break;
  2043. case 3:
  2044. $ret = 'Marzo';
  2045. break;
  2046. case 4:
  2047. $ret = 'Aprile';
  2048. break;
  2049. case 5:
  2050. $ret = 'Maggio';
  2051. break;
  2052. case 6:
  2053. $ret = 'Giugno';
  2054. break;
  2055. case 7:
  2056. $ret = 'Luglio';
  2057. break;
  2058. case 8:
  2059. $ret = 'Agosto';
  2060. break;
  2061. case 9:
  2062. $ret = 'Settembre';
  2063. break;
  2064. case 10:
  2065. $ret = 'Ottobre';
  2066. break;
  2067. case 11:
  2068. $ret = 'Novembre';
  2069. break;
  2070. case 12:
  2071. $ret = 'Dicembre';
  2072. break;
  2073. default:
  2074. $ret = '';
  2075. break;
  2076. }
  2077. return $ret;
  2078. }
  2079. public function archive($id)
  2080. {
  2081. try {
  2082. $member = \App\Models\Member::findOrFail($id);
  2083. $originalFirstName = $member->first_name;
  2084. $originalLastName = $member->last_name;
  2085. $member->update([
  2086. 'is_archived' => true,
  2087. 'archived_date' => now(),
  2088. 'first_name' => 'Nome Archiviato',
  2089. 'last_name' => 'Cognome Archiviato',
  2090. 'fiscal_code' => null,
  2091. 'email' => null,
  2092. 'phone' => null,
  2093. 'phone2' => null,
  2094. 'phone3' => null,
  2095. 'address' => null,
  2096. 'zip_code' => null,
  2097. 'birth_place' => null,
  2098. 'birth_date' => null,
  2099. 'birth_city_id' => null,
  2100. 'birth_province_id' => null,
  2101. 'birth_nation_id' => null,
  2102. 'nation_id' => null,
  2103. 'province_id' => null,
  2104. 'city_id' => null,
  2105. 'document_type' => null,
  2106. 'document_number' => null,
  2107. 'document_from' => null,
  2108. 'document_expire_date' => null,
  2109. 'document_files' => null,
  2110. 'father_name' => null,
  2111. 'mother_name' => null,
  2112. 'father_email' => null,
  2113. 'mother_email' => null,
  2114. 'father_phone' => null,
  2115. 'mother_phone' => null,
  2116. 'father_fiscal_code' => null,
  2117. 'mother_fiscal_code' => null,
  2118. 'father_doc_number' => null,
  2119. 'father_doc_type' => null,
  2120. 'mother_doc_number' => null,
  2121. 'mother_doc_type' => null,
  2122. 'father_document_files' => null,
  2123. 'mother_document_files' => null,
  2124. 'image' => null,
  2125. 'gender' => null,
  2126. 'status' => 'archived',
  2127. 'enabled' => false
  2128. ]);
  2129. updateMemberData($id);
  2130. session()->flash('success', 'Membro archiviato con successo');
  2131. $this->emit('reload');
  2132. } catch (\Exception $e) {
  2133. session()->flash('error', 'Errore durante l\'archiviazione: ' . $e->getMessage());
  2134. Log::error('Archive member error', [
  2135. 'member_id' => $id,
  2136. 'error' => $e->getMessage(),
  2137. 'trace' => $e->getTraceAsString()
  2138. ]);
  2139. }
  2140. }
  2141. }
  2142. class codicefiscale
  2143. {
  2144. /**
  2145. * Array delle consonanti
  2146. */
  2147. protected $_consonanti = array(
  2148. 'B',
  2149. 'C',
  2150. 'D',
  2151. 'F',
  2152. 'G',
  2153. 'H',
  2154. 'J',
  2155. 'K',
  2156. 'L',
  2157. 'M',
  2158. 'N',
  2159. 'P',
  2160. 'Q',
  2161. 'R',
  2162. 'S',
  2163. 'T',
  2164. 'V',
  2165. 'W',
  2166. 'X',
  2167. 'Y',
  2168. 'Z'
  2169. );
  2170. /**
  2171. * Array delle vocali
  2172. */
  2173. protected $_vocali = array(
  2174. 'A',
  2175. 'E',
  2176. 'I',
  2177. 'O',
  2178. 'U'
  2179. );
  2180. /**
  2181. * Array per il calcolo della lettera del mese
  2182. * Al numero del mese corrisponde una lettera
  2183. */
  2184. protected $_mesi = array(
  2185. 1 => 'A',
  2186. 2 => 'B',
  2187. 3 => 'C',
  2188. 4 => 'D',
  2189. 5 => 'E',
  2190. 6 => 'H',
  2191. 7 => 'L',
  2192. 8 => 'M',
  2193. 9 => 'P',
  2194. 10 => 'R',
  2195. 11 => 'S',
  2196. 12 => 'T'
  2197. );
  2198. protected $_pari = array(
  2199. '0' => 0,
  2200. '1' => 1,
  2201. '2' => 2,
  2202. '3' => 3,
  2203. '4' => 4,
  2204. '5' => 5,
  2205. '6' => 6,
  2206. '7' => 7,
  2207. '8' => 8,
  2208. '9' => 9,
  2209. 'A' => 0,
  2210. 'B' => 1,
  2211. 'C' => 2,
  2212. 'D' => 3,
  2213. 'E' => 4,
  2214. 'F' => 5,
  2215. 'G' => 6,
  2216. 'H' => 7,
  2217. 'I' => 8,
  2218. 'J' => 9,
  2219. 'K' => 10,
  2220. 'L' => 11,
  2221. 'M' => 12,
  2222. 'N' => 13,
  2223. 'O' => 14,
  2224. 'P' => 15,
  2225. 'Q' => 16,
  2226. 'R' => 17,
  2227. 'S' => 18,
  2228. 'T' => 19,
  2229. 'U' => 20,
  2230. 'V' => 21,
  2231. 'W' => 22,
  2232. 'X' => 23,
  2233. 'Y' => 24,
  2234. 'Z' => 25
  2235. );
  2236. protected $_dispari = array(
  2237. '0' => 1,
  2238. '1' => 0,
  2239. '2' => 5,
  2240. '3' => 7,
  2241. '4' => 9,
  2242. '5' => 13,
  2243. '6' => 15,
  2244. '7' => 17,
  2245. '8' => 19,
  2246. '9' => 21,
  2247. 'A' => 1,
  2248. 'B' => 0,
  2249. 'C' => 5,
  2250. 'D' => 7,
  2251. 'E' => 9,
  2252. 'F' => 13,
  2253. 'G' => 15,
  2254. 'H' => 17,
  2255. 'I' => 19,
  2256. 'J' => 21,
  2257. 'K' => 2,
  2258. 'L' => 4,
  2259. 'M' => 18,
  2260. 'N' => 20,
  2261. 'O' => 11,
  2262. 'P' => 3,
  2263. 'Q' => 6,
  2264. 'R' => 8,
  2265. 'S' => 12,
  2266. 'T' => 14,
  2267. 'U' => 16,
  2268. 'V' => 10,
  2269. 'W' => 22,
  2270. 'X' => 25,
  2271. 'Y' => 24,
  2272. 'Z' => 23
  2273. );
  2274. protected $_controllo = array(
  2275. '0' => 'A',
  2276. '1' => 'B',
  2277. '2' => 'C',
  2278. '3' => 'D',
  2279. '4' => 'E',
  2280. '5' => 'F',
  2281. '6' => 'G',
  2282. '7' => 'H',
  2283. '8' => 'I',
  2284. '9' => 'J',
  2285. '10' => 'K',
  2286. '11' => 'L',
  2287. '12' => 'M',
  2288. '13' => 'N',
  2289. '14' => 'O',
  2290. '15' => 'P',
  2291. '16' => 'Q',
  2292. '17' => 'R',
  2293. '18' => 'S',
  2294. '19' => 'T',
  2295. '20' => 'U',
  2296. '21' => 'V',
  2297. '22' => 'W',
  2298. '23' => 'X',
  2299. '24' => 'Y',
  2300. '25' => 'Z'
  2301. );
  2302. /**
  2303. * Stringa di errore
  2304. */
  2305. protected $_error = null;
  2306. /**
  2307. * Separatore per la data di nascita
  2308. */
  2309. protected $_dateSeparator = '/';
  2310. /**
  2311. * Percorso del file del database SQLite
  2312. * dei codici catastali
  2313. */
  2314. protected $_dbCatastali = null;
  2315. /**
  2316. * Trasforma la stringa passata in un array di lettere
  2317. * e lo incrocia con un ulteriore array
  2318. */
  2319. protected function _getLettere($string, array $haystack)
  2320. {
  2321. $letters = array();
  2322. foreach (str_split($string) as $needle) {
  2323. if (in_array($needle, $haystack)) {
  2324. $letters[] = $needle;
  2325. }
  2326. }
  2327. return $letters;
  2328. }
  2329. /**
  2330. * Ritorna un array con le vocali di una data stringa
  2331. */
  2332. protected function _getVocali($string)
  2333. {
  2334. return $this->_getLettere($string, $this->_vocali);
  2335. }
  2336. /**
  2337. * Ritorna un array con le consonanti di una data stringa
  2338. */
  2339. protected function _getConsonanti($string)
  2340. {
  2341. return $this->_getLettere($string, $this->_consonanti);
  2342. }
  2343. /**
  2344. * Pulisce la stringa filtrando tutti i caratteri che
  2345. * non sono lettere. Lo switch $toupper se impostato a TRUE
  2346. * converte la stringa risultante in MAIUSCOLO.
  2347. */
  2348. protected function _sanitize($string, $toupper = true)
  2349. {
  2350. $result = preg_replace('/[^A-Za-z]*/', '', $string);
  2351. return ($toupper) ? strtoupper($result) : $result;
  2352. }
  2353. /**
  2354. * Se la stringa passata a funzione e' costituita
  2355. * da meno di 3 caratteri, rimpiazza le lettere
  2356. * mancanti con la lettera X.
  2357. */
  2358. protected function _addMissingX($string)
  2359. {
  2360. $code = $string;
  2361. while (strlen($code) < 3) {
  2362. $code .= 'X';
  2363. }
  2364. return $code;
  2365. }
  2366. /**
  2367. * Ottiene il codice identificativo del nome
  2368. */
  2369. protected function _calcolaNome($string)
  2370. {
  2371. $nome = $this->_sanitize($string);
  2372. $code = '';
  2373. // Se il nome inserito e' piu' corto di 3 lettere
  2374. // si aggiungono tante X quanti sono i caratteri
  2375. // mancanti.
  2376. if (strlen($nome) < 3) {
  2377. return $this->_addMissingX($nome);
  2378. }
  2379. $nome_cons = $this->_getConsonanti($nome);
  2380. // Se le consonanti contenute nel nome sono minori
  2381. // o uguali a 3 vengono considerate nell'ordine in cui
  2382. // compaiono.
  2383. if (count($nome_cons) <= 3) {
  2384. $code = implode('', $nome_cons);
  2385. } else {
  2386. // Se invece abbiamo almeno 4 consonanti, prendiamo
  2387. // la prima, la terza e la quarta.
  2388. for ($i = 0; $i < 4; $i++) {
  2389. if ($i == 1) continue;
  2390. if (!empty($nome_cons[$i])) {
  2391. $code .= $nome_cons[$i];
  2392. }
  2393. }
  2394. }
  2395. // Se compaiono meno di 3 consonanti nel nome, si
  2396. // utilizzano le vocali, nell'ordine in cui compaiono
  2397. // nel nome.
  2398. if (strlen($code) < 3) {
  2399. $nome_voc = $this->_getVocali($nome);
  2400. while (strlen($code) < 3) {
  2401. $code .= array_shift($nome_voc);
  2402. }
  2403. }
  2404. return $code;
  2405. }
  2406. protected function _calcolaCognome($string)
  2407. {
  2408. $cognome = $this->_sanitize($string);
  2409. $code = '';
  2410. // Se il cognome inserito e' piu' corto di 3 lettere
  2411. // si aggiungono tante X quanti sono i caratteri
  2412. // mancanti.
  2413. if (strlen($cognome) < 3) {
  2414. return $this->_addMissingX($cognome);
  2415. }
  2416. $cognome_cons = $this->_getConsonanti($cognome);
  2417. // Per il calcolo del cognome si prendono le prime
  2418. // 3 consonanti.
  2419. for ($i = 0; $i < 3; $i++) {
  2420. if (array_key_exists($i, $cognome_cons)) {
  2421. $code .= $cognome_cons[$i];
  2422. }
  2423. }
  2424. // Se le consonanti non bastano, vengono prese
  2425. // le vocali nell'ordine in cui compaiono.
  2426. if (strlen($code) < 3) {
  2427. $cognome_voc = $this->_getVocali($cognome);
  2428. while (strlen($code) < 3) {
  2429. $code .= array_shift($cognome_voc);
  2430. }
  2431. }
  2432. return $code;
  2433. }
  2434. /**
  2435. * Imposta il separatore di data ( default: / )
  2436. */
  2437. public function setDateSeparator($char)
  2438. {
  2439. $this->_dateSeparator = $char;
  2440. return $this;
  2441. }
  2442. /**
  2443. * Ritorna la parte di codice fiscale corrispondente
  2444. * alla data di nascita del soggetto (Forma: AAMGG)
  2445. */
  2446. protected function _calcolaDataNascita($data, $sesso)
  2447. {
  2448. $dn = explode($this->_dateSeparator, $data);
  2449. $giorno = (int) @$dn[2];
  2450. $mese = (int) @$dn[1];
  2451. $anno = (int) @$dn[0];
  2452. // Le ultime due cifre dell'anno di nascita
  2453. $aa = substr($anno, -2);
  2454. // La lettera corrispondente al mese di nascita
  2455. $mm = $this->_mesi[$mese];
  2456. // Il giorno viene calcolato a seconda del sesso
  2457. // del soggetto di cui si calcola il codice:
  2458. // se e' Maschio si mette il giorno reale, se e'
  2459. // Femmina viene aggiungo 40 a questo numero.
  2460. $gg = (strtoupper($sesso) == 'M') ? $giorno : ($giorno + 40);
  2461. // Bug #1: Thanks to Luca
  2462. if (strlen($gg) < 2) $gg = '0' . $gg;
  2463. return $aa . $mm . $gg;
  2464. }
  2465. /**
  2466. * Ritorna la cifra di controllo sulla base dei
  2467. * 15 caratteri del codice fiscale calcolati.
  2468. */
  2469. protected function _calcolaCifraControllo($codice)
  2470. {
  2471. $code = str_split($codice);
  2472. $sum = 0;
  2473. for ($i = 1; $i <= count($code); $i++) {
  2474. $cifra = $code[$i - 1];
  2475. $sum += ($i % 2) ? $this->_dispari[$cifra] : $this->_pari[$cifra];
  2476. }
  2477. $sum %= 26;
  2478. return $this->_controllo[$sum];
  2479. }
  2480. /**
  2481. * Imposta il messaggio di errore
  2482. */
  2483. protected function _setError($string)
  2484. {
  2485. $this->_error = $string;
  2486. }
  2487. /**
  2488. * Verifica la presenza di un errore.
  2489. * Ritorna TRUE se presente, FALSE altrimenti.
  2490. */
  2491. public function hasError()
  2492. {
  2493. return !is_null($this->_error);
  2494. }
  2495. /**
  2496. * Ritorna la stringa di errore
  2497. */
  2498. public function getError()
  2499. {
  2500. return $this->_error;
  2501. }
  2502. /**
  2503. * Ritorna il codice fiscale utilizzando i parametri
  2504. * passati a funzione. Se si verifica
  2505. */
  2506. public function calcola($nome, $cognome, $data, $sesso, $comune)
  2507. {
  2508. $codice = $this->_calcolaCognome($cognome) .
  2509. $this->_calcolaNome($nome) .
  2510. $this->_calcolaDataNascita($data, $sesso) .
  2511. $comune;
  2512. if ($this->hasError()) {
  2513. return false;
  2514. }
  2515. $codice .= $this->_calcolaCifraControllo($codice);
  2516. if (strlen($codice) != 16) {
  2517. return 'ERROR';
  2518. }
  2519. return $codice;
  2520. }
  2521. }