Member.php 120 KB

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