app.js 42 KB

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