timesheet source code
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1294 lines
35KB

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