midisponibilidad.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. * Para crear horario de administrativos
  3. */
  4. $(document).ready(function(){
  5. loadHorarioEdicion();
  6. $('#modal_confirm').on('show.bs.modal', function (event) {
  7. var button = $(event.relatedTarget); // Button that triggered the modal
  8. var id = button.parents(".bloque-clase").data("id_obj");
  9. $("#id_borrar").val(id);
  10. });
  11. $('.editable').click(function(){//abre modal para crear
  12. $("#errorBox").collapse('hide');
  13. $("#errorBox_text").html("");
  14. var dia = getDiaNombre($(this).data("dia"));
  15. var hora = $(this).data("hora");
  16. if(hora < 10) hora = "0"+hora;
  17. var min = $(this).data("fraccion");
  18. if(min < 10) min = "0"+min;
  19. $('#dia').val($(this).data("dia"));
  20. $('#hora').val(hora+":"+min);
  21. $('#fecha_horario').html(dia+" - "+hora+":"+min+" hrs.");
  22. $("#submitBtn").data('tipo', 1);
  23. $("#modalLabel").html("Crear Horario");
  24. $('#duracion').removeClass('is-invalid');
  25. $('#modal').modal('show');
  26. });
  27. $('#submitBtn').click(function(){
  28. //Crea Obj JSON y elemento HTML
  29. if(validaDuracion(-1, $('#dia').val(), $('#hora').val(), parseFloat($('#duracion').val())*60)){
  30. var horario = {
  31. id_obj: id_obj,
  32. id_db:0,
  33. dia: parseInt($('#dia').val()),
  34. dia_orig: parseInt($('#dia').val()),
  35. hora: $('#hora').val(),
  36. duracion: parseFloat($('#duracion').val())*60,
  37. editable: true,
  38. color: "#f0b6c0"
  39. };
  40. if(guardaHorario(1, horario)){
  41. horariosObj.push(horario);
  42. //Crea horario HMTL
  43. creaHorarioHTML(id_obj, getX(horario.dia), getY(horario.hora), getAlto(horario.duracion) ,horario.color, "#bloque-horarios");
  44. id_obj++;
  45. }
  46. $('#modal').modal('hide');
  47. }//fin duración valida
  48. else{
  49. $("#avanzadoBox").collapse('show');
  50. $('#duracion').addClass('is-invalid');
  51. }
  52. });
  53. });
  54. function validaDuracion(pos, dia, hora_ini, duracion){//valida que la materia no tenga conflictos con la siguiente y que esté dentro del límite del horario
  55. var horaObjIni = new Date();
  56. var horaObjFin;
  57. var horaArr = hora_ini.split(":");
  58. horaObjIni.setHours(horaArr[0]);
  59. horaObjIni.setMinutes(horaArr[1]);
  60. horaObjIni.setSeconds(0);
  61. horaObjFin = new Date(horaObjIni.getTime());
  62. horaObjFin.setMinutes(horaObjFin.getMinutes() + parseInt(duracion));
  63. //Obtiene última hora de clase
  64. var fechaLimite = new Date();
  65. fechaLimite.setHours(parseInt($('.hora').last().data('hora')) + 1);
  66. fechaLimite.setMinutes(0);
  67. fechaLimite.setSeconds(0);
  68. if( Date.parse(horaObjFin) > Date.parse(fechaLimite)){
  69. return false;
  70. }
  71. return validaHorasBloque(pos, dia, horaObjIni, horaObjFin);//valida si choca con el siguiente
  72. }
  73. function validaHorasBloque(pos, dia, horaObjIni, horaObjFin){
  74. for(var i=0; i < horariosObj.length; i++){
  75. var horaArr = horariosObj[i].hora.split(":");
  76. var horaClaseInicio = new Date();
  77. horaClaseInicio.setHours(horaArr[0]);
  78. horaClaseInicio.setMinutes(horaArr[1]);
  79. horaClaseInicio.setSeconds(0);
  80. //Objeto leído no es el objeto actual, mismo día, hora de fin del objeto actual choca con hora de inicio objeto anterior
  81. if(pos != i && parseInt(horariosObj[i].dia) == parseInt(dia) && Date.parse(horaClaseInicio) < Date.parse(horaObjFin) && Date.parse(horaClaseInicio) > Date.parse(horaObjIni)){
  82. return false;//Si existe, no es válido
  83. }
  84. }
  85. return true;//no existe, es válido
  86. }
  87. //funcion para guardar por ajax información
  88. function guardaHorario(nuevo, objClase){
  89. _editable = false;
  90. var url = './action/midisponibilidad_insert.php';
  91. if(nuevo != 1){
  92. url = './action/midisponibilidad_update.php';
  93. }
  94. var state = false;
  95. $.ajax({
  96. url: url,
  97. type: 'POST',
  98. dataType: 'json',
  99. async: false,
  100. data: { json: JSON.stringify(objClase)},
  101. beforeSend: function(x) {
  102. if (x && x.overrideMimeType) {
  103. x.overrideMimeType("application/j-son;charset=UTF-8");
  104. }
  105. },
  106. success: function(result) {
  107. if(result["error"]!= "" && result["error"] !== undefined){
  108. $("#errorBox").collapse('show');
  109. $("#errorBox_text").html("Error al guardar el horario.<br>"+result["error"]);
  110. $('#messageBox')[0].scrollIntoView({ block: "end" });
  111. state = false;
  112. }else{
  113. state = true;
  114. if(nuevo == 1){
  115. objClase.id_db = result["id"];
  116. }
  117. }
  118. },
  119. error: function(jqXHR, textStatus, errorThrown ){
  120. $("#errorBox").collapse('show');
  121. $("#errorBox_text").html(errorThrown);
  122. $('#messageBox')[0].scrollIntoView({ block: "end" });
  123. state = false;
  124. }
  125. });//ajax
  126. _editable = true;
  127. return state;
  128. }
  129. function loadHorarioEdicion(){
  130. $('.bloque-clase').remove();
  131. horariosObj = [];
  132. id_obj = 0;
  133. //carga horarios y crea bloques
  134. $.ajax({
  135. url: './action/midisponibilidad_select.php',
  136. type: 'POST',
  137. dataType: 'json',
  138. //data: { autorizacion: _horarioEstado},
  139. success: function(result) {
  140. if(result["error"]!= "" && result["error"] !== undefined){
  141. console.log("Ocurrió un error de load");
  142. $("#errorBox").collapse('show');
  143. $("#errorBox_text").html(result["error"]);
  144. $('#messageBox')[0].scrollIntoView({ block: "end" });
  145. }else{
  146. var i, j;
  147. for(i = 0; i< result["horario"].length; i++){
  148. var horario = {
  149. id_obj: id_obj,
  150. id_db: parseInt(result["horario"][i]["id"]),
  151. dia: parseInt(result["horario"][i]["dia"]),
  152. dia_orig: parseInt(result["horario"][i]["dia"]),
  153. hora: result["horario"][i]["hora"],
  154. duracion: parseInt(result["horario"][i]["duracion"]),
  155. color: result["horario"][i]["color"]
  156. };
  157. horariosObj.push(horario);
  158. creaHorarioHTML(id_obj, getX(horario.dia), getY(horario.hora), getAlto(horario.duracion) ,horario.color, "#bloque-horarios");
  159. id_obj++;
  160. }//fin for
  161. }
  162. _editable = true;
  163. },
  164. error: function(jqXHR, textStatus, errorThrown ){
  165. $("#errorBox").collapse('show');
  166. $("#errorBox_text").html("Error al cargar horario.<br>"+errorThrown);
  167. $('#messageBox')[0].scrollIntoView({ block: "end" });
  168. _editable = true;
  169. }
  170. });//ajax
  171. }
  172. function creaHorarioHTML(id, posX, posY, alto, color, parentBox){//crea bloque HTML
  173. var edit_class = "";
  174. edit_class = "bloque-draggable ui-draggable ui-draggable-handle bloque-resizable";
  175. var nuevoHorario = '<div class="bloque-clase no-overflow '+edit_class+'" id="bloque_'+id+'" data-id_obj="'+id+'"\
  176. style="top:'+posY+'px; left:'+posX+'px; background-color:'+color+'; height:'+alto+'px" >\
  177. <div class="menu-wrapper">\
  178. <div class="menu-flotante d-none">\
  179. <span class="float-right iconos" >\n\
  180. <span class="ing-basura ing-fw mx-1" aria-hidden="true" data-toggle="modal" data-target="#modal_confirm" title="Borrar bloque"></span>\
  181. </span>\
  182. </div>\
  183. </div>\
  184. </div>';
  185. $(nuevoHorario).appendTo(parentBox);
  186. makeDraggable();
  187. makeResizable();
  188. }
  189. function makeDraggable() {
  190. $(".bloque-draggable").draggable({
  191. cursor: "move",
  192. containment:"#area-horario",
  193. grid: [_w, _h],
  194. stack: "#bloque-horarios div",
  195. revert : true,
  196. revertDuration: 0,
  197. start: function( event, ui ) { _drag = true; },
  198. drag: function( event, ui ) { $(this).find('.menu-flotante').addClass('d-none');},
  199. stop: function( event, ui ) {
  200. $(this).find('.menu-flotante').removeClass('d-none');
  201. //Valida que no colisione con otro objeto
  202. _drag = false;
  203. var error = false;
  204. var fechaObj = new Date();
  205. var horaArr;
  206. var objetoOrigen =[0,0,0];//x, y1, y2 (this)
  207. var objetoDestino =[0,0,0];//x, y1, y2
  208. var thisIndex = getIndexClase($(this).data("id_obj"));
  209. var top = ui.position.top;
  210. var left = ui.position.left;
  211. //Obtiene coordenadas de objeto actual
  212. objetoOrigen[0] = left;
  213. objetoOrigen[1] = top;
  214. objetoOrigen[2] = top + getAlto(horariosObj[thisIndex].duracion);
  215. for(var i=0; i < horariosObj.length; i++){
  216. if(horariosObj[i].id_obj != $(this).data("id_obj")){
  217. fechaObj = new Date();
  218. //no es el objeto actual, obtiene coordenadas
  219. objetoDestino[0] = getX(horariosObj[i].dia);
  220. objetoDestino[1] = getY(horariosObj[i].hora);
  221. horaArr = horariosObj[i].hora.split(":");
  222. fechaObj.setHours(horaArr[0]);
  223. fechaObj.setMinutes(horaArr[1]);
  224. fechaObj.setMinutes(fechaObj.getMinutes() + parseInt(horariosObj[i].duracion));
  225. objetoDestino[2] = getY(fechaObj.getHours()+":"+fechaObj.getMinutes());
  226. //valida si se sobreponen
  227. if(objetoOrigen[0] == objetoDestino[0]){
  228. if(
  229. (objetoOrigen[1] >= objetoDestino[1] && objetoOrigen[1] < objetoDestino[2]) ||
  230. (objetoDestino[1] >= objetoOrigen[1] && objetoDestino[1] < objetoOrigen[2])
  231. ){//si se sobreponen, lo regresa a su posición anterior
  232. //si son horario completo o si se enciman las fechas
  233. $(this).draggable( "option", "revert", true );
  234. error = true;
  235. //alert("No se puede mover el horario.");
  236. }
  237. }
  238. }
  239. }
  240. if(!error){//no se sobreponen
  241. //Valida cuadricula
  242. top = Math.floor(top / _h)*_h;
  243. if(top < 0) top = 0;
  244. left = Math.floor(left / _w)*_w;
  245. if(left < 0) left = 0;
  246. //Actualiza objeto
  247. horariosObj[thisIndex].dia = getDia(left);
  248. horariosObj[thisIndex].hora = getHora(top)+":"+getMinutos(top);
  249. if(guardaHorario(0, horariosObj[thisIndex])){
  250. $(this).css({top: top + "px", left: left + "px"});
  251. horariosObj[thisIndex].dia_orig = horariosObj[thisIndex].dia;
  252. }else{
  253. $(this).draggable( "option", "revert", true );
  254. horariosObj[thisIndex].dia = horariosObj[thisIndex].dia_orig;
  255. }
  256. }
  257. }
  258. });
  259. }
  260. function makeResizable() {
  261. $(".bloque-resizable").resizable({
  262. containment:"#area-horario",
  263. maxWidth: _w,
  264. minWidth: 1,
  265. minHeight: _frac,
  266. grid: [_w, _h],
  267. handles: "s",
  268. autoHide: true,
  269. start: function( event, ui ) { _drag = true;},
  270. stop: function( event, ui ) {
  271. //Valida que no colisione con otro objeto
  272. _drag = false;
  273. var error = false;
  274. var thisIndex = getIndexClase($(this).data("id_obj"));
  275. var fechaObj = new Date();
  276. var horaArr;
  277. var objetoOrigen =[0,0,0];//x, y1, y2 (this)
  278. var objetoDestino =[0,0,0];//x, y1, y2
  279. var top = ui.position.top;
  280. var height = ui.size.height;
  281. var left = ui.position.left;
  282. //Obtiene coordenadas de objeto actual
  283. objetoOrigen[0] = left;
  284. objetoOrigen[1] = top;
  285. objetoOrigen[2] = top + height;
  286. for(var i=0; i < horariosObj.length; i++){
  287. if(horariosObj[i].id_obj != $(this).data("id_obj")){
  288. fechaObj = new Date();
  289. //no es el objeto actual, obtiene coordenadas
  290. objetoDestino[0] = getX(horariosObj[i].dia);
  291. objetoDestino[1] = getY(horariosObj[i].hora);
  292. horaArr = horariosObj[i].hora.split(":");
  293. fechaObj.setHours(horaArr[0]);
  294. fechaObj.setMinutes(horaArr[1]);
  295. fechaObj.setMinutes(fechaObj.getMinutes() + parseInt(horariosObj[i].duracion));
  296. objetoDestino[2] = getY(fechaObj.getHours()+":"+fechaObj.getMinutes());
  297. //valida si se sobreponen
  298. if(objetoOrigen[0] == objetoDestino[0]){
  299. if(
  300. (objetoOrigen[2] > objetoDestino[1] && objetoOrigen[1] < objetoDestino[1])
  301. ){//si se sobreponen, lo regresa a su posición anterior
  302. //si son horario completo o si se enciman las fechas
  303. $(this).css('height', ui.originalSize.height + 2);
  304. error = true;
  305. //alert("No se puede mover el horario.");
  306. }
  307. }
  308. }
  309. }
  310. if(!error){//no se sobreponen
  311. //Valida cuadricula
  312. height = Math.ceil(height / _h)*_h;
  313. //Actualiza objeto
  314. horariosObj[thisIndex].duracion = height/(_h*_frac) * 60;
  315. if(guardaHorario(0, horariosObj[thisIndex])){
  316. $(this).css({height: height + "px"});
  317. $(this).find(".tiempo").text(height/(_h*_frac));
  318. // $(this).css('height', {height: (ui.originalSize.height) + "px"});
  319. }else{
  320. ui.element.css('height', ui.originalSize.height + 2);
  321. }
  322. }else{
  323. }
  324. },
  325. });
  326. }
  327. function getIndexClase(idobj){//busca en qué posición del arreglo está el id del horario
  328. for(var i=0; i < horariosObj.length; i++){
  329. if(horariosObj[i].id_obj == idobj){
  330. return i;
  331. }
  332. }
  333. return -1;
  334. }
  335. $(document).on( "click", ".bloque-borra", function(event){
  336. var thisIndex = getIndexClase($("#id_borrar").val());
  337. $.ajax({
  338. url: './action/midisponibilidad_delete.php',
  339. type: 'POST',
  340. dataType: 'json',
  341. async: false,
  342. data: { json: JSON.stringify(horariosObj[thisIndex])},
  343. beforeSend: function(x) {
  344. if (x && x.overrideMimeType) {
  345. x.overrideMimeType("application/j-son;charset=UTF-8");
  346. }
  347. },
  348. success: function(result) {
  349. if(result["error"]!= "" && result["error"] !== undefined){
  350. $("#errorBox").collapse('show');
  351. $("#errorBox_text").html("Error al borrar el horario.");
  352. $('#messageBox')[0].scrollIntoView({ block: "end" });
  353. }else{
  354. $('#bloque_'+$("#id_borrar").val()).remove();
  355. var deletedObj = horariosObj.splice(thisIndex, 1);
  356. }
  357. },
  358. error: function(jqXHR, textStatus, errorThrown ){
  359. $("#errorBox").collapse('show');
  360. $("#errorBox_text").html(errorThrown);
  361. $('#messageBox')[0].scrollIntoView({ block: "end" });
  362. }
  363. });//ajax
  364. $(this).parents(".modal").modal("hide");
  365. });