Member.php 97 KB

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