Member.php 101 KB

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