Member.php 99 KB

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