PageSourceSearch

https://coag.org/site/60880/js/ch_formcontroller.js

js coag.org collected 2026-10-01 13:06:26 UTC 13,800 bytes, 488 lines download raw bytes

1console.log("formcontroller.js loaded");
2
3angular.module('chilApp')
4.config(function ($interpolateProvider) {
5  $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
6})
7.constant('siteId', $site_id)
8.factory('postdetailApi', function($http, $q){
9  
10  return {
11    browse: function(postId) { 
12      return $http.get('/api/post/' + postId )
13      .then(function(r){
14        return r.data;
15      });
16      
17    }
18  }
19})
20.directive('checklist', function() {
21  return {
22    restrict: "A",
23    require: "?^ngController",
24    terminal: false,
25    scope: {
26      list: '@checklist',
27      value: '@'
28    },
29    link: function(scope, elem, attrs, controller) {
30
31      
32      var handler = function(setup) {
33        var checked = elem.prop('checked');
34        var target = null;
35        
36        if (controller.model != undefined) {
37          if (controller.model[scope.list] === undefined ||
38            	controller.model[scope.list] === null ||
39            	controller.model[scope.list] === ''
40           )
41          {
42            controller.model[scope.list] = [];
43          }
44        	target =  controller.model[scope.list]; 
45      	} else {
46          if (controller[scope.list] === undefined || 
47              controller[scope.list] === null)
48          {
49            controller[scope.list] = [];
50          }
51        	target = controller[scope.list];
52      }
53       
54      var index = target.indexOf(scope.value);
55
56        
57        if (checked && index == -1) {
58          if (setup) { 
59            elem.prop('checked', false);
60          } else {
61            target.push(scope.value);
62          }
63        } else if (!checked && index != -1) {
64          if (setup) {
65            elem.prop('checked', true);
66          }
67          else {
68            target.splice(index, 1);
69          }
70        }
71        
72      };
73
74      var setupHandler = handler.bind(null, true);
75      var changeHandler = handler.bind(null, false);
76
77      elem.bind('change', function() {
78        scope.$apply(changeHandler);
79      });
80      
81      scope.$watch('list', setupHandler, true);
82    }
83  };
84})
85.controller("FormController", function($scope, $window, $sce, $timeout, siteId, postdetailApi){
86  var scope = this; 
87  var postId = '';
88  // var commentCreatorId = _userId;
89
90  var commentCreatorId = '[email protected]';
91
92  scope.post = '';
93  scope.body = '';
94  scope.comments = [];
95  scope.runningTime = '00:00';
96  scope.totalresult = 0;
97  scope.result = 0;
98  
99  scope.first = true;
100  scope.showform = false;
101  scope.after = false;
102  
103  //scope.zoneid = _zoneId;
104  scope.zoneid = 0;
105
106  
107  if (typeof _postId !== 'undefined') {postId = _postId;}
108  
109  scope.init = function () {
110      scope.load(postId);
111  };
112  
113  scope.load = function(postId){ 
114    console.log("LOADING FORM " + postId);
115    return postdetailApi.browse(postId)
116    .then(function(data){
117      console.log(data);
118      loadForm(data)
119      console.log("CUESTIONARIO CARGADO!!!");
120      return data;
121    });
122  }
123  
124  loadForm = function(data) {
125    if (data.post != null && 
126        data.post.body !== undefined && data.post.body !== null ){ 
127      scope.post = data.post; 
128      scope.body = data.post.body.replace(/<[^>]+>/gm, '');
129      scope.body = angular.fromJson(scope.body);
130      console.log(scope.body);
131      angular.forEach(data.post.comments, function(d){
132        if(d.creator.id == commentCreatorId){
133          scope.comments.push(d);
134        }
135      });
136      
137      scope.comments = scope.comments.reverse();
138    }
139    scope.createModel(scope.body);
140  }
141  
142  scope.addOption = function(variable,option) {
143  	console.log(variable);
144  	console.log(option);
145  }
146  
147     	// Datos falsos para las ocasiones en que no se usane en los cuestionarios
148  scope.fakeName = 'Anonimous';
149  scope.fakeTfn = '---------';
150  scope.fakeEmail = '[email protected]';
151  
152  scope.send = function() {
153    
154    console.log(scope);
155    
156    var lang = scope.post.lang;
157    
158    if (!scope.updateModel(scope.body)) {
159      console.log(scope.model);
160      if (lang === 'CA') {
161      	$window.alert("Ha d'omplir els camps obligatoris marcats amb * vermell.");
162      } else {
163	      $window.alert("Debe rellenar los campos obligatorios marcados con * rojo.");
164      }    
165      return;
166    }
167    
168    if (scope.model['tfn'] !== undefined && !scope.checkTfn(scope.model['tfn']) ) {
169      if (lang === 'CA') {
170      	$window.alert("Vostè ha d'introduir un telèfon vàlid.");
171      } else {
172	      $window.alert("Debe introducir un teléfono válido.");
173      }    
174      return;
175    }
176    if (scope.model['email'] !== undefined && !scope.checkEmail(scope.model['email']) ) {
177      if (lang === 'CA') {
178        $window.alert("Vostè ha d'introduir un correu electrònic vàlid.");
179      } else {
180        $window.alert("Debe introducir un email válido.");
181      }     
182      return;
183    }
184    if (scope.model['nombre'] !== undefined &&
185        !scope.checkName(scope.model['nombre'], scope.model['apellidos']) ) {
186      if (lang === 'CA') {
187        $window.alert("Vostè ha d'introduir nom i cognoms vàlids.");
188      } else {
189        $window.alert("Debe introducir nombre y apellidos válidos.");
190      }      
191      return;
192    }
193
194    var tfn = scope.model['tfn'] !== undefined ? 
195        					scope.cleanTfn(scope.model['tfn']) : 
196    							scope.fakeTfn;
197
198    var email = scope.model['email'] !== undefined ?
199        					scope.cleanEmail(scope.model['email']) : 
200    							scope.fakeEmail;
201
202    var nombre = scope.model['nombre'] !== undefined ?
203        					scope.cleanName(scope.model['nombre'], scope.model['apellidos']) : 
204    							scope.fakeName;
205
206    
207   
208    var content = JSON.stringify(scope.model, function(key, value) {
209      if (typeof value === 'string' || value instanceof String) {
210        return value.replace(/"/g, '\\"');
211      } else {
212       	return value;
213      }
214    });
215    //console.log(scope.model);
216    //console.log(scope.model.consulta.replace(/"/g, '\\"'));
217  	//var content = JSON.stringify(scope.model);
218    
219    console.log("NOMBRE: " + nombre)
220
221    scope.checkDBTfn(tfn)
222    	.then(
223        (count) => {
224          console.log("TFN EN LA BD: " + count.toString())
225          if (count >0) {
226            if (lang === 'CA') {
227              $window.alert("Aquest telèfon ha estat utilitzat per a participar.");
228            } else {
229              $window.alert("Este teléfono ha sido utilizado para participar.");
230            } 
231          	return new Promise(	(resolve, reject) => reject('Telefono ya utilizado') );
232	        }
233          else
234          	return scope.checkDBEmail(email)
235       }) 
236    	.then(
237        (count) => {
238          console.log("EMAIL EN LA BD: " + count.toString())
239          if (count >0) {
240            if (lang === 'CA') {
241              $window.alert("Aquest email ha estat utilitzat per a participar.");
242            } else {
243              $window.alert("Este email ha sido utilizado para participar.");
244            } 
245          	return new Promise(	(resolve, reject) => reject('Email ya utilizado'));
246	        }
247          else {
248          	console.log(content);
249          	return scope.saveForm(email, nombre, tfn, content);
250        	}
251       }) 
252			.then (
253          (success) => {  
254          	if (success) {
255          		$window.alert(scope.body.AcceptMessage);
256        		  location.href="/";
257        		} else
258             if (lang === 'CA') {
259                $window.alert("Hi ha hagut un error, provi més tard.");
260              } else {
261                $window.alert("Ha habido un error, pruebe mas tarde.");
262              }           
263      });
264
265  };
266  
267  scope.checkDBTfn = function(tfn) {
268    return new Promise (
269    		function (resolve, reject) {
270          if (tfn === scope.fakeTfn) {
271        		resolve(0);
272        	}
273          else {
274            $.ajax({
275              /* url: "https://api.chil.me/api/comment/check", */
276
277              url: "/api/comment/check",
278 
279              type: "POST",
280              data: {
281                "ObjectId": scope.post.id,
282                "Type" : 4,
283                "SubType" : 1,
284                "Tfn": tfn
285              },
286              dataType:'json',
287              success: function (response) {
288                //console.log(response)
289                resolve(response.count);
290              },
291              error: function(error){
292                console.log("Something went wrong", error);
293                reject("checkDBTfn. Petición rechazada");
294              }
295            });
296        	}
297        });    
298    
299    
300   	//console.log("CUESTIONARIO POSTEADO!!!");
301    //$window.alert("Please enter your name!");
302    
303  };
304  
305  scope.checkDBEmail = function(email) {
306    return new Promise (
307    		function (resolve, reject) {
308          if (email === scope.fakeEmail) {
309            resolve(0);
310          } else {
311             $.ajax({
312                /* url: "https://api.chil.me/api/comment/check", */
313
314                url: "/api/comment/check", 
315                type: "POST",
316                data: {
317                  "ObjectId": scope.post.id,
318                  "Type" : 4,
319                  "SubType" : 1,
320                  "Email": email
321                },
322                dataType:'json',
323                success: function (response) {
324                  //console.log(response)
325                  resolve(response.count);
326                },
327                error: function(error){
328                  console.log("Something went wrong", error);
329                  reject("checkDBEmail. Petición rechazada");
330                }
331              });
332          }
333         });    
334    
335    
336   	//console.log("CUESTIONARIO POSTEADO!!!");
337    //$window.alert("Please enter your name!");
338    
339  };
340   
341  scope.saveForm = function(email, nombre, tfn, content) {
342    return new Promise (
343    		function (resolve, reject) {
344            $.ajax({
345              url: "/api/comment/add", 
346
347              /* url: "https://api.chil.me/api/comment/add", */
348
349
350              /* url: "http://localhost:59520/api/comment/add", */
351              
352              type: "POST",
353              data: {
354                "ObjectId": scope.post.id,
355                "Type" : 4,
356                "SubType" : 1,
357                "Email": email,
358                "UserName": nombre,
359                "Tfn": tfn,
360                "Message": content
361              },
362              dataType:'json',
363              success: function (response) {
364                console.log('CUESTIONARIO POSTEADO!!!')
365                resolve(true);
366              },
367              error: function(error){
368                console.log("Something went wrong", error);
369                resolve(false);
370              }
371            });
372        });
373  };
374  
375  scope.createModel = function(origin) {
376   	scope.model = new Object();  
377    if(origin.Groups !== undefined && origin.Groups !== null ) {
378    	origin.Groups.forEach(function(group) {      
379      group.Fields.forEach(function(field) {
380        if (field.Tag !== undefined && 
381            field.Tag !== null && 
382            field.Tag.trim() !== '' ) {
383          
384          switch (field.Select) {
385            case 'slider':
386              field.value = "0";
387              break;
388            case 'multiple':
389              field.value = [];
390              break;
391
392            default:
393              field.value = '';
394          }
395      				 //field.Tag.trim().toLowerCase();
396		      scope.model[field.Tag.trim().toLowerCase()] = null;
397        }
398      });                     
399    });
400    }
401  };
402  
403  scope.updateModel = function(origin) {
404    
405    console.log('Actualizar datos');
406    console.log('----------------');
407
408     console.log(scope);
409
410    var mandatoryNotFilled = false;
411    
412    origin.Groups.forEach(function(group) {      
413      group.Fields.forEach(function(field) {
414        //console.log(field.Tag.trim().toLowerCase());
415        //console.log(scope.model[field.Tag.trim().toLowerCase()]);
416
417        if (field.Tag !== undefined && 
418            field.Tag !== null && 
419            field.Tag.trim() !== '' &&
420            !Array.isArray(scope.model[field.Tag.trim().toLowerCase()])
421            ) {
422          
423		      	  scope.model[field.Tag.trim().toLowerCase()] = field.value;
424        } 
425        
426        // Verificar que si es un campo obligatorio, esta relleno
427        if (field.Mandatory) {
428          if (
429              ( Array.isArray(scope.model[field.Tag.trim().toLowerCase()]) &&
430                scope.model[field.Tag.trim().toLowerCase()].length === 0) 
431              ||
432              ( scope.model[field.Tag.trim().toLowerCase()] === '')
433             )
434            mandatoryNotFilled = true;
435        }
436      });                     
437    });
438
439    return !mandatoryNotFilled;
440  };
441 
442  scope.checkTfn = function(tfn) {
443    
444    var re = /^(\+34|0034|34)?[\s|\-|\.]?[6|7|9][\s|\-|\.]?([0-9][\s|\-|\.]?){8}$/;
445    if (tfn === null || tfn.trim() === '' 
446       || !re.test(tfn.toLowerCase()) )
447      return false;
448    else 
449  		return true;  
450  };
451   
452  scope.checkEmail = function(email) {
453    var re = /\S+@\S+\.\S+/;
454
455    if (email === null || email.trim() === ''
456       || !re.test(email.toLowerCase())
457        )
458      return false;
459    else   	
460      return true;  
461  };
462  
463  scope.checkName = function(nombre, apellidos) {
464      if (nombre === undefined || nombre === null || nombre.trim() === ''
465         /*|| apellidos === null || apellidos.trim() === '' */
466          )
467        return false;
468      else   	
469        return true;  
470    };
471
472  scope.cleanTfn = function(tfn) {
473      return tfn.replace(/[ .*+?^${}()|[\]\\]/g, ""); 
474    };
475
476  scope.cleanEmail = function(email) {
477      return email.trim().toLowerCase();
478    };
479
480 	scope.cleanName = function(nombre, apellidos) {
481
482    if (apellidos == undefined || apellidos == null || apellidos.trim() == "")
483    		return nombre.trim();
484    else 
485      	return nombre.trim() + " " + apellidos.trim();
486    };
487
488})

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.