Member.php 102 KB

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