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

1214 lines
33KB

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