Member.php 99 KB

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