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.

1327 líneas
36KB

  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. //uncheck everyone
  208. $(e).find('input[type="checkbox"]').prop('checked', false);
  209. var html = $(e).find('div[name="title"] a').html();
  210. html = html.toLowerCase();
  211. if (-1 != html.indexOf(value)){//we find it;
  212. $(e).show();
  213. }else{
  214. $(e).hide();
  215. }
  216. });
  217. }
  218. function get_selector_for_filter_people(input){
  219. var selector='';
  220. var role = $(input).attr('placeholder');
  221. if (role == 'staff') //we filter staff
  222. selector = 'div.stafflist';
  223. else if (role = 'client')
  224. selector = 'div.clientlist';
  225. return selector;
  226. }
  227. $(document).on('click', 'div.divTableHead.bdelete', function(){
  228. add_new_empty_job();
  229. });
  230. function add_new_empty_job(){
  231. var o = new Job({empty:true});
  232. $('div.workspace').append(o.el);
  233. o.el.get(0).scrollIntoView();
  234. dtp_init();
  235. }
  236. $(document).on('click', 'div[name="copyschedule"]', function(e){
  237. e.stopPropagation();
  238. add_new_empty_job();
  239. });
  240. $(document).on('click', 'div.divTableCell.bdelete', function(){
  241. var job = $(this).closest('.divTable').data().job;
  242. var el = $(this).closest('div.divTable');
  243. if ( job.get_job_id() == '')
  244. el.remove();
  245. else{
  246. if (confirm('delete this job?')){
  247. $.post(bts().ajax_url, { // POST request
  248. _ajax_nonce: bts().nonce, // nonce
  249. action: "delete_job", // action
  250. jobid: job.data.id,
  251. }, function(response, status, xhr){
  252. if (response.status=='success'){
  253. el.addClass('blink_me');
  254. el.fadeOut(900);
  255. setTimeout(function(){
  256. el.remove();
  257. }, 900);
  258. }else{
  259. alert( 'error saving data, please check your network');
  260. }
  261. });
  262. }
  263. }
  264. });
  265. $(document).on('mouseenter', 'div.divTableCell', function(){
  266. $(this).closest('div.divTable').addClass('highlight');
  267. });
  268. $(document).on('mouseleave', 'div.divTableCell', function(){
  269. $(this).closest('div.divTable').removeClass('highlight');
  270. });
  271. $(document).on('click', 'div.workspace span.ticon.ticon-save', function(){
  272. var table = $(this).closest('div.divTable');
  273. table.data().job.do_save_record();
  274. });
  275. $(document).on('click', '.divTableHeading span.ticon.ticon-save', function(){
  276. //save all
  277. $('div.workspace span.ticon.ticon-save').each(function (i,e){
  278. if ($(this).is(":visible"))
  279. $(this).trigger('click');
  280. });
  281. });
  282. $(document).on('click', 'span.ticon.ticon-copy', function(){
  283. if (!confirm("make a copy of this job?"))
  284. return;
  285. var table = $(this).closest('div.divTable');
  286. var job = table.data().job;
  287. var newj = clone_data_create_new_job(job.get_record_from_ui());
  288. $('div.workspace').append(newj.el);
  289. newj.el.get(0).scrollIntoView();//make sure it's visible;
  290. newj.mark_highlight_me(1000);//for 1 second;
  291. dtp_init();
  292. });
  293. class Job{ //save data for the record, and display it as GUI
  294. constructor(data){
  295. var html = jQuery("#job_item").html();
  296. this.el = $(html);
  297. //jQuery('div.workspace').append(this.el);
  298. this.load_data(data);
  299. this.init_start_rating();
  300. }
  301. init_start_rating(){
  302. var self = this;
  303. this.el.find("div.brating span").click(function(){
  304. var r = $(this).attr('data-rating');
  305. self.mark_dirty();
  306. self.set_rating(r);
  307. })
  308. this.el.find("div.brating").mouseenter(function(){
  309. //change to all hollow star
  310. $(this).find('span').html('☆');
  311. });
  312. this.el.find("div.brating").mouseleave(function(){
  313. self.set_rating(self.data.rating);
  314. });
  315. }
  316. load_data(data)
  317. {
  318. //save to html element
  319. this.data = data;
  320. this.el.data({job:this, data:data});
  321. //draw GUI
  322. this.clear_err_msg();
  323. this.set_job_id(data.id);
  324. this.set_tos(data.tos);
  325. this.set_start(data.start);
  326. this.set_finish(data.finish);
  327. this.set_rate(data.rate);
  328. this.set_staff(data.staff);
  329. this.set_client(data.client);
  330. this.set_ack(data.ack);
  331. this.set_rating(data.rating);
  332. //draw GUI by other
  333. this.mark_dirty_on_new_record(data);
  334. this.mark_week_color();
  335. this.validate(); //also triggers mark errors
  336. }
  337. get_job_id(){
  338. return this.el.find('input[name="id"]').attr('value');
  339. }
  340. set_job_id(val){
  341. return this.el.find('input[name="id"]').attr('value', val);
  342. }
  343. get_tos()
  344. {
  345. return this.el.find('div.btos select').children("option:selected").val();
  346. }
  347. set_tos(val)
  348. {
  349. if (typeof(val) =="undefined")
  350. return;
  351. this.el.find('div.btos select option[value="'+val+'"]').prop('selected',true);
  352. }
  353. get_start(){
  354. return this.el.find('div.bstart input').attr('value');
  355. }
  356. set_start(val)
  357. {
  358. if (typeof(val) =="undefined")
  359. return;
  360. this.el.find('div.bstart input').attr('value', val);
  361. }
  362. get_finish()
  363. {
  364. return this.el.find('div.bfinish input').attr('value');
  365. }
  366. set_finish(val)
  367. {
  368. if (typeof(val) == "undefined")
  369. return;
  370. this.el.find('div.bfinish input').attr('value', val);
  371. }
  372. get_rate()
  373. {
  374. return this.el.find('div.brate select').children("option:selected").val();
  375. }
  376. set_rate(val)
  377. {
  378. if (typeof(val) =="undefined")
  379. return;
  380. this.el.find('div.brate select option[value="'+val+'"]').prop('selected',true);
  381. }
  382. get_staff()
  383. {
  384. return this.el.find('div.bstaff select').children("option:selected").val();
  385. }
  386. set_staff(val)
  387. {
  388. if (typeof(val) =="undefined")
  389. return;
  390. this.el.find('div.bstaff select option[value="'+val+'"]').prop('selected',true);
  391. }
  392. get_client()
  393. {
  394. return this.el.find('div.bclient select').children("option:selected").val();
  395. }
  396. set_client(val)
  397. {
  398. if (typeof(val) =="undefined")
  399. return;
  400. this.el.find('div.bclient select option[value="'+val+'"]').prop('selected',true);
  401. }
  402. get_ack()
  403. {
  404. return this.el.find('div.bconfirmed input:checked').length > 0;
  405. }
  406. set_ack(val)
  407. {
  408. if (typeof(val) =="undefined")
  409. return;
  410. return this.el.find('div.bconfirmed input').prop('checked', val!=0);
  411. }
  412. get_rating(){
  413. var count =0;
  414. this.el.find('div.brating span').each(function(i,e){
  415. if ($(e).html()=='★')
  416. count +=1;
  417. });
  418. return count;
  419. }
  420. set_rating(num){
  421. if (!(1 <= num && num <=5))
  422. return;
  423. this.el.find('div.brating span').each(function(i,e){
  424. var rating = $(e).attr('data-rating');
  425. var rating = parseInt(rating);
  426. if (rating <= num)
  427. $(e).html('★');
  428. else
  429. $(e).html('☆');
  430. });
  431. }
  432. get_record_from_ui(){
  433. var record = {};
  434. record.id = this.get_job_id();
  435. record.tos = this.get_tos();
  436. record.start = this.get_start();
  437. record.finish = this.get_finish();
  438. record.rate = this.get_rate();
  439. record.staff = this.get_staff();
  440. record.client = this.get_client();
  441. record.ack = this.get_ack();
  442. record.rating = this.get_rating();
  443. return record;
  444. }
  445. do_save_record(){
  446. var self = this;
  447. $.post(bts().ajax_url, { // POST request
  448. _ajax_nonce: bts().nonce, // nonce
  449. action: "save_job", // action
  450. record: this.get_record_from_ui(),
  451. }, function(response, status, xhr){
  452. if (response.status=='success'){
  453. self.load_data(response.newdata);
  454. self.mark_saved();
  455. self.mark_old();
  456. }else{
  457. alert( 'error saving data, please check your network');
  458. }
  459. });
  460. }
  461. mark_dirty_on_new_record(data){
  462. if (typeof(data.id) === 'undefined' || data.id == ''){
  463. this.mark_dirty();
  464. this.mark_new();
  465. }
  466. else{
  467. this.mark_saved();
  468. }
  469. }
  470. mark_dirty() //need save
  471. {
  472. var d = this.el.find('.bsave');
  473. d.removeClass('saved');
  474. d.addClass('blink_me');
  475. setTimeout(function(){
  476. d.removeClass('blink_me');
  477. d.removeClass('saved');
  478. },1000);
  479. }
  480. mark_saved()
  481. {
  482. var d = this.el.find('.bsave');
  483. d.addClass('blink_me');
  484. setTimeout(function(){
  485. d.removeClass('blink_me');
  486. d.addClass('saved');
  487. },1000);
  488. }
  489. //newly created empty record
  490. mark_new()
  491. {
  492. this.el.addClass('emptyrecord');
  493. }
  494. mark_old()
  495. {
  496. this.el.removeClass('emptyrecord');
  497. }
  498. mark_highlight_me(ms){
  499. this.el.addClass('blink_me');
  500. this.el.addClass('highlight');
  501. this.el.addClass('newcopy');
  502. var self = this;
  503. setTimeout(function(){
  504. self.el.removeClass('blink_me');
  505. self.el.removeClass('highlight');
  506. self.el.removeClass('newcopy');
  507. },ms);
  508. }
  509. is_start_valid(){
  510. var s = this.get_start();
  511. return is_valid_date_str(s);
  512. }
  513. is_finish_valid(){
  514. var f = this.get_finish();
  515. if (!is_valid_date_str(f))
  516. return false;
  517. }
  518. is_finish_resonable(){
  519. var f = this.get_finish();
  520. if (!is_valid_date_str(f))
  521. return false;
  522. var s = this.get_start();
  523. s = new Date(s);
  524. f = new Date(f);
  525. return (s < f);
  526. }
  527. validate()
  528. {
  529. var ok_time = this.validate_start() &&
  530. this.validate_finish(); //finish might not be executed, if start is wrong
  531. var ok_tos = this.validate_tos(); //make sure this validate is executed;
  532. var ok_rate = this.validate_rate() ; //make sure this validate is executed
  533. var ok = ok_time && ok_tos && ok_rate;
  534. if (ok){
  535. this.el.removeClass('invalidjob');
  536. }else{
  537. this.el.addClass('invalidjob');
  538. }
  539. return ok;
  540. }
  541. validate_start(){
  542. var str = this.get_start();
  543. if ( is_valid_date_str(str) ){
  544. this.mark_start_valid();
  545. this.set_err_msg_start('');
  546. return true;
  547. }else{
  548. this.mark_start_invalid();
  549. this.set_err_msg_start('wrong date');
  550. return false;
  551. }
  552. }
  553. validate_finish()
  554. {
  555. var str = this.get_finish();
  556. if (! is_valid_date_str(str)){
  557. this.set_err_msg_finish('wrong date');
  558. this.mark_finish_invalid();
  559. return false;
  560. }
  561. if (!this.is_finish_resonable()){
  562. this.set_err_msg_finish("older than start")
  563. this.mark_finish_invalid();
  564. return false;
  565. }
  566. this.mark_finish_valid();
  567. this.set_err_msg_finish('');
  568. return true;
  569. }
  570. validate_rate()
  571. {
  572. var rate_info = this.get_rate_info_by_id(this.get_rate());
  573. if ( rate_info.RatePerUnit <= 0){
  574. this.set_err_msg_rate('bad rate');
  575. this.mark_rate_invalid();
  576. return false;
  577. }
  578. if (this.get_rate() != this.data.rate){
  579. this.set_err_msg_rate('rate@Xero inactive ' + this.data.rate);
  580. this.mark_rate_invalid();
  581. this.mark_dirty();
  582. return false;
  583. }
  584. this.set_err_msg_rate('');
  585. this.mark_rate_valid();
  586. return true;
  587. }
  588. validate_tos(){
  589. if (this.get_tos() != this.data.tos){
  590. this.set_err_msg_tos('require NDIS ' + this.data.tos);
  591. this.mark_tos_invalid();
  592. this.mark_dirty();
  593. console.log('tos mark dirty');
  594. return false;
  595. }
  596. this.set_err_msg_tos('');
  597. this.mark_tos_valid();
  598. return true;
  599. }
  600. clear_err_msg(){
  601. this.el.find('.divTableRow.errmsg > div').html('');
  602. }
  603. set_err_msg_start(str)
  604. {
  605. this.el.find('div.bstart_err').html(str);
  606. }
  607. set_err_msg_finish(str)
  608. {
  609. this.el.find('div.bfinish_err').html(str);
  610. }
  611. set_err_msg_rate(str)
  612. {
  613. this.el.find('div.brate_err').html(str);
  614. }
  615. set_err_msg_save(str)
  616. {
  617. this.el.find('div.bsave_err').html(str);
  618. }
  619. set_err_msg_tos(str)
  620. {
  621. this.el.find('div.btos_err').html(str);
  622. }
  623. mark_tos_valid(){
  624. this.el.find('div.btos select').removeClass('invalid');
  625. }
  626. mark_tos_invalid(){
  627. this.el.find('div.btos select').addClass('invalid');
  628. }
  629. mark_start_valid(){
  630. this.el.find('div.bstart input').removeClass('invalid');
  631. }
  632. mark_start_invalid(){
  633. this.el.find('div.bstart input').addClass('invalid');
  634. }
  635. mark_finish_valid(){
  636. this.el.find('div.bfinish input').removeClass('invalid');
  637. }
  638. mark_finish_invalid(){
  639. this.el.find('div.bfinish input').addClass('invalid');
  640. }
  641. mark_rate_valid(){
  642. this.el.find('div.brate select').removeClass('invalid');
  643. }
  644. mark_rate_invalid(){
  645. this.el.find('div.brate select').addClass('invalid');
  646. }
  647. mark_week_color(){
  648. this.el.find('div.brating').removeClass('week1color');
  649. this.el.find('div.brating').removeClass('week2color');
  650. if (this.is_week1()){
  651. this.el.find('div.brating').addClass('week1color');
  652. }else if (this.is_week2()){
  653. this.el.find('div.brating').addClass('week2color');
  654. }
  655. }
  656. is_week1()
  657. {
  658. var w1_begin = new Date($('span[name="w1d1"]').data().date) ;
  659. var w1_end = new Date($('span[name="w1d7"]').data().date);
  660. w1_begin.setHours(0,0,0,0);
  661. w1_end.setHours(23,59,59);
  662. //w1_end = new Date (w1_end.setDate(w1_end.getDate()+1)); //from 00:00 to 23:59;
  663. var me = new Date(this.data.start);
  664. return (w1_begin <= me && me <= w1_end );
  665. }
  666. is_week2()
  667. {
  668. var w2_begin = new Date($('span[name="w2d1"]').data().date);
  669. var w2_end = new Date($('span[name="w2d7"]').data().date);
  670. w2_begin.setHours(0,0,0,0);
  671. w2_end.setHours(23,59,59);
  672. var me = new Date(this.data.start);
  673. return (w2_begin <= me && me <= w2_end );
  674. }
  675. get_payment_summary(){
  676. var result ={};
  677. result.ot = this.get_is_high_pay();
  678. result.hour = this.get_working_duration();
  679. result.money = this.get_wages();
  680. return result;
  681. }
  682. get_is_high_pay()
  683. {
  684. var rate_info = this.get_rate_info_by_id(this.get_rate());
  685. return this.is_high_pay_hour(rate_info);
  686. }
  687. get_working_duration()
  688. {
  689. //finish - start
  690. var f = new Date(this.get_finish());
  691. var s = new Date(this.get_start());
  692. var diff = f.getTime() - s.getTime();
  693. var hours = Math.floor(diff / 1000 / 60 / 60);
  694. diff -= hours * 1000 * 60 * 60;
  695. var minutes = Math.floor(diff / 1000 / 60);
  696. var minute_to_hour = minutes/60;
  697. return (hours + minute_to_hour);
  698. }
  699. get_wages(){
  700. var hour = this.get_working_duration();
  701. var rate_info = this.get_rate_info_by_id(this.get_rate());
  702. return hour * rate_info.RatePerUnit;
  703. }
  704. get_rate_info_by_id(id){
  705. var rate_info = {};
  706. var rates = bts().earnings_rate;
  707. for(var i =0; i< rates.length; i++){
  708. var r = rates[i];
  709. if(r.EarningsRateID == id){
  710. rate_info = $.extend(true,{}, r);//make a copy
  711. break;
  712. }
  713. }
  714. return rate_info;
  715. }
  716. is_high_pay_hour(rate_info){
  717. var keywords =bts().high_pay_keywords;
  718. var found = false;
  719. keywords.forEach(function(e){
  720. if (-1 != rate_info.Name.toLowerCase().indexOf(e.toLowerCase()) )
  721. found = true;
  722. });
  723. return found;
  724. }
  725. }//end of class Job
  726. //global GUI summary
  727. function get_wages()
  728. {
  729. var txt = $('div.wages div').html();
  730. return parseInt(txt);
  731. }
  732. function set_wages(num){
  733. $('div.wages div').html(num);
  734. }
  735. function set_working_hours(num){
  736. $('input#woh').attr('value', num);
  737. }
  738. function get_working_hours(){
  739. var txt = $('input#woh').attr('value');
  740. return parseFloat(txt);
  741. }
  742. //modal box
  743. function set_modal_title(selector, title){
  744. var s = 'div.bts_'+ selector +' .ult_modal-title';
  745. $(s).html(title);
  746. }
  747. function set_modal_content(selector, content){
  748. var s = 'div.bts_'+ selector +' div.ult_modal-body.ult-html';
  749. $(s).html(content);
  750. }
  751. function open_modal (selector){
  752. var s='div.bts_'+selector+'_button';
  753. $(s).trigger('click');
  754. }
  755. // setTimeout(function(){
  756. // set_modal_title('warning', 'suck title');
  757. // set_modal_content('warning', 'fucking details');
  758. // //open_modal('warning');
  759. // }, 1000);
  760. //
  761. // setTimeout(function(){
  762. // set_modal_title('error', 'error title');
  763. // set_modal_content('error', 'error details');
  764. // //open_modal('error');
  765. // }, 5000);
  766. $(document).on('mouseenter', 'div.week1 div', function(){
  767. $(this).addClass('blink_me');
  768. get_week2_partner(this).addClass('blink_me');
  769. blink_same_date_by_div(this);
  770. });
  771. $(document).on('mouseleave', 'div.week1 div', function(){
  772. $(this).removeClass('blink_me');
  773. get_week2_partner(this).removeClass('blink_me');
  774. unblink_all_date();
  775. });
  776. function get_week2_partner(div){
  777. var index = $(div).index()+1;
  778. return $('div.week2 div:nth-child('+index+')');
  779. }
  780. function init_weekdays(){
  781. var curr = new Date; // get current date
  782. // First day is the day of the month - the day of the week
  783. var first = curr.getDate() - curr.getDay() + 1; //+1 we want Mon as first
  784. var last = first + 6; // last day is the first day + 6
  785. //var firstday = new Date(curr.setDate(first)); //Mon
  786. //var lastday = new Date(curr.setDate(last)); //Sun
  787. var pos = 1; //first lot
  788. for (var i=first; i<=last; i++)
  789. {
  790. var d1 = new Date(curr.setDate(i));
  791. var d2 = new Date(curr.setDate(i+7));
  792. set_day_number(1,pos, d1); //week 1
  793. set_day_number(2,pos, d2); //week 2
  794. pos +=1;
  795. }
  796. }
  797. function set_day_number(week, index, date){
  798. var selector = 'span[name="w'+week+'d'+index+'"]';
  799. $(selector).html(date.getDate());
  800. $(selector).data({date:date});
  801. }
  802. function set_today(){
  803. var selector = 'div.sheettitle span[name="today"]';
  804. var curr = new Date;
  805. $(selector).html(format_date(curr));
  806. }
  807. Date.prototype.get_week_number = function(){
  808. var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
  809. var dayNum = d.getUTCDay() || 7;
  810. d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  811. var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
  812. return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
  813. };
  814. function set_week_number(){
  815. var date = $('span[name="w1d1"]').data().date;
  816. //console.log("date %o", date);
  817. var num = date.get_week_number();
  818. $('div.weekly span[name="week1"]').html(num);
  819. $('div.weekly span[name="week2"]').html(num+1);
  820. }
  821. function number_of_unsaved_job(){
  822. var count =0;
  823. var total_job = $('div.bsave').length -1;//remove table header
  824. var total_saved = $('div.bsave.saved').length;
  825. var empty = $('div.emptyrecord').length;
  826. count = total_job - total_saved - empty;
  827. return count;
  828. }
  829. $('div.prevweek.left').click(function(){
  830. if (number_of_unsaved_job() > 0){
  831. if(!confirm("you have unsaved jobs, proceed will lost them"))
  832. return;
  833. }
  834. $('div.weekdays span.weekday').each(function(i, e){
  835. var date = $(e).data().date;
  836. var newdate = new Date(date.setDate(date.getDate() -7 ));
  837. $(e).html(newdate.getDate());
  838. $(e).data({data:newdate});
  839. });
  840. set_week_number();
  841. load_timesheet();
  842. });
  843. $('div.nextweek.right').click(function(){
  844. if (number_of_unsaved_job() > 0){
  845. if(!confirm("you have unsaved jobs,proceed will lost them"))
  846. return;
  847. }
  848. $('div.weekdays span.weekday').each(function(i, e){
  849. var date = $(e).data().date;
  850. var newdate = new Date(date.setDate(date.getDate() +7 ));
  851. $(e).html(newdate.getDate());
  852. $(e).data({data:newdate});
  853. });
  854. set_week_number();
  855. load_timesheet();
  856. });
  857. $('div.weekly div.weekname.prev').click(function(){
  858. if (!confirm ('copy entire week to next week? '))
  859. return;
  860. var jobs = [];
  861. var job_els =[];
  862. $('div.week1 >div').each(function(i,e){
  863. var date = new Date($(e).find('span.weekday').data().date);
  864. var strDate = format_date(date); //yyyy-mm-dd
  865. $('div.bstart input').each(function(i,e){
  866. var value = $(e).attr('value');
  867. if( -1 != value.indexOf(strDate) ) //found
  868. {
  869. var el = $(e).closest('div.divTable');
  870. if (el.is(":visible")){
  871. var j = el.data().job;
  872. var newj = clone_data_create_new_job(j.get_record_from_ui(),7);//add 7 days
  873. job_els.push(newj.el);
  874. }
  875. }
  876. });
  877. });
  878. show_jobs(job_els);
  879. debounced_calculate();
  880. });
  881. $('div.weekly div.weekname.next').click(function(){
  882. alert('you can only copy from past to future (left to right)');
  883. });
  884. $('div.week1 > div').click(function(e){
  885. e.stopPropagation();
  886. if ($('div.bstart input.blink_me').length == 0){
  887. alert("nothing to copy");
  888. return;
  889. }
  890. if (!confirm ('copy to next week'))
  891. return;
  892. var jobs_el = [];
  893. $('div.bstart input.blink_me').each(function(i,e){
  894. var r = copy_single_day_to_next_week(e);
  895. if (r != false)
  896. jobs_el.push(r.el);
  897. });
  898. show_jobs(jobs_el);
  899. unblink_all_date();
  900. });
  901. $('div.week1,div.week2').click(function(e){
  902. e.stopPropagation();
  903. $(this).toggleClass('filtered');
  904. do_filter_workspace();
  905. });
  906. function copy_single_day_to_next_week(el){
  907. var tb = $(el).closest('div.divTable');
  908. if (tb.is(':visible')){
  909. var j = $(tb).data().job;
  910. var newj = clone_data_create_new_job(j.get_record_from_ui() , 7); // +7 days
  911. return newj;
  912. }
  913. return false;
  914. }
  915. function clone_data_create_new_job(val, num_of_shifted_days){
  916. var data = $.extend(true, {}, val);//make a copy
  917. num_of_shifted_days = typeof num_of_shifted_days !=='undefined'? num_of_shifted_days: 0;// 0 days
  918. //reset
  919. data.id='';
  920. data.ack = 0;
  921. data.rating = 0;
  922. if (is_valid_date_str(data.start)){
  923. var s = new Date(data.start);
  924. var s1 = s.getDate() + num_of_shifted_days;
  925. s = new Date(s.setDate(s1));
  926. data.start = format_date_time(s);
  927. }
  928. if (is_valid_date_str(data.finish)){
  929. var f = new Date(data.finish);
  930. var f1 = f.getDate() + num_of_shifted_days;
  931. f = new Date(f.setDate(f1));
  932. data.finish = format_date_time(f);
  933. }
  934. var newj = new Job(data);
  935. return newj;
  936. }
  937. function is_valid_date_str(val){
  938. var d = new Date(val);
  939. if (d.toString()== 'Invalid Date')
  940. return false;
  941. return true;
  942. }
  943. function blink_same_date_by_div(div){
  944. var date = new Date($(div).find('span.weekday').data().date);
  945. blink_same_date(date);
  946. }
  947. function blink_same_date(date){
  948. var strDate = format_date(date); //yyyy-mm-dd
  949. var els=[];
  950. unblink_all_date();
  951. $('div.bstart input').each(function(i,e){
  952. var value = $(e).attr('value');
  953. if( -1 != value.indexOf(strDate) ) //found
  954. {
  955. els.push(e);
  956. $(e).addClass('blink_me');
  957. }
  958. });
  959. }
  960. function unblink_all_date(){
  961. $('div.bstart input').removeClass('blink_me');
  962. }
  963. $('div.sheettitle h1').click(function(){
  964. reset_title_to_today();
  965. load_timesheet();
  966. });
  967. function reset_title_to_today(){
  968. set_today();
  969. init_weekdays();
  970. set_week_number();
  971. }
  972. function load_timesheet()
  973. {
  974. clear_workspace();
  975. var first = $('span[name="w1d1"]').data().date;
  976. var last = $('span[name="w2d7"]').data().date;
  977. $.post(bts().ajax_url, { // POST request
  978. _ajax_nonce: bts().nonce, // nonce
  979. action: "list_job", // action
  980. start: format_date(first),
  981. finish: format_date(last),
  982. }, function(response, status, xhr){
  983. if (response.status =='success'){
  984. var job_els = [];
  985. response.jobs.forEach(function(job){
  986. //console.log('loading job... %o', job);
  987. var o = new Job(job);
  988. job_els.push(o.el);
  989. });
  990. show_jobs(job_els, 'in-ajax=true');
  991. //filter it if reqired
  992. debounced_filter_workspace();
  993. }else{
  994. alert('error loading job');
  995. }
  996. hide_loading_jobs();
  997. });
  998. }
  999. function show_jobs(job_els, in_ajax){
  1000. if (job_els.length >0){
  1001. $('div.workspace').append(job_els);
  1002. job_els[0].get(0).scrollIntoView();
  1003. console.log('loading ... %d jobs', job_els.length);
  1004. }
  1005. if (typeof in_ajax =='undefined')
  1006. dtp_init();
  1007. }
  1008. function format_date(date){
  1009. var dd = date.getDate();
  1010. var mm = date.getMonth() + 1; //January is 0!
  1011. var yyyy = date.getFullYear();
  1012. if (dd < 10) {
  1013. dd = '0' + dd;
  1014. }
  1015. if (mm < 10) {
  1016. mm = '0' + mm;
  1017. }
  1018. return yyyy + '-' + mm + '-' +dd ;
  1019. }
  1020. function format_date_time(date){
  1021. var strdate = format_date(date);
  1022. var hh = date.getHours();
  1023. if (hh<10){
  1024. hh= '0' + hh;
  1025. }
  1026. var mm = date.getMinutes();
  1027. if (mm<10){
  1028. mm='0' + mm;
  1029. }
  1030. return strdate + ' ' + hh + ":" + mm;
  1031. }
  1032. function clear_workspace()//clear all timesheet jobs
  1033. {
  1034. $('div.workspace > div.divTable').remove();
  1035. //clear datetime picker
  1036. $('div.xdsoft_datetimepicker').remove();
  1037. //
  1038. show_loading_jobs();
  1039. }
  1040. $('button[name="confirmschedule"]').click(function(){
  1041. //$('div.workspace span.ticon.ticon-save').trigger('click');
  1042. });
  1043. var debounced_filter_workspace = debounce(do_filter_workspace, 1000);
  1044. $(document).on('click','div.userlist', debounced_filter_workspace);
  1045. function do_filter_workspace(){
  1046. var staffs =[];
  1047. $('div.stafflist div.peopleitem :checked').each(function(i, e){
  1048. if ($(e).parent().is(':visible')){
  1049. var id = $(e).parent().attr('data-id');
  1050. //console.log("%o, id=%s", e, id);
  1051. staffs.push(id.substring(1));
  1052. }
  1053. });
  1054. var clients =[];
  1055. $('div.clientlist div.peopleitem :checked').each(function(i, e){
  1056. if ($(e).parent().is(':visible')){
  1057. var id = $(e).parent().attr('data-id');
  1058. //console.log("%o, id=%s", e, id);
  1059. clients.push(id.substring(1));
  1060. }
  1061. });
  1062. filter_workspace(staffs, clients);
  1063. filter_workspace_by_weeks();
  1064. debounced_calculate();
  1065. }
  1066. function filter_workspace(staffs, clients){
  1067. //if both array is empty
  1068. if( (staffs === undefined || staffs.length ==0) &&
  1069. (clients===undefined || clients.length ==0)){
  1070. //show all
  1071. $('div.workspace div.divTable').show();
  1072. return;
  1073. }
  1074. //filter some of them;
  1075. $('div.workspace div.divTable').each(function(i,e){
  1076. var job = $(e).data().job;
  1077. var s = job.get_staff();
  1078. var c = job.get_client();
  1079. if (staffs.indexOf(s) ==-1 && clients.indexOf(c) ==-1)
  1080. $(this).fadeOut();
  1081. else
  1082. $(this).fadeIn();
  1083. });
  1084. }
  1085. function filter_workspace_by_weeks(){
  1086. var hide_week1 = $('div.week1').hasClass('filtered');
  1087. var hide_week2 = $('div.week2').hasClass('filtered');
  1088. if (hide_week1 && hide_week2 ){
  1089. alert("You are hiding both weeks");
  1090. }
  1091. $('div.workspace div.divTable').each(function(i,e){
  1092. var job = $(e).data().job;
  1093. if ((hide_week1 && job.is_week1()) ||
  1094. (hide_week2 && job.is_week2()) ){
  1095. $(e).fadeOut();
  1096. }
  1097. });
  1098. }
  1099. var debounced_calculate = debounce(calculate_total_hour_and_money, 2000);
  1100. function calculate_total_hour_and_money()
  1101. {
  1102. //init pays for all staff;
  1103. var pays={
  1104. total: 0,
  1105. hours: 0,
  1106. };
  1107. $('.stafflist > div.peopleitem').each(function(i,e){
  1108. var people = $(this).data().obj;
  1109. people.reset_summary();
  1110. });
  1111. $('div.workspace > .divTable').each(function(i,e){
  1112. if (! $(e).is(':visible'))
  1113. return;
  1114. var job = $(e).data().job; //class Job
  1115. if (typeof job === 'undefined')
  1116. return;
  1117. var ps = job.get_payment_summary();
  1118. pays.total += ps.money;
  1119. pays.hours += ps.hour;
  1120. var staff = job.get_staff();
  1121. var people = find_staff(staff); //class People
  1122. if (people !=false)
  1123. people.add_payment_summary(ps);
  1124. });
  1125. set_wages(pays.total.toFixed(2));
  1126. set_working_hours(pays.hours.toFixed(2));
  1127. }
  1128. function find_staff(login)
  1129. {
  1130. var d = $('#p'+login).data();
  1131. if (typeof d === 'undefined')
  1132. return false;
  1133. return $('#p'+login).data().obj;
  1134. }
  1135. $(document).on('change', '.divTableRow select, .divTableRow input', function() {
  1136. var job = $(this).closest('.divTable').data().job;
  1137. job.validate();
  1138. job.mark_dirty();
  1139. debounced_calculate();
  1140. });
  1141. function init_ts(){
  1142. show_loading_jobs();
  1143. list_staff();
  1144. list_clients();
  1145. xero(false);
  1146. wifi(false);
  1147. init_user_search();
  1148. //ajax_earning_rate();
  1149. reset_title_to_today();
  1150. load_timesheet();
  1151. }
  1152. // function ajax_earning_rate(){
  1153. // $.post(bts().ajax_url, { // POST request
  1154. // _ajax_nonce: bts().nonce, // nonce
  1155. // action: "earnings_rate", // action
  1156. // }, function(response, status, xhr){
  1157. // bts().earnings_rate = response;
  1158. // console.log("%o", bts().earnings_rate);
  1159. // });
  1160. // }
  1161. init_ts();
  1162. /*________________________________________________________________________*/
  1163. });
  1164. })(jQuery);
  1165. /*______________scrolling______________________________________________*/
  1166. jQuery(document).ready(function(){
  1167. var timeoutid =0;
  1168. jQuery('button.peoplelist[name="down"]').mousedown(function(){
  1169. var button = this;
  1170. timeoutid = setInterval(function(){
  1171. //console.log("down scrotop %d ", jQuery(button).parent().find(".userlist").get(0).scrollTop );
  1172. jQuery(button).parent().find(".userlist").get(0).scrollTop +=240;
  1173. }, 100);
  1174. }).on('mouseup mouseleave', function(){
  1175. clearTimeout(timeoutid);
  1176. });
  1177. jQuery('button.peoplelist[name="up"]').mousedown(function(){
  1178. var button = this;
  1179. timeoutid = setInterval(function(){
  1180. //console.log("up scrotop %d ", jQuery(button).parent().find(".userlist").get(0).scrollTop );
  1181. jQuery(button).parent().find(".userlist").get(0).scrollTop -=240;
  1182. }, 100);
  1183. }).on('mouseup mouseleave', function(){
  1184. clearTimeout(timeoutid);
  1185. });
  1186. });