Member.php 101 KB

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