Member.php 99 KB

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