Member.php 100 KB

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