Member.php 100 KB

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