Member.php 120 KB

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