Member.php 101 KB

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