timesheet source code
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1257 líneas
34KB

  1. (function ($) {
  2. $(function () {
  3. // http://davidwalsh.name/javascript-debounce-function
  4. function debounce(func, wait, immediate) {
  5. var timeout;
  6. return function () {
  7. var context = this, args = arguments;
  8. var later = function () {
  9. timeout = null;
  10. if (!immediate)
  11. func.apply(context, args);
  12. };
  13. var callNow = immediate && !timeout;
  14. clearTimeout(timeout);
  15. timeout = setTimeout(later, wait);
  16. if (callNow)
  17. func.apply(context, args);
  18. };
  19. };
  20. /*____________________________________________________________________________________*/
  21. class People{
  22. constructor(selector, template, data){
  23. this.selector = selector;
  24. this.data = data;
  25. this.template = template;
  26. // this.sample_people = {
  27. // login: '01515b52-6936-46b2-a000-9ad4cd7a5b50',
  28. // firstname: "first",
  29. // lastname: "last",
  30. // phone: '041122221',
  31. // email: 'abc@gmail.com',
  32. // pay: 0,
  33. // hour: 12,
  34. // OT: 3,
  35. // petrol: 50,
  36. // rating: 1,
  37. // };
  38. this.load_data(this.data);
  39. }
  40. load_data(data){
  41. var template = $(this.template).html();
  42. var html = Mustache.render(template, data);
  43. $(this.selector).html(html);
  44. //save it
  45. $(this.selector).data({obj:this, data:data});
  46. //draw rating star
  47. this.set_ratings(this.data.rating);
  48. this.set_unconfirmed_job(this.data.unconfirmedjob);
  49. }
  50. set_ratings(num){
  51. for (var i=1; i<= 5; i++){
  52. if (i <=num){
  53. $(this.selector + " div[name='rating'] span:nth-child(" +i+ ")").addClass('checked');
  54. }else{
  55. $(this.selector + " div[name='rating'] span:nth-child(" +i+ ")").removeClass('checked');
  56. }
  57. }
  58. this.data.rating = num;
  59. }
  60. set_unconfirmed_job(num){
  61. if( num == 0 )
  62. $(this.selector + " span[name='badge']").hide();
  63. else
  64. $(this.selector + " span[name='badge']").show();
  65. this.data.unconfirmedjob = num;
  66. }
  67. reset_summary() {
  68. this.summary = {
  69. wages : 0,
  70. normal_hour : 0,
  71. ot_hour : 0,
  72. petrol : 0,
  73. };
  74. this.update_summary_in_gui();
  75. }
  76. add_payment_summary(ps)
  77. {
  78. //{ot: false, hour: "2.67", money: "76.90"}
  79. this.summary.wages += ps.money;
  80. if (! ps.ot )
  81. this.summary.normal_hour += ps.hour;
  82. else
  83. this.summary.ot_hour += ps.hour;
  84. this.update_summary_in_gui();
  85. }
  86. update_summary_in_gui()
  87. {
  88. var msg = '$' + this.summary.wages.toFixed(2);
  89. $(this.selector).find('div[name="wages"]').html(msg);
  90. msg = this.summary.normal_hour.toFixed(2) + '+' +this.summary.ot_hour.toFixed(2) + 'hr';
  91. $(this.selector).find('div[name="hours"]').html(msg);
  92. msg = 'petrol:' + this.summary.petrol.toFixed(2) + 'km';
  93. $(this.selector).find('div[name="petrol"]').html(msg);
  94. }
  95. }//end of class People
  96. function bts_staff_html(data){
  97. var template = $('#staff_item').html();
  98. var head = '<div class="peopleitem" id="p'+ data.login +'">';
  99. r = head + '</div>' ;
  100. return r;
  101. }
  102. function bts_client_html(data){
  103. var template = $('#client_item').html();
  104. var head = '<div class="peopleitem" id="p'+ data.login +'">';
  105. r = head + '</div>' ;
  106. return r;
  107. }
  108. function sample_staff(){
  109. for (var i=1; i<100; i++){
  110. var sample_people = {
  111. login: '01515b52-6936-46b2-a000-9ad4cd7a5b50' +i,
  112. firstname: "first"+i,
  113. lastname: "last",
  114. mobile: '041122221' +i,
  115. email: 'abc@gmail.com' + i,
  116. wages: 0,
  117. hour: i,
  118. OT: 3,
  119. petrol: 50 +i,
  120. rating: Math.floor(Math.random() * Math.floor(5)),
  121. unconfirmedjob: Math.floor(Math.random() * Math.floor(30)),
  122. };
  123. var html = bts_staff_html(sample_people);
  124. jQuery('div.stafflist').append(html);
  125. new People("#p" + sample_people.login, sample_people);
  126. }
  127. }
  128. function list_staff() {
  129. show_loading_staff();
  130. $('div.stafflist div.peopleitem').remove();
  131. $.post(bts().ajax_url, { // POST request
  132. _ajax_nonce: bts().nonce, // nonce
  133. action: "list_staff", // action
  134. }, function(response, status, xhr){
  135. if (response.status =='success'){
  136. response.users.forEach(function(u){
  137. var html = bts_staff_html(u);
  138. jQuery('div.stafflist').append(html);
  139. new People("#p" + u.login,'#staff_item', u);
  140. });
  141. hide_loading_staff();
  142. calculate_total_hour_and_money();
  143. }else{
  144. alert('error getting staff list');
  145. }
  146. });
  147. }
  148. function list_clients() {
  149. show_loading_client();
  150. $('div.clientlist div.peopleitem').remove(); //clear it
  151. $.post(bts().ajax_url, { // POST request
  152. _ajax_nonce: bts().nonce, // nonce
  153. action: "list_client", // action
  154. }, function(response, status, xhr){
  155. if (response.status =='success'){
  156. response.users.forEach(function(u){
  157. hide_loading_client();
  158. var html = bts_client_html(u);
  159. jQuery('div.clientlist').append(html);
  160. new People("#p" + u.login, '#client_item' ,u);
  161. });
  162. }else{
  163. alert('error getting Client list');
  164. }
  165. });
  166. }
  167. function show_loading_staff(){
  168. jQuery('div.stafflist img').attr('src', bts().load_user_img).show();
  169. }
  170. function show_loading_client(){
  171. jQuery('div.clientlist img').attr('src', bts().load_user_img).show();
  172. }
  173. function hide_loading_staff(){
  174. jQuery('div.stafflist img').hide();
  175. }
  176. function hide_loading_client(){
  177. jQuery('div.clientlist img').hide();
  178. }
  179. function show_loading_jobs(){
  180. jQuery('div.workspace img').attr('src', bts().load_job_img).show();
  181. }
  182. function hide_loading_jobs(){
  183. jQuery('div.workspace img').hide();
  184. }
  185. function xero(t){
  186. if (t)
  187. $('div.xero i').show();
  188. else
  189. $('div.xero i').hide();
  190. }
  191. function wifi(t){
  192. if (t)
  193. $('div.wifi i').show();
  194. else
  195. $('div.wifi i').hide();
  196. }
  197. function init_user_search(){
  198. $('div.b_search input').keyup(debounce(function(e){
  199. filter_user(e.target);
  200. }, 500));
  201. }
  202. function filter_user(input){
  203. var value = $(input).attr('value');
  204. value = value.toLowerCase();
  205. var selector = get_selector_for_filter_people(input);
  206. $.each( $(selector).find('div.peopleitem'), function(index, e){
  207. var html = $(e).find('div[name="title"] a').html();
  208. html = html.toLowerCase();
  209. if (-1 != html.indexOf(value)){//we find it;
  210. $(e).show();
  211. }else{
  212. $(e).hide();
  213. }
  214. });
  215. }
  216. function get_selector_for_filter_people(input){
  217. var selector='';
  218. var role = $(input).attr('placeholder');
  219. if (role == 'staff') //we filter staff
  220. selector = 'div.stafflist';
  221. else if (role = 'client')
  222. selector = 'div.clientlist';
  223. return selector;
  224. }
  225. $(document).on('click', 'div.divTableHead.bdelete', function(){
  226. var o = new Job({empty:true});
  227. });
  228. $(document).on('click', 'div[name="copyschedule"]', function(e){
  229. e.stopPropagation();
  230. if (!confirm('add 10 empty new jobs?'))
  231. return;
  232. for (var i=1; i<=10; i++){
  233. var o = new Job({empty:true});
  234. }
  235. });
  236. $(document).on('click', 'div.divTableCell.bdelete', function(){
  237. var job = $(this).closest('.divTable').data().job;
  238. var el = $(this).closest('div.divTable');
  239. if ( job.get_job_id() == '')
  240. el.remove();
  241. else{
  242. if (confirm('delete this job?')){
  243. $.post(bts().ajax_url, { // POST request
  244. _ajax_nonce: bts().nonce, // nonce
  245. action: "delete_job", // action
  246. jobid: job.data.id,
  247. }, function(response, status, xhr){
  248. if (response.status=='success'){
  249. el.addClass('blink_me');
  250. el.fadeOut(900);
  251. setTimeout(function(){
  252. el.remove();
  253. }, 900);
  254. }else{
  255. alert( 'error saving data, please check your network');
  256. }
  257. });
  258. }
  259. }
  260. });
  261. $(document).on('mouseenter', 'div.divTableCell', function(){
  262. $(this).closest('div.divTable').addClass('highlight');
  263. });
  264. $(document).on('mouseleave', 'div.divTableCell', function(){
  265. $(this).closest('div.divTable').removeClass('highlight');
  266. });
  267. $(document).on('click', 'div.workspace span.ticon.ticon-save', function(){
  268. var table = $(this).closest('div.divTable');
  269. table.data().job.do_save_record();
  270. });
  271. $(document).on('click', '.divTableHeading span.ticon.ticon-save', function(){
  272. //save all
  273. $('div.workspace span.ticon.ticon-save').each(function (i,e){
  274. if ($(this).is(":visible"))
  275. $(this).trigger('click');
  276. });
  277. });
  278. $(document).on('click', 'span.ticon.ticon-copy', function(){
  279. if (!confirm("make a copy of this job?"))
  280. return;
  281. var table = $(this).closest('div.divTable');
  282. var job = table.data().job;
  283. clone_data_create_new_job(job.get_record_from_ui());
  284. });
  285. class Job{ //save data for the record, and display it as GUI
  286. constructor(data){
  287. var html = jQuery("#job_item").html();
  288. this.el = $(html);
  289. jQuery('div.workspace').append(this.el);
  290. this.load_data(data);
  291. dtp_init();
  292. this.init_start_rating()
  293. }
  294. init_start_rating(){
  295. var self = this;
  296. this.el.find("div.brating span").click(function(){
  297. var r = $(this).attr('data-rating');
  298. self.mark_dirty();
  299. self.set_rating(r);
  300. })
  301. this.el.find("div.brating").mouseenter(function(){
  302. //change to all hollow star
  303. $(this).find('span').html('☆');
  304. });
  305. this.el.find("div.brating").mouseleave(function(){
  306. self.set_rating(self.data.rating);
  307. });
  308. }
  309. load_data(data)
  310. {
  311. this.set_job_id(data.id);
  312. this.set_tos(data.tos);
  313. this.set_start(data.start);
  314. this.set_finish(data.finish);
  315. this.set_rate(data.rate);
  316. this.set_staff(data.staff);
  317. this.set_client(data.client);
  318. this.set_ack(data.ack);
  319. this.set_rating(data.rating);
  320. //save to html element
  321. this.data = data;
  322. this.el.data({job:this, data:data});
  323. this.mark_dirty_on_new_record(data);
  324. this.mark_week_color();
  325. this.validate(); //also triggers mark errors
  326. }
  327. get_job_id(){
  328. return this.el.find('input[name="id"]').attr('value');
  329. }
  330. set_job_id(val){
  331. return this.el.find('input[name="id"]').attr('value', val);
  332. }
  333. get_tos()
  334. {
  335. return this.el.find('div.btos select').children("option:selected").val();
  336. }
  337. set_tos(val)
  338. {
  339. if (typeof(val) =="undefined")
  340. return;
  341. this.el.find('div.btos select option[value="'+val+'"]').prop('selected',true);
  342. }
  343. get_start(){
  344. return this.el.find('div.bstart input').attr('value');
  345. }
  346. set_start(val)
  347. {
  348. if (typeof(val) =="undefined")
  349. return;
  350. this.el.find('div.bstart input').attr('value', val);
  351. }
  352. get_finish()
  353. {
  354. return this.el.find('div.bfinish input').attr('value');
  355. }
  356. set_finish(val)
  357. {
  358. if (typeof(val) == "undefined")
  359. return;
  360. this.el.find('div.bfinish input').attr('value', val);
  361. }
  362. get_rate()
  363. {
  364. return this.el.find('div.brate select').children("option:selected").val();
  365. }
  366. set_rate(val)
  367. {
  368. if (typeof(val) =="undefined")
  369. return;
  370. this.el.find('div.brate select option[value="'+val+'"]').prop('selected',true);
  371. }
  372. get_staff()
  373. {
  374. return this.el.find('div.bstaff select').children("option:selected").val();
  375. }
  376. set_staff(val)
  377. {
  378. if (typeof(val) =="undefined")
  379. return;
  380. this.el.find('div.bstaff select option[value="'+val+'"]').prop('selected',true);
  381. }
  382. get_client()
  383. {
  384. return this.el.find('div.bclient select').children("option:selected").val();
  385. }
  386. set_client(val)
  387. {
  388. if (typeof(val) =="undefined")
  389. return;
  390. this.el.find('div.bclient select option[value="'+val+'"]').prop('selected',true);
  391. }
  392. get_ack()
  393. {
  394. return this.el.find('div.bconfirmed input:checked').length > 0;
  395. }
  396. set_ack(val)
  397. {
  398. if (typeof(val) =="undefined")
  399. return;
  400. return this.el.find('div.bconfirmed input').prop('checked', val!=0);
  401. }
  402. get_rating(){
  403. var count =0;
  404. this.el.find('div.brating span').each(function(i,e){
  405. if ($(e).html()=='★')
  406. count +=1;
  407. });
  408. return count;
  409. }
  410. set_rating(num){
  411. if (!(1 <= num && num <=5))
  412. return;
  413. this.el.find('div.brating span').each(function(i,e){
  414. var rating = $(e).attr('data-rating');
  415. var rating = parseInt(rating);
  416. if (rating <= num)
  417. $(e).html('★');
  418. else
  419. $(e).html('☆');
  420. });
  421. }
  422. get_record_from_ui(){
  423. var record = {};
  424. record.id = this.get_job_id();
  425. record.tos = this.get_tos();
  426. record.start = this.get_start();
  427. record.finish = this.get_finish();
  428. record.rate = this.get_rate();
  429. record.staff = this.get_staff();
  430. record.client = this.get_client();
  431. record.ack = this.get_ack();
  432. record.rating = this.get_rating();
  433. return record;
  434. }
  435. do_save_record(){
  436. var self = this;
  437. $.post(bts().ajax_url, { // POST request
  438. _ajax_nonce: bts().nonce, // nonce
  439. action: "save_job", // action
  440. record: this.get_record_from_ui(),
  441. }, function(response, status, xhr){
  442. if (response.status=='success'){
  443. self.load_data(response.newdata);
  444. self.mark_saved();
  445. self.mark_old();
  446. }else{
  447. alert( 'error saving data, please check your network');
  448. }
  449. });
  450. }
  451. mark_dirty_on_new_record(data){
  452. if (typeof(data.id) === 'undefined' || data.id == ''){
  453. this.mark_dirty();
  454. this.mark_new();
  455. }
  456. else{
  457. this.mark_saved();
  458. }
  459. }
  460. mark_dirty() //need save
  461. {
  462. var d = this.el.find('.bsave');
  463. d.removeClass('saved');
  464. d.addClass('blink_me');
  465. setTimeout(function(){
  466. d.removeClass('blink_me');
  467. },1000);
  468. }
  469. mark_saved()
  470. {
  471. var d = this.el.find('.bsave');
  472. d.addClass('blink_me');
  473. setTimeout(function(){
  474. d.removeClass('blink_me');
  475. d.addClass('saved');
  476. },1000);
  477. }
  478. //newly created empty record
  479. mark_new()
  480. {
  481. this.el.addClass('emptyrecord');
  482. }
  483. mark_old()
  484. {
  485. this.el.removeClass('emptyrecord');
  486. }
  487. mark_highlight_me(ms){
  488. this.el.addClass('blink_me');
  489. this.el.addClass('highlight');
  490. this.el.addClass('newcopy');
  491. var self = this;
  492. setTimeout(function(){
  493. self.el.removeClass('blink_me');
  494. self.el.removeClass('highlight');
  495. self.el.removeClass('newcopy');
  496. },ms);
  497. }
  498. is_start_valid(){
  499. var s = this.get_start();
  500. return is_valid_date_str(s);
  501. }
  502. is_finish_valid(){
  503. var f = this.get_finish();
  504. if (!is_valid_date_str(f))
  505. return false;
  506. }
  507. is_finish_resonable(){
  508. var f = this.get_finish();
  509. if (!is_valid_date_str(f))
  510. return false;
  511. var s = this.get_start();
  512. s = new Date(s);
  513. f = new Date(f);
  514. return (s < f);
  515. }
  516. validate()
  517. {
  518. this.clear_err_msg();
  519. var ok = this.validate_start() &&
  520. this.validate_finish() &&
  521. this.validate_rate();
  522. if (ok){
  523. this.el.removeClass('invalidjob');
  524. }else{
  525. this.el.addClass('invalidjob');
  526. }
  527. return ok;
  528. }
  529. validate_start(){
  530. var str = this.get_start();
  531. if ( is_valid_date_str(str) ){
  532. this.mark_start_valid();
  533. this.set_err_msg_start('');
  534. return true;
  535. }else{
  536. this.mark_start_invalid();
  537. this.set_err_msg_start('wrong date');
  538. return false;
  539. }
  540. }
  541. validate_finish()
  542. {
  543. var str = this.get_finish();
  544. if (! is_valid_date_str(str)){
  545. this.set_err_msg_finish('wrong date');
  546. this.mark_finish_invalid();
  547. return false;
  548. }
  549. if (!this.is_finish_resonable()){
  550. this.set_err_msg_finish("older than start")
  551. this.mark_finish_invalid();
  552. return false;
  553. }
  554. this.mark_finish_valid();
  555. this.set_err_msg_finish('');
  556. return true;
  557. }
  558. validate_rate()
  559. {
  560. var rate_info = this.get_rate_info_by_id(this.get_rate());
  561. if ( rate_info.RatePerUnit <= 0){
  562. this.set_err_msg_rate('bad rate');
  563. this.mark_rate_invalid();
  564. return false;
  565. }
  566. this.set_err_msg_rate('');
  567. this.mark_rate_valid();
  568. return true;
  569. }
  570. clear_err_msg(){
  571. this.el.find('.divTableRow.errmsg > div').html('');
  572. }
  573. set_err_msg_start(str)
  574. {
  575. this.el.find('div.bstart_err').html(str);
  576. }
  577. set_err_msg_finish(str)
  578. {
  579. this.el.find('div.bfinish_err').html(str);
  580. }
  581. set_err_msg_rate(str)
  582. {
  583. this.el.find('div.brate_err').html(str);
  584. }
  585. set_err_msg_save(str)
  586. {
  587. this.el.find('div.bsave_err').html(str);
  588. }
  589. mark_start_valid(){
  590. this.el.find('div.bstart input').removeClass('invalid');
  591. }
  592. mark_start_invalid(){
  593. this.el.find('div.bstart input').addClass('invalid');
  594. }
  595. mark_finish_valid(){
  596. this.el.find('div.bfinish input').removeClass('invalid');
  597. }
  598. mark_finish_invalid(){
  599. this.el.find('div.bfinish input').addClass('invalid');
  600. }
  601. mark_rate_valid(){
  602. this.el.find('div.brate select').removeClass('invalid');
  603. }
  604. mark_rate_invalid(){
  605. this.el.find('div.brate select').addClass('invalid');
  606. }
  607. mark_week_color(){
  608. this.el.find('div.brating').removeClass('week1color');
  609. this.el.find('div.brating').removeClass('week2color');
  610. if (this.is_week1()){
  611. this.el.find('div.brating').addClass('week1color');
  612. }else if (this.is_week2()){
  613. this.el.find('div.brating').addClass('week2color');
  614. }
  615. }
  616. is_week1()
  617. {
  618. var w1_begin = new Date($('span[name="w1d1"]').data().date) ;
  619. var w1_end = new Date($('span[name="w1d7"]').data().date);
  620. w1_begin.setHours(0,0,0,0);
  621. w1_end.setHours(23,59,59);
  622. //w1_end = new Date (w1_end.setDate(w1_end.getDate()+1)); //from 00:00 to 23:59;
  623. var me = new Date(this.data.start);
  624. return (w1_begin <= me && me <= w1_end );
  625. }
  626. is_week2()
  627. {
  628. var w2_begin = new Date($('span[name="w2d1"]').data().date);
  629. var w2_end = new Date($('span[name="w2d7"]').data().date);
  630. w2_begin.setHours(0,0,0,0);
  631. w2_end.setHours(23,59,59);
  632. var me = new Date(this.data.start);
  633. return (w2_begin <= me && me <= w2_end );
  634. }
  635. get_payment_summary(){
  636. var result ={};
  637. result.ot = this.get_is_high_pay();
  638. result.hour = this.get_working_duration();
  639. result.money = this.get_wages();
  640. return result;
  641. }
  642. get_is_high_pay()
  643. {
  644. var rate_info = this.get_rate_info_by_id(this.get_rate());
  645. return this.is_high_pay_hour(rate_info);
  646. }
  647. get_working_duration()
  648. {
  649. //finish - start
  650. var f = new Date(this.get_finish());
  651. var s = new Date(this.get_start());
  652. var diff = f.getTime() - s.getTime();
  653. var hours = Math.floor(diff / 1000 / 60 / 60);
  654. diff -= hours * 1000 * 60 * 60;
  655. var minutes = Math.floor(diff / 1000 / 60);
  656. var minute_to_hour = minutes/60;
  657. return (hours + minute_to_hour);
  658. }
  659. get_wages(){
  660. var hour = this.get_working_duration();
  661. var rate_info = this.get_rate_info_by_id(this.get_rate());
  662. return hour * rate_info.RatePerUnit;
  663. }
  664. get_rate_info_by_id(id){
  665. var rate_info = {};
  666. var rates = bts().earnings_rate;
  667. for(var i =0; i< rates.length; i++){
  668. var r = rates[i];
  669. if(r.EarningsRateID == id){
  670. rate_info = $.extend(true,{}, r);//make a copy
  671. break;
  672. }
  673. }
  674. return rate_info;
  675. }
  676. is_high_pay_hour(rate_info){
  677. var keywords =bts().high_pay_keywords;
  678. var found = false;
  679. keywords.forEach(function(e){
  680. if (-1 != rate_info.Name.toLowerCase().indexOf(e.toLowerCase()) )
  681. found = true;
  682. });
  683. return found;
  684. }
  685. }//end of class Job
  686. //global GUI summary
  687. function get_wages()
  688. {
  689. var txt = $('div.wages div').html();
  690. return parseInt(txt);
  691. }
  692. function set_wages(num){
  693. $('div.wages div').html(num);
  694. }
  695. function set_working_hours(num){
  696. $('input#woh').attr('value', num);
  697. }
  698. function get_working_hours(){
  699. var txt = $('input#woh').attr('value');
  700. return parseFloat(txt);
  701. }
  702. //modal box
  703. function set_modal_title(selector, title){
  704. var s = 'div.bts_'+ selector +' .ult_modal-title';
  705. $(s).html(title);
  706. }
  707. function set_modal_content(selector, content){
  708. var s = 'div.bts_'+ selector +' div.ult_modal-body.ult-html';
  709. $(s).html(content);
  710. }
  711. function open_modal (selector){
  712. var s='div.bts_'+selector+'_button';
  713. $(s).trigger('click');
  714. }
  715. // setTimeout(function(){
  716. // set_modal_title('warning', 'suck title');
  717. // set_modal_content('warning', 'fucking details');
  718. // //open_modal('warning');
  719. // }, 1000);
  720. //
  721. // setTimeout(function(){
  722. // set_modal_title('error', 'error title');
  723. // set_modal_content('error', 'error details');
  724. // //open_modal('error');
  725. // }, 5000);
  726. $(document).on('mouseenter', 'div.week1 div', function(){
  727. $(this).addClass('blink_me');
  728. get_week2_partner(this).addClass('blink_me');
  729. blink_same_date_by_div(this);
  730. });
  731. $(document).on('mouseleave', 'div.week1 div', function(){
  732. $(this).removeClass('blink_me');
  733. get_week2_partner(this).removeClass('blink_me');
  734. unblink_all_date();
  735. });
  736. function get_week2_partner(div){
  737. var index = $(div).index()+1;
  738. return $('div.week2 div:nth-child('+index+')');
  739. }
  740. function init_weekdays(){
  741. var curr = new Date; // get current date
  742. // First day is the day of the month - the day of the week
  743. var first = curr.getDate() - curr.getDay() + 1; //+1 we want Mon as first
  744. var last = first + 6; // last day is the first day + 6
  745. //var firstday = new Date(curr.setDate(first)); //Mon
  746. //var lastday = new Date(curr.setDate(last)); //Sun
  747. var pos = 1; //first lot
  748. for (var i=first; i<=last; i++)
  749. {
  750. var d1 = new Date(curr.setDate(i));
  751. var d2 = new Date(curr.setDate(i+7));
  752. set_day_number(1,pos, d1); //week 1
  753. set_day_number(2,pos, d2); //week 2
  754. pos +=1;
  755. }
  756. }
  757. function set_day_number(week, index, date){
  758. var selector = 'span[name="w'+week+'d'+index+'"]';
  759. $(selector).html(date.getDate());
  760. $(selector).data({date:date});
  761. }
  762. function set_today(){
  763. var selector = 'div.sheettitle span[name="today"]';
  764. var curr = new Date;
  765. $(selector).html(format_date(curr));
  766. }
  767. Date.prototype.get_week_number = function(){
  768. var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
  769. var dayNum = d.getUTCDay() || 7;
  770. d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  771. var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
  772. return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
  773. };
  774. function set_week_number(){
  775. var date = $('span[name="w1d1"]').data().date;
  776. //console.log("date %o", date);
  777. var num = date.get_week_number();
  778. $('div.weekly span[name="week1"]').html(num);
  779. $('div.weekly span[name="week2"]').html(num+1);
  780. }
  781. function number_of_unsaved_job(){
  782. var count =0;
  783. var total_job = $('div.bsave').length -1;//remove table header
  784. var total_saved = $('div.bsave.saved').length;
  785. var empty = $('div.emptyrecord').length;
  786. count = total_job - total_saved - empty;
  787. return count;
  788. }
  789. $('div.prevweek.left').click(function(){
  790. if (number_of_unsaved_job() > 0){
  791. if(!confirm("you have unsaved jobs, proceed will lost them"))
  792. return;
  793. }
  794. $('div.weekdays span.weekday').each(function(i, e){
  795. var date = $(e).data().date;
  796. var newdate = new Date(date.setDate(date.getDate() -7 ));
  797. $(e).html(newdate.getDate());
  798. $(e).data({data:newdate});
  799. });
  800. set_week_number();
  801. load_timesheet();
  802. });
  803. $('div.nextweek.right').click(function(){
  804. if (number_of_unsaved_job() > 0){
  805. if(!confirm("you have unsaved jobs,proceed will lost them"))
  806. return;
  807. }
  808. $('div.weekdays span.weekday').each(function(i, e){
  809. var date = $(e).data().date;
  810. var newdate = new Date(date.setDate(date.getDate() +7 ));
  811. $(e).html(newdate.getDate());
  812. $(e).data({data:newdate});
  813. });
  814. set_week_number();
  815. load_timesheet();
  816. });
  817. $('div.weekly div.weekname.prev').click(function(){
  818. if (!confirm ('copy entire week to next week? '))
  819. return;
  820. var jobs = [];
  821. $('div.week1 >div').each(function(i,e){
  822. var date = new Date($(e).find('span.weekday').data().date);
  823. var strDate = format_date(date); //yyyy-mm-dd
  824. $('div.bstart input').each(function(i,e){
  825. var value = $(e).attr('value');
  826. if( -1 != value.indexOf(strDate) ) //found
  827. {
  828. var j = $(e).closest('div.divTable').data().job;
  829. jobs.push(j);
  830. }
  831. });
  832. });
  833. jobs.forEach(function(e){
  834. clone_data_create_new_job(e.get_record_from_ui(),7);//add 7 days
  835. });
  836. });
  837. $('div.weekly div.weekname.next').click(function(){
  838. alert('you can only copy from past to future (left to right)');
  839. });
  840. $('div.week1 > div').click(function(e){
  841. e.stopPropagation();
  842. if ($('div.bstart input.blink_me').length == 0){
  843. alert("nothing to copy");
  844. return;
  845. }
  846. if (!confirm ('copy to next week'))
  847. return;
  848. $('div.bstart input.blink_me').each(function(i,e){
  849. copy_single_day_to_next_week(e);
  850. });
  851. unblink_all_date();
  852. });
  853. $('div.week1,div.week2').click(function(e){
  854. e.stopPropagation();
  855. $(this).toggleClass('filtered');
  856. filter_workspace_by_weeks();
  857. });
  858. function copy_single_day_to_next_week(el){
  859. var j = $(el).closest('div.divTable').data().job;
  860. clone_data_create_new_job(j.get_data_from_ui() , 7); // +7 days
  861. }
  862. function clone_data_create_new_job(val, num_of_shifted_days){
  863. var data = $.extend(true, {}, val);//make a copy
  864. num_of_shifted_days = typeof num_of_shifted_days !=='undefined'? num_of_shifted_days: 0;// 0 days
  865. //reset
  866. data.id='';
  867. data.ack = 0;
  868. data.rating = 0;
  869. if (is_valid_date_str(data.start)){
  870. var s = new Date(data.start);
  871. var s1 = s.getDate() + num_of_shifted_days;
  872. s = new Date(s.setDate(s1));
  873. data.start = format_date_time(s);
  874. }
  875. if (is_valid_date_str(data.finish)){
  876. var f = new Date(data.finish);
  877. var f1 = f.getDate() + num_of_shifted_days;
  878. f = new Date(f.setDate(f1));
  879. data.finish = format_date_time(f);
  880. }
  881. var newj = new Job(data);
  882. newj.mark_highlight_me(1000);//for 1 second;
  883. }
  884. function is_valid_date_str(val){
  885. var d = new Date(val);
  886. if (d.toString()== 'Invalid Date')
  887. return false;
  888. return true;
  889. }
  890. function blink_same_date_by_div(div){
  891. var date = new Date($(div).find('span.weekday').data().date);
  892. blink_same_date(date);
  893. }
  894. function blink_same_date(date){
  895. var strDate = format_date(date); //yyyy-mm-dd
  896. var els=[];
  897. unblink_all_date();
  898. $('div.bstart input').each(function(i,e){
  899. var value = $(e).attr('value');
  900. if( -1 != value.indexOf(strDate) ) //found
  901. {
  902. els.push(e);
  903. $(e).addClass('blink_me');
  904. }
  905. });
  906. }
  907. function unblink_all_date(){
  908. $('div.bstart input').removeClass('blink_me');
  909. }
  910. $('div.sheettitle h1').click(function(){
  911. reset_title_to_today();
  912. });
  913. function reset_title_to_today(){
  914. set_today();
  915. init_weekdays();
  916. set_week_number();
  917. }
  918. function load_timesheet()
  919. {
  920. clear_workspace();
  921. var first = $('span[name="w1d1"]').data().date;
  922. var last = $('span[name="w2d7"]').data().date;
  923. $.post(bts().ajax_url, { // POST request
  924. _ajax_nonce: bts().nonce, // nonce
  925. action: "list_job", // action
  926. start: format_date(first),
  927. finish: format_date(last),
  928. }, function(response, status, xhr){
  929. if (response.status =='success'){
  930. response.jobs.forEach(function(job){
  931. new Job(job);
  932. });
  933. //filter it if reqired
  934. do_filter_workspace();
  935. }else{
  936. alert('error loading job');
  937. }
  938. hide_loading_jobs();
  939. });
  940. }
  941. function format_date(date){
  942. var dd = date.getDate();
  943. var mm = date.getMonth() + 1; //January is 0!
  944. var yyyy = date.getFullYear();
  945. if (dd < 10) {
  946. dd = '0' + dd;
  947. }
  948. if (mm < 10) {
  949. mm = '0' + mm;
  950. }
  951. return yyyy + '-' + mm + '-' +dd ;
  952. }
  953. function format_date_time(date){
  954. var strdate = format_date(date);
  955. var hh = date.getHours();
  956. if (hh<10){
  957. hh= '0' + hh;
  958. }
  959. var mm = date.getMinutes();
  960. if (mm<10){
  961. mm='0' + mm;
  962. }
  963. return strdate + ' ' + hh + ":" + mm;
  964. }
  965. function clear_workspace()//clear all timesheet jobs
  966. {
  967. $('div.workspace > div.divTable').remove();
  968. //clear datetime picker
  969. $('div.xdsoft_datetimepicker').remove();
  970. }
  971. $('button[name="confirmschedule"]').click(function(){
  972. //$('div.workspace span.ticon.ticon-save').trigger('click');
  973. });
  974. $(document).on('click','div.userlist', debounce(do_filter_workspace));
  975. function do_filter_workspace(){
  976. var staffs =[];
  977. $('div.stafflist div.peopleitem :checked').each(function(i, e){
  978. var id = $(e).parent().attr('data-id');
  979. //console.log("%o, id=%s", e, id);
  980. staffs.push(id.substring(1));
  981. });
  982. var clients =[];
  983. $('div.clientlist div.peopleitem :checked').each(function(i, e){
  984. var id = $(e).parent().attr('data-id');
  985. //console.log("%o, id=%s", e, id);
  986. clients.push(id.substring(1));
  987. });
  988. filter_workspace(staffs, clients);
  989. calculate_total_hour_and_money();
  990. }
  991. function filter_workspace(staffs, clients){
  992. //if both array is empty
  993. if( (staffs === undefined || staffs.length ==0) &&
  994. (clients===undefined || clients.length ==0)){
  995. //show all
  996. $('div.workspace div.divTable').show();
  997. return;
  998. }
  999. //filter some of them;
  1000. $('div.workspace div.divTable').each(function(i,e){
  1001. var job = $(e).data().job;
  1002. var s = job.get_staff();
  1003. var c = job.get_client();
  1004. if (staffs.indexOf(s) ==-1 && clients.indexOf(c) ==-1)
  1005. $(this).fadeOut();
  1006. else
  1007. $(this).fadeIn();
  1008. });
  1009. }
  1010. function filter_workspace_by_weeks(){
  1011. var hide_week1 = $('div.week1').hasClass('filtered');
  1012. var hide_week2 = $('div.week2').hasClass('filtered');
  1013. if (hide_week1 && hide_week2 ){
  1014. alert("You are hiding both weeks");
  1015. }
  1016. $('div.workspace div.divTable').each(function(i,e){
  1017. var job = $(e).data().job;
  1018. if ((hide_week1 && job.is_week1()) ||
  1019. (hide_week2 && job.is_week2()) ){
  1020. $(e).fadeOut();
  1021. }else{
  1022. $(e).fadeIn();
  1023. }
  1024. });
  1025. debounced_calculate();
  1026. }
  1027. var debounced_calculate = debounce(calculate_total_hour_and_money, 2000);
  1028. function calculate_total_hour_and_money()
  1029. {
  1030. //init pays for all staff;
  1031. var pays={
  1032. total: 0,
  1033. hours: 0,
  1034. };
  1035. $('.stafflist > div.peopleitem').each(function(i,e){
  1036. var people = $(this).data().obj;
  1037. people.reset_summary();
  1038. });
  1039. $('div.workspace > .divTable').each(function(i,e){
  1040. if (! $(e).is(':visible'))
  1041. return;
  1042. var job = $(e).data().job; //class Job
  1043. if (typeof job === 'undefined')
  1044. return;
  1045. var ps = job.get_payment_summary();
  1046. pays.total += ps.money;
  1047. pays.hours += ps.hour;
  1048. var staff = job.get_staff();
  1049. var people = find_staff(staff); //class People
  1050. if (people !=false)
  1051. people.add_payment_summary(ps);
  1052. });
  1053. set_wages(pays.total.toFixed(2));
  1054. set_working_hours(pays.hours.toFixed(2));
  1055. }
  1056. function find_staff(login)
  1057. {
  1058. var d = $('#p'+login).data();
  1059. if (typeof d === 'undefined')
  1060. return false;
  1061. return $('#p'+login).data().obj;
  1062. }
  1063. $(document).on('change', '.divTableRow select, .divTableRow input', function() {
  1064. var job = $(this).closest('.divTable').data().job;
  1065. job.validate();
  1066. job.mark_dirty();
  1067. debounced_calculate();
  1068. });
  1069. function init_ts(){
  1070. show_loading_jobs();
  1071. list_staff();
  1072. list_clients();
  1073. xero(false);
  1074. wifi(false);
  1075. init_user_search();
  1076. //ajax_earning_rate();
  1077. reset_title_to_today();
  1078. load_timesheet();
  1079. }
  1080. // function ajax_earning_rate(){
  1081. // $.post(bts().ajax_url, { // POST request
  1082. // _ajax_nonce: bts().nonce, // nonce
  1083. // action: "earnings_rate", // action
  1084. // }, function(response, status, xhr){
  1085. // bts().earnings_rate = response;
  1086. // console.log("%o", bts().earnings_rate);
  1087. // });
  1088. // }
  1089. init_ts();
  1090. /*________________________________________________________________________*/
  1091. });
  1092. })(jQuery);
  1093. /*______________scrolling______________________________________________*/
  1094. jQuery(document).ready(function(){
  1095. var timeoutid =0;
  1096. jQuery('button.peoplelist[name="down"]').mousedown(function(){
  1097. var button = this;
  1098. timeoutid = setInterval(function(){
  1099. //console.log("down scrotop %d ", jQuery(button).parent().find(".userlist").get(0).scrollTop );
  1100. jQuery(button).parent().find(".userlist").get(0).scrollTop +=240;
  1101. }, 100);
  1102. }).on('mouseup mouseleave', function(){
  1103. clearTimeout(timeoutid);
  1104. });
  1105. jQuery('button.peoplelist[name="up"]').mousedown(function(){
  1106. var button = this;
  1107. timeoutid = setInterval(function(){
  1108. //console.log("up scrotop %d ", jQuery(button).parent().find(".userlist").get(0).scrollTop );
  1109. jQuery(button).parent().find(".userlist").get(0).scrollTop -=240;
  1110. }, 100);
  1111. }).on('mouseup mouseleave', function(){
  1112. clearTimeout(timeoutid);
  1113. });
  1114. });