Member.php 120 KB

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