Member.php 102 KB

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