timesheet source code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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