app.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. // file:///Users/francoisbeaufils/Downloads/geocoder-demo-master/index.html
  2. var app = angular.module('application', ['ngMaterial', 'adaptive.detection', 'ui.bootstrap.typeahead']);
  3. app.directive('skrollr', function() {
  4. var directiveDefinitionObject = {
  5. link: function() {
  6. skrollr.init();
  7. }
  8. };
  9. return directiveDefinitionObject;
  10. });
  11. app.controller('mainController', function($scope, $detection, $http, $mdSidenav, $timeout, $sce, $mdToast) {
  12. $scope.title = "Manche Numerique";
  13. var getGeoCodeInProgress = false,
  14. nbJoursFTTH = 244,
  15. siteName = 'Eligibilité Manche Numérique',
  16. siteUrl = 'http://eligibilite.manchenumerique.fr',
  17. siteEmail = 'ftth@manchenumerique.fr',
  18. siteAddresse = '235, rue Joseph Cugnot Zone Delta, 50000 SAINT LÔ',
  19. layer = {},
  20. currentMarker, searchExtent;
  21. var catTypeVoie = [
  22. {
  23. "name": "Allée",
  24. "id" : "allee"
  25. },
  26. {
  27. "name": "Avenue",
  28. "id" : "avenue"
  29. },
  30. {
  31. "name": "Boulevard",
  32. "id" : "boulevard"
  33. },
  34. {
  35. "name": "Carrefour",
  36. "id" : "carrefour"
  37. },
  38. {
  39. "name": "Chemin",
  40. "id" : "chemin"
  41. },
  42. {
  43. "name": "Cité",
  44. "id" : "cite"
  45. },
  46. {
  47. "name": "Hammeau",
  48. "id" : "hammeau"
  49. },
  50. {
  51. "name": "Impasse",
  52. "id" : "impasse"
  53. },
  54. {
  55. "name": "Lieu-dit",
  56. "id" : "lieu_dit"
  57. },
  58. {
  59. "name": "Lotissement",
  60. "id" : "lotissement"
  61. },
  62. {
  63. "name": "Place",
  64. "id" : "place"
  65. },
  66. {
  67. "name": "Résidence",
  68. "id" : "residence"
  69. },
  70. {
  71. "name": "Route",
  72. "id" : "route"
  73. },
  74. {
  75. "name": "Rue",
  76. "id" : "rue"
  77. },
  78. {
  79. "name": "Villa",
  80. "id" : "villa"
  81. },
  82. {
  83. "name": "Village",
  84. "id" : "village"
  85. }
  86. ];
  87. var catVousEtes = [
  88. {
  89. "name": "Locataire de ce logement",
  90. "id" : "locataire"
  91. },
  92. {
  93. "name": "Occupant à titre gratuit de ce logement",
  94. "id" : "occupant_gratuit"
  95. },
  96. {
  97. "name": "Propriétaire de ce logement",
  98. "id" : "proprietaire"
  99. }
  100. ];
  101. var catCeLogementEst = [
  102. {
  103. "name": "Votre résidence principale",
  104. "id" : "residence_principale"
  105. },
  106. {
  107. "name": "Votre résidence secondaire",
  108. "id" : "residence_secondaire"
  109. }
  110. ];
  111. $scope.formulaires = {
  112. "eligibilite": {
  113. "sections": [
  114. {
  115. "name": "Générale",
  116. "visible": false,
  117. "lines": [
  118. {
  119. "ctrls": [
  120. {
  121. "name" : "Prénom",
  122. "id" : "prenom",
  123. "type" : "text",
  124. "width" : "50%",
  125. "require": true,
  126. "isValid": function(value) {
  127. return !!value && value.length > 2;
  128. },
  129. "msg" : 'Prénom invalide'
  130. },
  131. {
  132. "name" : "Nom",
  133. "id" : "nom",
  134. "type" : "text",
  135. "width" : "50%",
  136. "require": true,
  137. "isValid": function(value) {
  138. return !!value && value.length > 2;
  139. },
  140. "msg" : 'Nom invalide'
  141. }
  142. ]
  143. },
  144. {
  145. "ctrls": [
  146. {
  147. "name" : "Email",
  148. "id" : "email",
  149. "type" : "text",
  150. "width" : null,
  151. "require": true,
  152. "isValid": function(value) {
  153. function validateEmail(email) {
  154. var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
  155. return re.test(email);
  156. }
  157. return validateEmail(value);
  158. },
  159. "msg" : 'Email invalide.'
  160. }
  161. ]
  162. },
  163. {
  164. "ctrls": [
  165. {
  166. "name" : "Téléphone fixe",
  167. "id" : "telephone_fixe",
  168. "type" : "text",
  169. "width" : "50%",
  170. "require": false
  171. },
  172. {
  173. "name" : "Téléphone portable",
  174. "id" : "telephone_portable",
  175. "type" : "text",
  176. "width" : "50%",
  177. "require": false
  178. }
  179. ]
  180. }
  181. ]
  182. },
  183. {
  184. "name": "Adresse",
  185. "visible": true,
  186. "lines": [
  187. {
  188. "ctrls": [
  189. {
  190. "name" : "Numero",
  191. "id" : "numero_voie",
  192. "type" : "text",
  193. "width" : "80px",
  194. "require": false
  195. },
  196. {
  197. "name" : "Type voie",
  198. "id" : "type_voie",
  199. "type" : "select",
  200. "width" : "106px",
  201. "require": false,
  202. "options": {
  203. "categories": catTypeVoie
  204. }
  205. },
  206. {
  207. "name" : "Nom voie",
  208. "id" : "nom_voie",
  209. "type" : "text",
  210. "width" : "378px",
  211. "require": true,
  212. "isValid": function(value) {
  213. return !!value;
  214. },
  215. "msg" : 'Nom de voie invalide.'
  216. }
  217. ]
  218. },
  219. {
  220. "ctrls": [
  221. {
  222. "name" : "Complément Adresse",
  223. "id" : "complement_addresse",
  224. "type" : "textarea",
  225. "width" : null,
  226. "require": false
  227. }
  228. ]
  229. },
  230. {
  231. "ctrls": [
  232. {
  233. "name" : "Bâtiment",
  234. "id" : "batiment",
  235. "type" : "text",
  236. "width" : "50%",
  237. "require": false
  238. },
  239. {
  240. "name" : "Cage escalier",
  241. "id" : "cage_escalier",
  242. "type" : "text",
  243. "width" : "50%",
  244. "require": false
  245. }
  246. ]
  247. },
  248. {
  249. "ctrls": [
  250. {
  251. "name" : "Etage / Niveau",
  252. "id" : "etage",
  253. "type" : "text",
  254. "width" : "50%",
  255. "require": false
  256. },
  257. {
  258. "name" : "Numero appartement / porte",
  259. "id" : "numero_appartement",
  260. "type" : "text",
  261. "width" : "50%",
  262. "require": false
  263. }
  264. ]
  265. },
  266. {
  267. "ctrls": [
  268. {
  269. "name" : "Code postal",
  270. "id" : "code_postal",
  271. "type" : "text",
  272. "width" : "50%",
  273. "require": true,
  274. "isValid": function(value) {
  275. if(!value || value.length !== 5 || isNaN(parseInt(value, 10))) {
  276. return false;
  277. }
  278. return true;
  279. },
  280. "msg" : 'Non valide'
  281. },
  282. {
  283. "name" : "Ville",
  284. "id" : "ville",
  285. "type" : "text",
  286. "width" : "50%",
  287. "require": true,
  288. "isValid": function(value) {
  289. return !!value && value.length > 2;
  290. },
  291. "msg" : 'Ville invalide.'
  292. }
  293. ]
  294. }
  295. ]
  296. },
  297. {
  298. "name": "Logement",
  299. "visible": true,
  300. "lines": [
  301. {
  302. "ctrls": [
  303. {
  304. "name" : "Vous êtes",
  305. "id" : "vous_etes",
  306. "type" : "radio",
  307. "width" : null,
  308. "require": true,
  309. "options": {
  310. "categories": catVousEtes,
  311. "alertes": {
  312. "locataire": "Si vous êtes locataire, vous devez impérativement avertir votre propriétaire que vous souhaitez bénéficier du pré-raccordement à la fibre optique."
  313. }
  314. },
  315. "isValid": function(value, other) {
  316. return !!value && value !== 'autre' || !!other;
  317. },
  318. "msg" : 'Choix incomplet.'
  319. }
  320. ]
  321. },
  322. {
  323. "ctrls": [
  324. {
  325. "name" : "Ce logement est",
  326. "id" : "ce_logement_est",
  327. "type" : "radio",
  328. "width" : null,
  329. "require": true,
  330. "options": {
  331. "categories": catCeLogementEst
  332. },
  333. "isValid": function(value, other) {
  334. return !!value && value !== 'autre' || !!other;
  335. },
  336. "msg" : 'Choix incomplet.'
  337. }
  338. ]
  339. }
  340. ]
  341. },
  342. {
  343. "name": "Conditions pour le raccordement final d’abonné dans un immeuble individuel",
  344. "visible": true,
  345. "lines": [
  346. {
  347. "text": "Manche Numérique propose aux personnes qui le souhaitent, de faire d’ores et déjà raccorder leur logement ou local à usage professionnel, au futur réseau de communications électroniques à Très Haut Débit FTTH. Le montant de ce raccordement s’élevera à 50 € pour les personnes qui souscriront à une offre Très Haut Débit auprès d’un opérateur et de 400 € pour ceux qui demanderont uniquement la pose de la prise, sans souscription d’un abonnement.",
  348. "ctrls": [
  349. {
  350. "name" : "Accord",
  351. "id" : "accord",
  352. "libelle": "Je souhaite être pré-raccordé au réseau de fibre optique et accepte les conditions de paiement de 50€. IMPORTANT : le règlement ne vous sera demandé qu’après travaux effectués",
  353. "type" : "checkbox",
  354. "width" : null,
  355. "require": true,
  356. "isValid": function(value) {
  357. return !!value;
  358. },
  359. "msg" : 'Vous devez doner votre accord.'
  360. }
  361. ]
  362. }
  363. ]
  364. },
  365. {
  366. "name": "Informatique et libertés",
  367. "visible": false,
  368. "lines": [
  369. {
  370. "ctrls": [
  371. {
  372. "name" : "Informatique et libertés",
  373. "id" : "info_et_libertes",
  374. "libelle": 'La personne responsable du traitement de la présente demande de pré-raccordement est le représentant du Syndicat Mixte Manche Numérique, le Président, Monsieur Serge DESLANDES. Les informations portées sur ce formulaire sont obligatoires. Elles font l’objet d’un traitement informatisé destiné au raccordement final de l’usager à la fibre optique (FTTH) ainsi qu’à l’exploitation du réseau optique. Les destinataires des données sont : le Syndicat Mixte Manche Numérique, les entreprises en charge de réaliser les travaux de raccordement, ainsi que l’exploitant du réseau optique. Conformément à la loi "informatique et libertés" du 6 janvier 1978 modifiée, vous bénéficiez d’un droit d’accès, de rectification aux informations qui vous concernent, d’opposition au traitement de vos données personnelles. Si vous souhaitez exercer ce droit et obtenir communication des informations vous concernant, veuillez-vous adresser au Syndicat Mixte Manche Numérique ftth@manchenumerique.fr. Dans l’hypothèse où le présent formulaire est incomplet et/ou illisible, la présente demande de raccordement ne sera pas traitée.',
  375. "type" : "checkbox",
  376. "width" : null,
  377. "require": true,
  378. "isValid": function(value) {
  379. return !!value;
  380. },
  381. "msg" : 'Vous devez accepter.'
  382. }
  383. ]
  384. }
  385. ]
  386. },
  387. {
  388. "name": "Souscription",
  389. "visible": false,
  390. "lines": [
  391. {
  392. "ctrls": [
  393. {
  394. "name" : "Souscription",
  395. "id" : "souscription_engagement",
  396. "libelle": 'Vous vous engagez à souscrire un abonnement chez un operateur 50 euros, sinon 400 euros.',
  397. "type" : "checkbox",
  398. "width" : null,
  399. "require": true,
  400. "isValid": function(value) {
  401. return !!value;
  402. },
  403. "msg" : 'Vous devez accepter.'
  404. }
  405. ]
  406. }
  407. ]
  408. }
  409. ]
  410. }
  411. };
  412. var addCurrentMarker = function() {
  413. if(currentMarker) {
  414. map.removeLayer(currentMarker);
  415. }
  416. currentMarker = L.marker([$scope.geoCode.y, $scope.geoCode.x], {draggable: true, title: "texst"}).addTo(map); //.bindPopup(data.locations[0].name).openPopup();
  417. currentMarker.bindPopup("L'adresse que vous nous avez fournie est localisée sur la carte. Il se peut que la position réelle de votre logement soit un peu différente. Dans ce cas, merci de déplacer le pointeur sur la carte pour le positionner à l'emplacement de votre logement.").openPopup();
  418. reverseLocation($scope.geoCode, null, function(address) {
  419. $scope.address = address;
  420. });
  421. currentMarker.on('dragend', function(event) {
  422. var p = currentMarker.getLatLng();
  423. //console.log('dragend', p);
  424. $scope.geoCode = {
  425. x: p.lng,
  426. y: p.lat
  427. };
  428. reverseLocation($scope.geoCode, null, function(address) {
  429. $scope.address = address;
  430. ariaz(address, function(result) {
  431. //console.log('ariaz', result);
  432. });
  433. getResults();
  434. });
  435. });
  436. };
  437. var ariaz = function(address, callback) {
  438. var url = 'http://www.eligibilite-adsl.com/testXmlAriase.php?ip=80.13.25.43&insee=35238&rivoli=8993&numeroVoie=2&complementNumeroVoie=';
  439. $.get(
  440. url,
  441. function(data, status) {
  442. callback(data);
  443. });
  444. };
  445. var computeDateFTTH = function() {
  446. if(!$scope.results.ftth) {return;}
  447. // A date already exists
  448. if($scope.results.ftth.DATE_OUV_SERVICE_REEL || $scope.results.ftth.DATE_OUV_SERVICE_PREV) {
  449. $scope.results.ftth.date = $scope.results.ftth.DATE_OUV_SERVICE_REEL || $scope.results.ftth.DATE_OUV_SERVICE_PREV;
  450. return;
  451. }
  452. // Compute Date
  453. var momentDate = moment($scope.results.ftth.DATE_FIN_TRAV_PREV, 'DD/MM/YY');
  454. momentDate.add(nbJoursFTTH, 'days');
  455. $scope.results.ftth.date = momentDate.format('DD/MM/YYYY');
  456. };
  457. var computeFullAdress = function() {
  458. return $scope.result.eligibilite.complement_addresse;
  459. };
  460. var formatDate = function(value) {
  461. return moment(value.toString().substr(0,4) + '-' + value.toString().substr(4,2) + '-' + value.toString().substr(6,2)).locale("fr");
  462. };
  463. var getRecordsFor = function(identifier, coordinates) {
  464. var records = [];
  465. _.each($scope.data[identifier], function(record) {
  466. _.some(record._polygons, function(polygon) {
  467. if(isInside(polygon, coordinates)) {
  468. records.push(record);
  469. return true;
  470. }
  471. });
  472. });
  473. // Debug
  474. var debug = false;
  475. if (debug) {
  476. var colors = ['red', 'green', 'blue', 'black', 'silver', 'yellow'];
  477. var marker = L.marker([coordinates.y, coordinates.x]).addTo(map);
  478. var Lpolygons = [];
  479. _.each(records, function(record, i) {
  480. var style = {
  481. color : colors[i],
  482. fillColor: colors[i],
  483. weight : 4
  484. };
  485. _.each(record._polygons, function(polygon) {
  486. Lpolygons.push(L.polygon(polygon, style).bindPopup($scope.getHtmlContent(identifier, record)));
  487. });
  488. });
  489. L.layerGroup(Lpolygons).addTo(map);
  490. }
  491. return records;
  492. };
  493. var getResults = function() {
  494. $scope.results = {};
  495. $.ajax({
  496. method : "POST",
  497. url : "ajax/oracle.php",
  498. data : $scope.geoCode
  499. })
  500. .error(function(err) {
  501. console.error('Oracle issue', err);
  502. // Debug without Oracle access
  503. onResults('{"x":-1.1060984089996,"y":49.119046582,"ftth":[{"ID_ZAPM_PARTIELLE":"203AP0","DATE_OUV_SERVICE_REEL":null,"DATE_OUV_SERVICE_PREV":null,"DATE_FIN_TRAV_PREV":"02\/05\/16"}],"adsl":[{"ID_FT_ADSL":"656","LEGENDE":"TV sur ADSL","NATURE":"0 - 37"}],"mimo":null}');
  504. })
  505. .done(function( msg ) {
  506. onResults(msg);
  507. });
  508. var onResults = function(results) {
  509. try {
  510. $scope.results = JSON.parse(results);
  511. $scope.results.address = $scope.address;
  512. $scope.results.ftth = parseResults($scope.results.ftth);
  513. $scope.results.adsl = parseResults($scope.results.adsl);
  514. $scope.results.mimo = parseResults($scope.results.mimo);
  515. computeDateFTTH();
  516. }
  517. catch(e) {
  518. console.error(e);
  519. }
  520. //console.log('$scope.results', $scope.results);
  521. };
  522. $scope.$evalAsync();
  523. };
  524. var init = function() {
  525. var stlo = [49.1154686, -1.0828136000000086];
  526. var map = L.map('map', {zoomControl:false}).setView(stlo, 9);
  527. map.on('dblclick', function(e) {
  528. var p = e.latlng;
  529. //console.log('click', e.latlng); // e is an event object (MouseEvent in this case)
  530. $scope.geoCode = {
  531. x: p.lng,
  532. y: p.lat
  533. };
  534. addCurrentMarker();
  535. $scope.showResultPane();
  536. getResults();
  537. });
  538. var maps = {
  539. "carte" : 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
  540. "satellite" : 'http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
  541. };
  542. var cLayer = L.tileLayer(maps.satellite, {
  543. attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  544. maxZoom: 18
  545. }).addTo(map);
  546. var styleOpts = {
  547. color : 'red',
  548. fillColor: 'red',
  549. weight : 8
  550. };
  551. $scope.data = {};
  552. $scope.colors = {
  553. "ftth": "#8cc474", // green
  554. "mimo": "#f9b256", // orange
  555. "adsl": "#76a7fa" // blue
  556. };
  557. $http({method: 'POST', url: 'data/dictionary.json'}).success(function(data) {
  558. $scope.dictionary = data;
  559. });
  560. $http({method: 'POST', url: 'data/Contour_Manche.json'}).success(function(data) {
  561. var style = {
  562. color : 'blue',
  563. fillColor: 'blue',
  564. weight : 2
  565. };
  566. $scope.data.manche = [{
  567. _polygons : [data.features[0].geometry.coordinates[0]],
  568. _style : style,
  569. _properties : {
  570. name : {string: 'Manche'}
  571. }
  572. }];
  573. var mancheCoordinates = data && data.features && data.features[0] && data.features[0].geometry && data.features[0].geometry.coordinates && data.features[0].geometry.coordinates[0]; // response data
  574. _.each(mancheCoordinates, function(c, i) {
  575. mancheCoordinates[i] = [c[1], c[0]];
  576. });
  577. // Rectangle coordinates around Manche
  578. //var mancheCoordinates = [[49.732307856286, -1.97117692088061],[48.4, -1.75],[48.4, -0.5],[49.732307856286, -1.2]];
  579. // Debug: show manche limits
  580. //L.polygon(mancheCoordinates, {color: 'blue', fillColor: 'blue',weight: 8}).addTo(map);
  581. searchExtent = {
  582. "xmin" : _.max(_.map(mancheCoordinates, function(c) {return c[1];})),
  583. "ymin" : _.max(_.map(mancheCoordinates, function(c) {return c[0];})),
  584. "xmax" : _.min(_.map(mancheCoordinates, function(c) {return c[1];})),
  585. "ymax" : _.min(_.map(mancheCoordinates, function(c) {return c[0];})),
  586. "spatialReference" : {"wkid" : 84}
  587. };
  588. var suggestURL = 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/suggest?f=pjson&searchExtent=' + JSON.stringify(searchExtent);
  589. var i = 0, j = 0;
  590. $scope.suggestLocation = function(val) {
  591. console.log('__suggestLocation', val);
  592. $scope.suggestionsReady = false;
  593. i++;
  594. return $http.get(suggestURL, {
  595. params: {
  596. text: val
  597. }
  598. }).then(function(response) {
  599. if(val === $scope.address) { // Very important to debounce queries
  600. $scope.suggestionsReady = response.data.suggestions.length !== 0;
  601. $scope.suggestions = _.cloneDeep(response.data.suggestions);
  602. }
  603. return response.data.suggestions.map(function(item){
  604. return item.text;
  605. });
  606. });
  607. };
  608. });
  609. //console.time('FTTH data');
  610. $http({method: 'POST', url: 'data/FTTH_zapm_partielle.json'}).success(function(data) {
  611. var style = {
  612. color : $scope.colors.ftth,
  613. fillColor: $scope.colors.ftth,
  614. weight : 2
  615. };
  616. var properties = {
  617. name : {key: 'ATD'},
  618. hidden: ['ID_PM', 'MARCHE', 'ID_FT_ADSL', 'ID_FTTH_MN_ZAPM_PARTIELLE', 'ID_ZAPM_PARTIELLE', 'ID_ZAPM'],
  619. position: ['DATE_DEB_TRAV_PREV']
  620. };
  621. parseData('ftth', data, style, properties);
  622. //console.timeEnd('FTTH data');
  623. //console.debug('Data for FTTH are ready', data);
  624. if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
  625. $scope.loaded = true;
  626. }
  627. $scope.$evalAsync();
  628. });
  629. //console.time('ADSL data');
  630. $http({method: 'POST', url: 'data/TEL_FT_ADSL.json'}).success(function(data) {
  631. var style = {
  632. color : $scope.colors.adsl,
  633. fillColor: $scope.colors.adsl,
  634. weight : 2
  635. };
  636. var properties = {
  637. name : {key: 'LEGENDE'},
  638. hidden: ['NATURE', 'NRA_CETE', 'NRA_TMP', 'NRA_DPT', 'ID_FT_ADSL']
  639. };
  640. parseData('adsl', data, style, properties);
  641. //console.timeEnd('ADSL data');
  642. //console.debug('Data for ADSL are ready', data);
  643. if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
  644. $scope.loaded = true;
  645. }
  646. $scope.$evalAsync();
  647. });
  648. //console.time('MiMo data');
  649. $http({method: 'POST', url: 'data/Couverture_mimo.json'}).success(function(data) {
  650. var style = {
  651. color : $scope.colors.mimo,
  652. fillColor: $scope.colors.mimo,
  653. weight : 2
  654. };
  655. var properties = {
  656. name : {string: 'Couverture MiMo'},
  657. hidden: ['ID_MIMO_COUVERTURE']
  658. };
  659. parseData('mimo', data, style, properties);
  660. //console.timeEnd('MiMo data');
  661. //console.debug('Data for MIMO are ready', data);
  662. if($scope.data.mimo && $scope.data.adsl && $scope.data.ftth) {
  663. $scope.loaded = true;
  664. }
  665. $scope.$evalAsync();
  666. });
  667. window.map = map;
  668. $scope.mapType = 'Satellite';
  669. $scope.view = {};
  670. $scope.isShown = {};
  671. };
  672. var isDate = function(value) {
  673. return (value.toString().length === 14 && value.toString().substring(0,2) === "20");
  674. };
  675. var isInside = function(polygon, point) {
  676. // ray-casting algorithm based on
  677. // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  678. var y = point.x ? point.x : point[0],
  679. x = point.y ? point.y : point[1];
  680. var inside = false;
  681. for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
  682. var xi = polygon[i][0], yi = polygon[i][1];
  683. var xj = polygon[j][0], yj = polygon[j][1];
  684. var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
  685. if (intersect) {
  686. inside = !inside;
  687. }
  688. }
  689. return inside;
  690. };
  691. var parseData = function(identifier, data, style, properties) {
  692. var getPolygonsCoord = function(type, coord) {
  693. var result = [];
  694. if(type === 'Polygon') {
  695. result.push(_.map(coord[0], function(r) {return [r[1], r[0]];}));
  696. }
  697. if(type === 'MultiPolygon') {
  698. var p = [];
  699. _.each(coord, function(c) {
  700. result.push(_.map(c[0], function(r) {return [r[1], r[0]];}));
  701. });
  702. }
  703. return result;
  704. };
  705. var records = [];
  706. _.each(data.features, function(r) {
  707. var record = r.properties;
  708. var polygons = getPolygonsCoord(r.geometry.type, r.geometry.coordinates);
  709. record._coordinates = r.geometry.coordinates;
  710. record._type = r.geometry.type;
  711. record._polygons = polygons;
  712. record._style = style;
  713. record._properties = properties;
  714. records.push(record);
  715. });
  716. $scope.data[identifier] = records;
  717. };
  718. var parseResults = function(records) {
  719. if(!records || !records.length) {
  720. return null;
  721. }
  722. if(records.length === 1) {
  723. return records[0];
  724. }
  725. var result = records[0];
  726. return result;
  727. };
  728. var reverseLocation = function(geoCode, address, callback) {
  729. var reverseGeo = 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?f=pjson&distance=300';
  730. var url = reverseGeo + '&location=' + (geoCode ? $scope.geoCode.x + ',' + $scope.geoCode.y : address) ;
  731. $.get(
  732. url,
  733. function(data, status) {
  734. data = JSON.parse(data);
  735. var adresse = data && data.address && data.address.Match_addr;
  736. if(data && data.address && data.address.Address) {
  737. var i = 0;
  738. var num = '';
  739. while(!isNaN(parseInt(data.address.Address[i], 10))) {
  740. num += data.address.Address[i];
  741. i++;
  742. }
  743. data.address.StreetNumber = num;
  744. data.address.Address = data.address.Address.substr(num.length).trim();
  745. var typeVoie = data.address.Address.substring(0, data.address.Address.indexOf(' ')).toLowerCase();
  746. type = _.find(catTypeVoie, function(c){
  747. if(c.id === typeVoie || c.name.toLowerCase() === typeVoie) {
  748. return true;
  749. }
  750. });
  751. if(type) {
  752. data.address.StreetType = type.id;
  753. data.address.Address = data.address.Address.substr(typeVoie.length).trim();
  754. }
  755. }
  756. //console.debug('Reverse', geoCode, address, '=>', adresse, data.address);
  757. callback(adresse, data.address);
  758. $scope.$evalAsync();
  759. });
  760. };
  761. $scope.changeMap = function(value) {
  762. //console.log('Goto', value);
  763. map.removeLayer(cLayer);
  764. cLayer = L.tileLayer(maps[value], {
  765. attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  766. maxZoom: 18
  767. }).addTo(map);
  768. };
  769. $scope.closeRight = function() {
  770. $mdSidenav('right').close().then(function(){});
  771. };
  772. $scope.computeLayer = function(identifier) {
  773. var Lpolygons = [];
  774. _.each($scope.data[identifier], function(record) {
  775. _.each(record._polygons, function(polygon) {
  776. Lpolygons.push(L.polygon(polygon, record._style).bindPopup($scope.getHtmlContent(identifier, record)));
  777. });
  778. });
  779. layer[identifier] = L.layerGroup(Lpolygons);
  780. };
  781. $scope.formatDateFTTH = function(date) {
  782. if(!date) {return;}
  783. var momentDate = moment(date, 'DD/MM/YYYY');
  784. var result = '<div class="popup-line"><div class="box-eligibilite-title">Date prévisionnelle abonnement FTTH</div><div style="font-weight: bold;" class="popup-value">' + momentDate.locale("fr").format('ddd, LL') + '</div><div class="popup-small-date">' + momentDate.locale("fr").fromNow() + '</div></div>';
  785. return $sce.trustAsHtml(result);
  786. };
  787. $scope.formatResults = function(identifier, results) {
  788. return $sce.trustAsHtml($scope.getHtmlContent(identifier, results));
  789. };
  790. $scope.getGeoCode = function(address, magicKey, callback) {
  791. var findURL = 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find?f=pjson&searchExtent=' + JSON.stringify(searchExtent);
  792. getGeoCodeInProgress = true;
  793. var url = findURL + "&text=" + address + ((magicKey) ? ("&magicKey=" + magicKey) : ', Basse-Normandie, France');
  794. //console.log('url', url);
  795. $.get(
  796. url,
  797. function(data, status) {
  798. data = JSON.parse(data);
  799. console.debug('address, magicKey', address, magicKey, data);
  800. if (status === 'success' && data.locations[0]) {
  801. if(data.locations[0].extent.xmax < searchExtent.xmin &&
  802. data.locations[0].extent.xmax > searchExtent.xmax &&
  803. data.locations[0].extent.xmin > searchExtent.xmax &&
  804. data.locations[0].extent.xmin > searchExtent.xmax) {
  805. getGeoCodeInProgress = false;
  806. console.debug('getGeoCode', address, magicKey, '=>', data);
  807. return callback(null, data);
  808. }
  809. getGeoCodeInProgress = false;
  810. console.debug('getGeoCode', address, magicKey, '=>', 'No result');
  811. callback('No result for ' + address);
  812. } else {
  813. getGeoCodeInProgress = false;
  814. console.debug('getGeoCode', address, magicKey, '=>', 'No result');
  815. callback(status !== 'success' ? status : 'No result for ' + address);
  816. }
  817. });
  818. };
  819. $scope.getHtmlContent = function(identifier, record) {
  820. var title = record._properties.name.string ? record._properties.name.string : record[record._properties.name.key];
  821. // Tooltip content
  822. var tooltip = '<div class="popup-line"><span class="popup-title">' + title +'</span></div>' +
  823. '<hr>';
  824. _.each(record, function(value, property) {
  825. if(property.charAt(0) === '_' ||
  826. (record._properties.hidden && record._properties.hidden.indexOf(property) !== -1) ||
  827. record._properties.name.key === property ||
  828. value === null |
  829. typeof value === 'undefined') {
  830. return;
  831. }
  832. var label = $scope.dictionary[property] || property;
  833. value = $scope.dictionary[value] || value;
  834. var date;
  835. if(property.substring(0, 5) === 'DATE_' && !$scope.dictionary[value] && isDate(value)) {
  836. date = formatDate(value);
  837. }
  838. tooltip += '<div class="popup-line"><div class="popup-label">' + label + '</div><div class="popup-value">' + (date ? date.locale("fr").format('ddd, LL') : value) + '</div><div class="popup-small-date">' + (date ? date.locale("fr").fromNow() : '') + '</div></div>';
  839. });
  840. return tooltip;
  841. };
  842. $scope.hideLayer = function(identifier) {
  843. map.removeLayer(layer[identifier]);
  844. };
  845. $scope.hideResultPane = function() {
  846. if(!$('#result').height()) {return;}
  847. $('#result').animate({height: 0}, 1000);
  848. $('#map').animate({
  849. height: $('body').height(),
  850. }, 1000, function() {
  851. // Animation complete.
  852. map.invalidateSize();
  853. var centerPoint = $scope.geoCode ? new L.LatLng($scope.geoCode.y, $scope.geoCode.x) : stlo;
  854. map.setView(centerPoint, 14);
  855. });
  856. };
  857. $scope.initPopup = function() {
  858. //console.log('initPopup', $scope.geoCode);
  859. $scope.postForm = null;
  860. reverseLocation($scope.geoCode, null, function(string, address) {
  861. //console.log('add', address);
  862. $scope.result = {eligibilite: {}, autres: {}};
  863. // Debug
  864. $scope.result.eligibilite.prenom = 'Francois';
  865. $scope.result.eligibilite.nom = 'Beaufils';
  866. $scope.result.eligibilite.email = 'francoisbeaufils@zeno-labs.com';
  867. $scope.result.eligibilite.vous_etes = 'locataire';
  868. $scope.result.eligibilite.ce_logement_est = 'residence_principale';
  869. $scope.result.eligibilite.info_et_libertes = true;
  870. $scope.result.eligibilite.accord = true;
  871. $scope.result.eligibilite.souscription_engagement = true;
  872. $scope.result.eligibilite.geo_code = JSON.stringify($scope.geoCode);
  873. $scope.result.eligibilite.code_postal = address.Postal;
  874. $scope.result.eligibilite.complement_addresse = address.Match_addr;
  875. $scope.result.eligibilite.nom_voie = address.Address;
  876. $scope.result.eligibilite.numero_voie = address.StreetNumber;
  877. $scope.result.eligibilite.type_voie = address.StreetType;
  878. $scope.result.eligibilite.ville = address.City;
  879. });
  880. };
  881. $scope.isFormValid = function() {
  882. if(!$scope.result || !$scope.result.eligibilite) {return;}
  883. var isValid = true;
  884. _.each($scope.formulaires.eligibilite.sections, function(section) {
  885. _.each(section.lines, function(line) {
  886. _.each(line.ctrls, function(ctrl) {
  887. ctrl.invalid = false;
  888. if(ctrl.require && !ctrl.isValid($scope.result.eligibilite[ctrl.id], $scope.result.autres[ctrl.id])) {
  889. isValid = false;
  890. ctrl.invalid = true;
  891. }
  892. });
  893. });
  894. });
  895. return isValid;
  896. };
  897. $scope.onSubmitAddress = function($item, $model, $label) {
  898. // console.log('onSubmitAddress address', $scope.address);
  899. // console.log('onSubmitAddress $item', $item);
  900. // console.log('onSubmitAddress $model', $model);
  901. // console.log('onSubmitAddress $label', $label);
  902. // Get magic key
  903. var item = _.find($scope.suggestions, {text: $item});
  904. if(!item) {
  905. item = $scope.suggestions[0];
  906. $scope.address = item.text;
  907. }
  908. $scope.magicKey = item.magicKey;
  909. //console.log('onSubmitAddress -_-item', item, '=>', $scope.magicKey);
  910. $scope.getGeoCode($scope.address, $scope.magicKey, function(err, data) {
  911. $scope.geoCode = data && data.locations && data.locations[0] && data.locations[0].feature.geometry;
  912. if(err) {console.error('Geocode error', err);}
  913. var toast = toast || {
  914. template: '<md-toast><i class = " md-error"></i> Oups! Aucun résultat trouvé dans la Manche pour: ' + $scope.address + '</md-toast>',
  915. hideDelay: 3000,
  916. position: 'bottom right'
  917. };
  918. // $mdToast.simple()
  919. // .template(')
  920. // .position('bottom right')
  921. // .hideDelay(3000);
  922. if(err || !$scope.geoCode) {
  923. $scope.hideResultPane();
  924. $mdToast.show(toast);
  925. }
  926. //console.log('Addresses found for', $scope.address, '=>', data, '=> Geocode:', $scope.geoCode);
  927. if($scope.geoCode) {
  928. addCurrentMarker();
  929. $scope.showResultPane();
  930. getResults();
  931. }
  932. });
  933. };
  934. $scope.postFormEl = function() {
  935. $scope.postForm = {inProgress: true};
  936. _.each($scope.result.autres, function(value, key) {
  937. $scope.result.eligibilite[key] = value;
  938. });
  939. console.log('postForm', $scope.result.eligibilite);
  940. $scope.$evalAsync();
  941. function mysql_real_escape_string (str) {
  942. if(typeof str !== 'string') {return str;}
  943. return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
  944. switch (char) {
  945. case "\0":
  946. return "\\0";
  947. case "\x08":
  948. return "\\b";
  949. case "\x09":
  950. return "\\t";
  951. case "\x1a":
  952. return "\\z";
  953. case "\n":
  954. return "\\n";
  955. case "\r":
  956. return "\\r";
  957. case "\"":
  958. case "'":
  959. case "\\":
  960. case "%":
  961. return "\\"+char; // prepends a backslash to backslash, percent,
  962. // and double/single quotes
  963. }
  964. });
  965. }
  966. var keys = '';
  967. var values = '';
  968. _.each($scope.result.eligibilite, function(value, key) {
  969. keys += '`' + key + '`, ';
  970. values += "'" + mysql_real_escape_string(value) + "', ";
  971. });
  972. var query = "INSERT INTO `eligibilite`.`demandes` (" + keys.substring(0, keys.length -2) + ") VALUES (" + values.substring(0, values.length -2) + ");";
  973. console.log('query', query);
  974. $.ajax({
  975. method : "POST",
  976. url : "ajax/datastores.php",
  977. data : {query: query}
  978. })
  979. .done(function( msg ) {
  980. if(!isNaN(msg)) {
  981. $scope.postForm = {ok: true};
  982. var numDemande = moment().format('YYYYMMDD') + msg;
  983. var body = 'Bonjour ' + $scope.result.eligibilite.prenom + ' ' + $scope.result.eligibilite.nom + ', <br>' +
  984. 'Nous vous confirmons votre demande de pré-raccordement FTTH. <br><br>' +
  985. 'Cette demande porte le numéro: ' +
  986. '<span style="color: #31708f;font-size:17px; font-weight:bold;">' + numDemande + '</span><br><br>' +
  987. 'Voici le détail de votre demande:' +
  988. '<div style="color: #31708f;background-color: #d9edf7;border-color: #bce8f1;padding: 10px;margin: 1em;font-size:14px;">' +
  989. '<table style="line-height: 40px;">';
  990. // _.each($scope.result.eligibilite, function(value, key) {
  991. // body += '<tr>';
  992. // body += '<th style="text-align:left;">' + key + '</th>';
  993. // body += '<td>' + value + '</td>';
  994. // body += '</tr>';
  995. // });
  996. // Numero demande
  997. body += '<tr>';
  998. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Numéro demande</th>';
  999. body += '<td>' + numDemande + '</td>';
  1000. body += '</tr>';
  1001. // Date demande
  1002. body += '<tr>';
  1003. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Date</th>';
  1004. body += '<td>' + moment().lang('fr').format('LLLL') + '</td>';
  1005. body += '</tr>';
  1006. // Demandeur
  1007. body += '<tr>';
  1008. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Demandeur</th>';
  1009. body += '<td>' + $scope.result.eligibilite.prenom + ' ' + $scope.result.eligibilite.nom + '</td>';
  1010. body += '</tr>';
  1011. // Email
  1012. body += '<tr>';
  1013. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Email</th>';
  1014. body += '<td>' + $scope.result.eligibilite.email + '</td>';
  1015. body += '</tr>';
  1016. // Adresse
  1017. body += '<tr>';
  1018. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Adresse</th>';
  1019. body += '<td>' + computeFullAdress() + '</td>';
  1020. body += '</tr>';
  1021. // Vous etes
  1022. var cat = _.find(catVousEtes, {id: $scope.result.eligibilite.vous_etes});
  1023. var res = cat && cat.name ? cat.name : $scope.result.eligibilite.vous_etes;
  1024. body += '<tr>';
  1025. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Vous êtes</th>';
  1026. body += '<td>' + res + '</td>';
  1027. body += '</tr>';
  1028. // Ce logement est
  1029. var cat2 = _.find(catCeLogementEst, {id: $scope.result.eligibilite.ce_logement_est});
  1030. var res2 = cat2 && cat2.name ? cat2.name : $scope.result.eligibilite.ce_logement_est;
  1031. body += '<tr>';
  1032. body += '<th style="text-align: left;white-space: nowrap;height: 40px;color: #666;">Ce logement est</th>';
  1033. body += '<td>' + res2 + '</td>';
  1034. body += '</tr>';
  1035. //console.log('$scope.result', $scope.result);
  1036. body += '</table></div><br>';
  1037. body += 'Conformément à la loi "informatique et libertés" du 6 janvier 1978 modifiée, vous bénéficiez d’un droit d’accès, de rectification aux informations qui vous concernent, d’opposition au traitement de vos données personnelles. Si vous souhaitez exercer ce droit et obtenir communication des informations vous concernant, merci de nous contacter :' + '<br>' +
  1038. '<div style="">' +
  1039. ' Email: ' + siteEmail + '<br>' +
  1040. ' Adresse: ' + siteAddresse + '<br>' +
  1041. '</div><br><br>';
  1042. body += 'A bientôt sur: <a href="' + siteUrl + '">' + siteName + '</a>';
  1043. var mail = {
  1044. to : $scope.result.eligibilite.email,
  1045. sujet : 'Votre demande de pré-raccordement FTTH n° ' + numDemande,
  1046. message: body
  1047. };
  1048. $.ajax({
  1049. method : "POST",
  1050. url : "ajax/datastores.php",
  1051. data : {mail: mail}
  1052. })
  1053. .done(function( msg ) {
  1054. console.log('Mail result', msg);
  1055. });
  1056. $scope.result.eligibilite = {};
  1057. }
  1058. else {
  1059. $scope.postForm = {error: msg};
  1060. }
  1061. $scope.autres = {};
  1062. $scope.$apply();
  1063. });
  1064. };
  1065. $scope.showLayer = function(identifier) {
  1066. map.addLayer(layer[identifier]);
  1067. };
  1068. $scope.showResultPane = function() {
  1069. var bodyHeight = $('body').height();
  1070. var height = Math.max(300, bodyHeight / 3);
  1071. var heightMap = bodyHeight - height;
  1072. $('#result').animate({height: height + 'px'}, 1000);
  1073. $('#map').animate({
  1074. height: heightMap + 'px',
  1075. }, 1000, function() {
  1076. // Animation complete.
  1077. map.invalidateSize();
  1078. map.setView(new L.LatLng($scope.geoCode.y, $scope.geoCode.x), 14);
  1079. });
  1080. };
  1081. $scope.toggleResultPane = function() {
  1082. if($('#result').height()) {
  1083. return $scope.hideResultPane();
  1084. }
  1085. if($scope.results && $scope.results.ftth) {
  1086. return $scope.showResultPane();
  1087. }
  1088. };
  1089. $scope.toggleRight = function() {
  1090. $mdSidenav('right').toggle()
  1091. .then(function(){});
  1092. };
  1093. $scope.$watch('view', function(view) {
  1094. if(_.isEmpty(view)) {return;}
  1095. $('#layer-loading').removeClass('force-hidden').find('.md-inner').show();
  1096. setTimeout(function() {
  1097. _.each(view, function(value, key) {
  1098. if($scope.isShown[key] !== value) {
  1099. if(value) {
  1100. if(typeof $scope.isShown[key] !== 'undefined') {
  1101. $scope.showLayer(key);
  1102. $('#layer-loading').find('.md-inner').hide();
  1103. }
  1104. else {
  1105. $timeout(function() {
  1106. $scope.computeLayer(key);
  1107. $scope.showLayer(key);
  1108. $('#layer-loading').find('.md-inner').hide();
  1109. }, 500);
  1110. }
  1111. }
  1112. else {
  1113. $scope.hideLayer(key);
  1114. setTimeout(function() {
  1115. $('#layer-loading').find('.md-inner').hide();
  1116. }, 1000);
  1117. }
  1118. $scope.isShown[key] = value;
  1119. }
  1120. });
  1121. });
  1122. }, true);
  1123. $(window).resize(function() {
  1124. if(!$('#result').height()) {return;}
  1125. $scope.showResultPane();
  1126. });
  1127. init();
  1128. });