mihorario.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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(), parseInt($('#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: parseInt($('#duracion').val())*60,
  37. tipo: parseInt($('#tipo').find(':selected').val()),
  38. tipo_nombre: $('#tipo').find(':selected').text(),
  39. editable: true,
  40. color: $('#tipo').find(':selected').data('color')
  41. };
  42. if(guardaHorario(1, horario)){
  43. horariosObj.push(horario);
  44. //Crea horario HMTL
  45. calculaTotalDia(horario.dia);
  46. calculaTotalTipo(horario.tipo);
  47. creaHorarioHTML(id_obj, getX(horario.dia), getY(horario.hora), getAlto(horario.duracion) ,horario.color, horario.tipo_nombre, horario.editable, "#bloque-horarios");
  48. id_obj++;
  49. calculaTotalHorarios();
  50. }
  51. $('#modal').modal('hide');
  52. }//fin duración valida
  53. else{
  54. $("#avanzadoBox").collapse('show');
  55. $('#duracion').addClass('is-invalid');
  56. }
  57. });
  58. });
  59. 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
  60. var horaObjIni = new Date();
  61. var horaObjFin;
  62. var horaArr = hora_ini.split(":");
  63. horaObjIni.setHours(horaArr[0]);
  64. horaObjIni.setMinutes(horaArr[1]);
  65. horaObjIni.setSeconds(0);
  66. horaObjFin = new Date(horaObjIni.getTime());
  67. horaObjFin.setMinutes(horaObjFin.getMinutes() + parseInt(duracion));
  68. //Obtiene última hora de clase
  69. var fechaLimite = new Date();
  70. fechaLimite.setHours(parseInt($('.hora').last().data('hora')) + 1);
  71. fechaLimite.setMinutes(0);
  72. fechaLimite.setSeconds(0);
  73. if( Date.parse(horaObjFin) > Date.parse(fechaLimite)){
  74. return false;
  75. }
  76. return validaHorasBloque(pos, dia, horaObjIni, horaObjFin);//valida si choca con el siguiente
  77. }
  78. function validaHorasBloque(pos, dia, horaObjIni, horaObjFin){
  79. for(var i=0; i < horariosObj.length; i++){
  80. var horaArr = horariosObj[i].hora.split(":");
  81. var horaClaseInicio = new Date();
  82. horaClaseInicio.setHours(horaArr[0]);
  83. horaClaseInicio.setMinutes(horaArr[1]);
  84. horaClaseInicio.setSeconds(0);
  85. //Objeto leído no es el objeto actual, mismo día, hora de fin del objeto actual choca con hora de inicio objeto anterior
  86. if(pos != i && parseInt(horariosObj[i].dia) == parseInt(dia) && Date.parse(horaClaseInicio) < Date.parse(horaObjFin) && Date.parse(horaClaseInicio) > Date.parse(horaObjIni)){
  87. return false;//Si existe, no es válido
  88. }
  89. }
  90. return true;//no existe, es válido
  91. }
  92. //funcion para guardar por ajax información
  93. function guardaHorario(nuevo, objClase){
  94. console.log("Guardar");
  95. _editable = false;
  96. var url = './action/mihorario_insert.php';
  97. if(nuevo != 1){
  98. url = './action/mihorario_update.php';
  99. }
  100. var state = false;
  101. $.ajax({
  102. url: url,
  103. type: 'POST',
  104. dataType: 'json',
  105. async: false,
  106. data: { json: JSON.stringify(objClase)},
  107. beforeSend: function(x) {
  108. if (x && x.overrideMimeType) {
  109. x.overrideMimeType("application/j-son;charset=UTF-8");
  110. }
  111. },
  112. success: function(result) {
  113. if(result["error"]!= "" && result["error"] !== undefined){
  114. $("#errorBox").collapse('show');
  115. $("#errorBox_text").html("Error al guardar el horario.<br>"+result["error"]);
  116. $('#messageBox')[0].scrollIntoView({ block: "end" });
  117. state = false;
  118. }else{
  119. state = true;
  120. if(nuevo == 1){
  121. objClase.id_db = result["id"];
  122. }
  123. }
  124. },
  125. error: function(jqXHR, textStatus, errorThrown ){
  126. $("#errorBox").collapse('show');
  127. $("#errorBox_text").html(errorThrown);
  128. $('#messageBox')[0].scrollIntoView({ block: "end" });
  129. state = false;
  130. }
  131. });//ajax
  132. _editable = true;
  133. return state;
  134. }
  135. function loadHorarioEdicion(){
  136. $('.bloque-clase').remove();
  137. horariosObj = [];
  138. id_obj = 0;
  139. //carga horarios y crea bloques
  140. $.ajax({
  141. url: './action/mihorario_select.php',
  142. type: 'POST',
  143. dataType: 'json',
  144. data: { autorizacion: _horarioEstado, fecha: $("#filter_fecha").val()},
  145. success: function(result) {
  146. if(result["error"]!= "" && result["error"] !== undefined){
  147. console.log("Ocurrió un error de load");
  148. $("#errorBox").collapse('show');
  149. $("#errorBox_text").html(result["error"]);
  150. $('#messageBox')[0].scrollIntoView({ block: "end" });
  151. }else{
  152. if(result["errorArr"] !== undefined){
  153. $("#errorBox").collapse('show');
  154. $("#errorBox_text").html("Hay bloques en el horario propuesto que tienen conflicto, crea uno nuevo");
  155. $('#messageBox')[0].scrollIntoView({ block: "end" });
  156. }
  157. var i, j;
  158. for(i = 0; i< result["horario"].length; i++){
  159. var horario = {
  160. id_obj: id_obj,
  161. id_db: parseInt(result["horario"][i]["id"]),
  162. dia: parseInt(result["horario"][i]["dia"]),
  163. dia_orig: parseInt(result["horario"][i]["dia"]),
  164. hora: result["horario"][i]["hora"],
  165. duracion: parseInt(result["horario"][i]["duracion"]),
  166. tipo: parseInt(result["horario"][i]["tipo"]),
  167. tipo_nombre: result["horario"][i]["tipo_nombre"],
  168. editable: result["horario"][i]["editable"],
  169. color: result["horario"][i]["color"]
  170. };
  171. horariosObj.push(horario);
  172. calculaTotalDia(horario.dia);
  173. calculaTotalTipo(horario.tipo);
  174. creaHorarioHTML(id_obj, getX(horario.dia), getY(horario.hora), getAlto(horario.duracion) ,horario.color, horario.tipo_nombre, horario.editable, "#bloque-horarios");
  175. id_obj++;
  176. }//fin for
  177. calculaTotalHorarios();
  178. }
  179. _editable = true;
  180. },
  181. error: function(jqXHR, textStatus, errorThrown ){
  182. $("#errorBox").collapse('show');
  183. $("#errorBox_text").html("Error al cargar horario.<br>"+errorThrown);
  184. $('#messageBox')[0].scrollIntoView({ block: "end" });
  185. _editable = true;
  186. }
  187. });//ajax
  188. }
  189. function creaHorarioHTML(id, posX, posY, alto, color, texto, editable, parentBox){//crea bloque HTML
  190. var edit_class = "";
  191. var zindex = "";
  192. if(editable === true ){
  193. edit_class = "bloque-draggable ui-draggable ui-draggable-handle bloque-resizable";
  194. zindex = "3";
  195. }else{
  196. zindex = "1";
  197. }
  198. var nuevoHorario = '<div class="bloque-clase no-overflow '+edit_class+'" id="bloque_'+id+'" data-id_obj="'+id+'"\
  199. style="top:'+posY+'px; left:'+posX+'px; background-color:'+color+'; height:'+alto+'px; z-index: '+zindex+'" >\
  200. <div class="menu-wrapper">\
  201. <p><b><span class="title">'+texto+'</span></b></p>\
  202. <p>Tiempo total: <span class="tiempo">'+(alto / (_h*_frac))+'</span> hrs. </p>\
  203. <div class="menu-flotante d-none">\
  204. <span class="float-right iconos" >';
  205. if(editable === true ){
  206. nuevoHorario +='<span class="ing-basura ing-fw mx-1" aria-hidden="true" data-toggle="modal" data-target="#modal_confirm" title="Borrar bloque"></span>';
  207. }
  208. nuevoHorario +='</span>\
  209. </div>\
  210. </div>\
  211. </div>';
  212. $(nuevoHorario).appendTo(parentBox);
  213. makeDraggable();
  214. makeResizable();
  215. }
  216. function makeDraggable() {
  217. $(".bloque-draggable").draggable({
  218. cursor: "move",
  219. containment:"#area-horario",
  220. grid: [_w, _h],
  221. stack: "#bloque-horarios div",
  222. revert : true,
  223. revertDuration: 0,
  224. start: function( event, ui ) { _drag = true; },
  225. drag: function( event, ui ) { $(this).find('.menu-flotante').addClass('d-none');},
  226. stop: function( event, ui ) {
  227. $(this).find('.menu-flotante').removeClass('d-none');
  228. //Valida que no colisione con otro objeto
  229. _drag = false;
  230. var error = false;
  231. var fechaObj = new Date();
  232. var horaArr;
  233. var objetoOrigen =[0,0,0];//x, y1, y2 (this)
  234. var objetoDestino =[0,0,0];//x, y1, y2
  235. var thisIndex = getIndexClase($(this).data("id_obj"));
  236. var top = ui.position.top;
  237. var left = ui.position.left;
  238. //Obtiene coordenadas de objeto actual
  239. objetoOrigen[0] = left;
  240. objetoOrigen[1] = top;
  241. objetoOrigen[2] = top + getAlto(horariosObj[thisIndex].duracion);
  242. for(var i=0; i < horariosObj.length; i++){
  243. if(horariosObj[i].id_obj != $(this).data("id_obj")){
  244. fechaObj = new Date();
  245. //no es el objeto actual, obtiene coordenadas
  246. objetoDestino[0] = getX(horariosObj[i].dia);
  247. objetoDestino[1] = getY(horariosObj[i].hora);
  248. horaArr = horariosObj[i].hora.split(":");
  249. fechaObj.setHours(horaArr[0]);
  250. fechaObj.setMinutes(horaArr[1]);
  251. fechaObj.setMinutes(fechaObj.getMinutes() + parseInt(horariosObj[i].duracion));
  252. objetoDestino[2] = getY(fechaObj.getHours()+":"+fechaObj.getMinutes());
  253. //valida si se sobreponen
  254. if(objetoOrigen[0] == objetoDestino[0]){
  255. if(
  256. (objetoOrigen[1] >= objetoDestino[1] && objetoOrigen[1] < objetoDestino[2]) ||
  257. (objetoDestino[1] >= objetoOrigen[1] && objetoDestino[1] < objetoOrigen[2])
  258. ){//si se sobreponen, lo regresa a su posición anterior
  259. //si son horario completo o si se enciman las fechas
  260. $(this).draggable( "option", "revert", true );
  261. error = true;
  262. //alert("No se puede mover el horario.");
  263. }
  264. }
  265. }
  266. }
  267. if(!error){//no se sobreponen
  268. //Valida cuadricula
  269. top = Math.floor(top / _h)*_h;
  270. if(top < 0) top = 0;
  271. left = Math.floor(left / _w)*_w;
  272. if(left < 0) left = 0;
  273. //Actualiza objeto
  274. horariosObj[thisIndex].dia = getDia(left);
  275. horariosObj[thisIndex].hora = getHora(top)+":"+getMinutos(top);
  276. calculaTotalDia(horariosObj[thisIndex].dia);
  277. calculaTotalDia(horariosObj[thisIndex].dia_orig);
  278. if(guardaHorario(0, horariosObj[thisIndex])){
  279. $(this).css({top: top + "px", left: left + "px"});
  280. horariosObj[thisIndex].dia_orig = horariosObj[thisIndex].dia;
  281. }else{
  282. $(this).draggable( "option", "revert", true );
  283. horariosObj[thisIndex].dia = horariosObj[thisIndex].dia_orig;
  284. }
  285. }
  286. }
  287. });
  288. }
  289. function makeResizable() {
  290. $(".bloque-resizable").resizable({
  291. containment:"#area-horario",
  292. maxWidth: _w,
  293. minWidth: 1,
  294. minHeight: _frac,
  295. grid: [_w, _h],
  296. handles: "s",
  297. autoHide: true,
  298. start: function( event, ui ) { _drag = true;},
  299. stop: function( event, ui ) {
  300. //Valida que no colisione con otro objeto
  301. _drag = false;
  302. var error = false;
  303. var thisIndex = getIndexClase($(this).data("id_obj"));
  304. var fechaObj = new Date();
  305. var horaArr;
  306. var objetoOrigen =[0,0,0];//x, y1, y2 (this)
  307. var objetoDestino =[0,0,0];//x, y1, y2
  308. var top = ui.position.top;
  309. var height = ui.size.height;
  310. var left = ui.position.left;
  311. //Obtiene coordenadas de objeto actual
  312. objetoOrigen[0] = left;
  313. objetoOrigen[1] = top;
  314. objetoOrigen[2] = top + height;
  315. for(var i=0; i < horariosObj.length; i++){
  316. if(horariosObj[i].id_obj != $(this).data("id_obj")){
  317. fechaObj = new Date();
  318. //no es el objeto actual, obtiene coordenadas
  319. objetoDestino[0] = getX(horariosObj[i].dia);
  320. objetoDestino[1] = getY(horariosObj[i].hora);
  321. horaArr = horariosObj[i].hora.split(":");
  322. fechaObj.setHours(horaArr[0]);
  323. fechaObj.setMinutes(horaArr[1]);
  324. fechaObj.setMinutes(fechaObj.getMinutes() + parseInt(horariosObj[i].duracion));
  325. objetoDestino[2] = getY(fechaObj.getHours()+":"+fechaObj.getMinutes());
  326. //valida si se sobreponen
  327. if(objetoOrigen[0] == objetoDestino[0]){
  328. if(
  329. (objetoOrigen[2] > objetoDestino[1] && objetoOrigen[1] < objetoDestino[1])
  330. ){//si se sobreponen, lo regresa a su posición anterior
  331. //si son horario completo o si se enciman las fechas
  332. $(this).css('height', ui.originalSize.height + 2);
  333. error = true;
  334. //alert("No se puede mover el horario.");
  335. }
  336. }
  337. }
  338. }
  339. if(!error){//no se sobreponen
  340. //Valida cuadricula
  341. height = Math.ceil(height / _h)*_h;
  342. //Actualiza objeto
  343. horariosObj[thisIndex].duracion = height/(_h*_frac) * 60;
  344. calculaTotalDia(horariosObj[thisIndex].dia);
  345. calculaTotalTipo(horariosObj[thisIndex].tipo);
  346. calculaTotalHorarios();
  347. if(guardaHorario(0, horariosObj[thisIndex])){
  348. $(this).css({height: height + "px"});
  349. $(this).find(".tiempo").text(height/(_h*_frac));
  350. // $(this).css('height', {height: (ui.originalSize.height) + "px"});
  351. }else{
  352. ui.element.css('height', ui.originalSize.height + 2);
  353. }
  354. }else{
  355. }
  356. },
  357. });
  358. }
  359. function getIndexClase(idobj){//busca en qué posición del arreglo está el id del horario
  360. for(var i=0; i < horariosObj.length; i++){
  361. if(horariosObj[i].id_obj == idobj){
  362. return i;
  363. }
  364. }
  365. return -1;
  366. }
  367. function calculaTotalDia(dia){
  368. var total_d = 0;
  369. for(var i =0; i < horariosObj.length; i++){
  370. if(horariosObj[i].dia == dia){
  371. total_d+= (horariosObj[i].duracion/60);
  372. }
  373. }
  374. $("#total_"+dia).text(total_d);
  375. }
  376. function calculaTotalTipo(tipo){
  377. var total_t = 0;
  378. for(var i =0; i < horariosObj.length; i++){
  379. if(horariosObj[i].tipo == tipo){
  380. total_t+= (horariosObj[i].duracion/60);
  381. }
  382. }
  383. $("#total_tipo_"+tipo).text(total_t);
  384. }
  385. function calculaTotalHorarios(){
  386. var total_t = 0;
  387. for(var i =0; i < horariosObj.length; i++){
  388. total_t+= (horariosObj[i].duracion/60);
  389. }
  390. $("#total_all").text(total_t);
  391. }
  392. $(document).on( "click", ".borrar-todo", function(event){
  393. //Borra todos los horarios propuestos
  394. var i;
  395. for(i = 0; i < horariosObj.length; i++){
  396. if(horariosObj[i]["tipo"] != 3){//no borra horarios docentes
  397. $.ajax({
  398. url: './action/mihorario_delete.php',
  399. type: 'POST',
  400. dataType: 'json',
  401. async: false,
  402. data: { json: JSON.stringify(horariosObj[i])},
  403. beforeSend: function(x) {
  404. if (x && x.overrideMimeType) {
  405. x.overrideMimeType("application/j-son;charset=UTF-8");
  406. }
  407. },
  408. success: function(result) {
  409. if(result["error"]!= "" && result["error"] !== undefined){
  410. $("#errorBox").collapse('show');
  411. $("#errorBox_text").html("Error al borrar el horario.");
  412. $('#messageBox')[0].scrollIntoView({ block: "end" });
  413. }else{
  414. $('#bloque_'+horariosObj[i]["id_obj"]).remove();
  415. var deletedObj = horariosObj.splice(i, 1);
  416. calculaTotalDia(deletedObj[0].dia);
  417. calculaTotalTipo(deletedObj[0].tipo);
  418. }
  419. },
  420. error: function(jqXHR, textStatus, errorThrown ){
  421. $("#errorBox").collapse('show');
  422. $("#errorBox_text").html(errorThrown);
  423. $('#messageBox')[0].scrollIntoView({ block: "end" });
  424. }
  425. });//ajax
  426. $(this).parents(".modal").modal("hide");
  427. }
  428. }
  429. calculaTotalHorarios();
  430. });
  431. $(document).on( "click", ".bloque-borra", function(event){
  432. var thisIndex = getIndexClase($("#id_borrar").val());
  433. $.ajax({
  434. url: './action/mihorario_delete.php',
  435. type: 'POST',
  436. dataType: 'json',
  437. async: false,
  438. data: { json: JSON.stringify(horariosObj[thisIndex])},
  439. beforeSend: function(x) {
  440. if (x && x.overrideMimeType) {
  441. x.overrideMimeType("application/j-son;charset=UTF-8");
  442. }
  443. },
  444. success: function(result) {
  445. if(result["error"]!= "" && result["error"] !== undefined){
  446. $("#errorBox").collapse('show');
  447. $("#errorBox_text").html("Error al borrar el horario.");
  448. $('#messageBox')[0].scrollIntoView({ block: "end" });
  449. }else{
  450. $('#bloque_'+$("#id_borrar").val()).remove();
  451. var deletedObj = horariosObj.splice(thisIndex, 1);
  452. calculaTotalDia(deletedObj[0].dia);
  453. calculaTotalTipo(deletedObj[0].tipo);
  454. calculaTotalHorarios();
  455. }
  456. },
  457. error: function(jqXHR, textStatus, errorThrown ){
  458. $("#errorBox").collapse('show');
  459. $("#errorBox_text").html(errorThrown);
  460. $('#messageBox')[0].scrollIntoView({ block: "end" });
  461. }
  462. });//ajax
  463. $(this).parents(".modal").modal("hide");
  464. });
  465. $(document).on( "click", ".bloque-send", function(event){
  466. var btnSend = $(this);
  467. $.ajax({
  468. url: './action/mihorarioestado_update.php',
  469. type: 'POST',
  470. dataType: 'json',
  471. async: false,
  472. data: { orig: btnSend.data("orig"), dest: btnSend.data("dest"), fecha:$("#filter_fecha").val()},
  473. success: function(result) {
  474. if(result["error"]!= "" && result["error"] !== undefined){
  475. $("#errorBox").collapse('show');
  476. $("#errorBox_text").html(result["error"]);
  477. $('#messageBox')[0].scrollIntoView({ block: "end" });
  478. }else{
  479. if(result["conflictoCount"] !== undefined && result["conflictoCount"] > 0)
  480. window.location.href = "mihorario.php?ok=0&error=5";
  481. else
  482. window.location.href = "mihorario.php?ok=0";
  483. }
  484. },
  485. error: function(jqXHR, textStatus, errorThrown ){
  486. $("#errorBox").collapse('show');
  487. $("#errorBox_text").html(errorThrown);
  488. $('#messageBox')[0].scrollIntoView({ block: "end" });
  489. }
  490. });//ajax
  491. $(this).parents(".modal").modal("hide");
  492. });