app.js 41 KB

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