Member.php 120 KB

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