Member.php 98 KB

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