Member.php 100 KB

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