timesheet source code
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

2437 lines
68KB

  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_km(km)
  61. {
  62. var str = "petrol:" + km.toFixed(2) + " km";
  63. $(this.selector + ' div[name="petrol"]').html(str);
  64. }
  65. set_unconfirmed_job(num){
  66. if( num == 0 )
  67. $(this.selector + " span[name='badge']").hide();
  68. else
  69. $(this.selector + " span[name='badge']").show();
  70. this.data.unconfirmedjob = num;
  71. }
  72. reset_summary() {
  73. this.summary = {
  74. wages : 0,
  75. normal_hour : 0,
  76. ot_hour : 0,
  77. petrol : 0,
  78. };
  79. this.update_summary_in_gui();
  80. }
  81. add_payment_summary(ps)
  82. {
  83. //{ot: false, hour: "2.67", money: "76.90"}
  84. this.summary.wages += ps.money;
  85. if (! ps.ot )
  86. this.summary.normal_hour += ps.hour;
  87. else
  88. this.summary.ot_hour += ps.hour;
  89. this.update_summary_in_gui();
  90. }
  91. update_summary_in_gui()
  92. {
  93. var msg = '$' + this.summary.wages.toFixed(2);
  94. $(this.selector).find('div[name="wages"]').html(msg);
  95. msg = this.summary.normal_hour.toFixed(2) + '+' +this.summary.ot_hour.toFixed(2) + 'hr';
  96. $(this.selector).find('div[name="hours"]').html(msg);
  97. msg = 'petrol:' + this.summary.petrol.toFixed(2) + 'km';
  98. $(this.selector).find('div[name="petrol"]').html(msg);
  99. }
  100. }//end of class People
  101. function bts_staff_html(data){
  102. var template = $('#staff_item').html();
  103. var head = '<div class="peopleitem" id="p'+ data.login +'">';
  104. r = head + '</div>' ;
  105. return r;
  106. }
  107. function bts_client_html(data){
  108. var template = $('#client_item').html();
  109. var head = '<div class="peopleitem" id="p'+ data.login +'">';
  110. r = head + '</div>' ;
  111. return r;
  112. }
  113. function sample_staff(){
  114. for (var i=1; i<100; i++){
  115. var sample_people = {
  116. login: '01515b52-6936-46b2-a000-9ad4cd7a5b50' +i,
  117. firstname: "first"+i,
  118. lastname: "last",
  119. mobile: '041122221' +i,
  120. email: 'abc@gmail.com' + i,
  121. wages: 0,
  122. hour: i,
  123. OT: 3,
  124. petrol: 50 +i,
  125. rating: Math.floor(Math.random() * Math.floor(5)),
  126. unconfirmedjob: Math.floor(Math.random() * Math.floor(30)),
  127. };
  128. var html = bts_staff_html(sample_people);
  129. jQuery('div.stafflist').append(html);
  130. new People("#p" + sample_people.login, sample_people);
  131. }
  132. }
  133. function list_staff() {
  134. show_loading_staff();
  135. $('div.stafflist div.peopleitem').remove();
  136. $.post(bts().ajax_url, { // POST request
  137. _ajax_nonce: bts().nonce, // nonce
  138. action: "list_staff", // action
  139. }).done(function(response, status, xhr){
  140. if (response.status =='success'){
  141. bts().staff = response.users;
  142. bts().staff_map = {};
  143. bts().staff_people= {};
  144. response.users.forEach(function(u){
  145. bts().staff_map[u.login] = u;
  146. var html = bts_staff_html(u);
  147. jQuery('div.stafflist').append(html);
  148. var staff_obj = new People("#p" + u.login,'#staff_item', u);
  149. bts().staff_people[u.login] = staff_obj;
  150. });
  151. hide_loading_staff();
  152. }else{
  153. alert('error getting staff list');
  154. }
  155. });
  156. }
  157. function list_clients() {
  158. show_loading_client();
  159. $('div.clientlist div.peopleitem').remove(); //clear it
  160. $.post(bts().ajax_url, { // POST request
  161. _ajax_nonce: bts().nonce, // nonce
  162. action: "list_client", // action
  163. }, function(response, status, xhr){
  164. if (response.status =='success'){
  165. bts().client = response.users;
  166. bts().client_map = {};
  167. response.users.forEach(function(u){
  168. bts().client_map[u.login] = u;
  169. hide_loading_client();
  170. var html = bts_client_html(u);
  171. jQuery('div.clientlist').append(html);
  172. new People("#p" + u.login, '#client_item' ,u);
  173. });
  174. }else{
  175. alert('error getting Client list');
  176. }
  177. });
  178. }
  179. function list_tos() {
  180. wifi(true);
  181. $.post(bts().ajax_url, { // POST request
  182. _ajax_nonce: bts().nonce, // nonce
  183. action: "list_tos", // action
  184. }, function(response, status, xhr){
  185. if (response.status =='success'){
  186. bts().tos = response.tos;
  187. wifi(false);
  188. }else{
  189. alert('error getting Type of Service list');
  190. }
  191. });
  192. }
  193. function show_loading_staff(){
  194. jQuery('div.stafflist img').attr('src', bts().load_user_img).show();
  195. }
  196. function show_loading_client(){
  197. jQuery('div.clientlist img').attr('src', bts().load_user_img).show();
  198. }
  199. function hide_loading_staff(){
  200. jQuery('div.stafflist img').hide();
  201. }
  202. function hide_loading_client(){
  203. jQuery('div.clientlist img').hide();
  204. }
  205. function show_loading_jobs(){
  206. jQuery('div.workspace img').attr('src', bts().load_job_img).show();
  207. }
  208. function hide_loading_jobs(){
  209. jQuery('div.workspace img').hide();
  210. }
  211. function xero(t){
  212. if (t)
  213. $('div.xero i').show();
  214. else
  215. $('div.xero i').hide();
  216. }
  217. function wifi(t){
  218. if (t)
  219. $('div.wifi i').show();
  220. else
  221. $('div.wifi i').hide();
  222. }
  223. function csv(t){
  224. if (t)
  225. $('div.csv i').show();
  226. else
  227. $('div.csv i').hide();
  228. }
  229. function init_user_search(){
  230. $('div.b_search input').keyup(debounce(function(e){
  231. filter_user(e.target);
  232. }, 500));
  233. }
  234. function filter_user(input){
  235. var value = $(input).val();
  236. value = value.toLowerCase();
  237. var selector = get_selector_for_filter_people(input);
  238. $.each( $(selector).find('div.peopleitem'), function(index, e){
  239. //uncheck everyone
  240. $(e).find('input[type="checkbox"]').prop('checked', false);
  241. var html = $(e).find('div[name="title"] a').html();
  242. html = html.toLowerCase();
  243. if (-1 != html.indexOf(value)){//we find it;
  244. $(e).show();
  245. }else{
  246. $(e).hide();
  247. }
  248. });
  249. }
  250. function get_selector_for_filter_people(input){
  251. var selector='';
  252. var role = $(input).attr('placeholder');
  253. if (role == 'staff') //we filter staff
  254. selector = 'div.stafflist';
  255. else if (role = 'client')
  256. selector = 'div.clientlist';
  257. return selector;
  258. }
  259. $(document).on('click', 'div.jobTable div.brate.error', function(){
  260. var msg = $(this).attr('title');
  261. if (msg != "")
  262. alert(msg);
  263. });
  264. $(document).on('click', 'div.workspace div.bedit span.ticon-edit', function(){
  265. var el = $(this).closest('div.jobTable');
  266. var newjob_id = el.attr('data-newjob_id');
  267. if (typeof newjob_id != 'undefined' && newjob_id != ''){
  268. do_edit_new_job(newjob_id);
  269. }else{
  270. var id = el.attr('data-id');
  271. do_edit_job(id);
  272. }
  273. });
  274. function get_workspace_start_date(){
  275. return new Date($('span[name="w1d1"]').data().date) ;
  276. }
  277. function get_payroll_start()
  278. {
  279. var ret = new Date(bts().pay_calendar.start + " 00:00:00");
  280. return ret;
  281. }
  282. function allow_editing(date){
  283. var begin = new Date(date);
  284. var pay_begin = get_payroll_start();
  285. var seconds = (begin.getTime() - pay_begin.getTime())/1000;
  286. return seconds > -10;
  287. }
  288. // $(document).on('click', 'div.bts_editor div.ult-overlay-close', function(){
  289. // $('.Editing').addClass('blink_me');
  290. // setTimeout(function(){
  291. // $(".Editing").removeClass('Editing blink_me');
  292. // }, 1000);
  293. //
  294. // });
  295. $(document).on('click', 'div.bts_editor div.ult-overlay-close', function(){
  296. var el = $('.Editing');
  297. el.addClass("blink_me").removeClass('Editing');
  298. setTimeout(function(){
  299. el.removeClass('blink_me');
  300. }, 600);
  301. });
  302. function close_editor(){
  303. $('div.bts_editor div.ult-overlay-close').trigger('click');
  304. }
  305. $(document).on('jobEditor:close', 'div.divTable.Editor', function(e,data){
  306. var editor = data.editor;
  307. var job = data.job;
  308. //console.log('close_editor event %o, %o', editor, job);
  309. editor.off_event_handler();//remove all events handler;
  310. var templ = $("#jobv1_item").html();
  311. var html = Mustache.render(templ, {jobs:job}); //job id should be available;
  312. if ( $('div.jobTable.Editing').length == 0){
  313. $('div.workspace').append(html);
  314. $('#job_'+job.id).get(0).scrollIntoView();
  315. }else{
  316. //create new job underneath it
  317. var templ = $("#jobv1_item").html();
  318. var html = Mustache.render(templ, {jobs:job}); //job id should be available;
  319. $('div.jobTable.Editing').after(html).remove();
  320. }
  321. var el = $('#job_' + job.id).addClass("blink_me");
  322. setTimeout(function(){
  323. el.removeClass('blink_me');
  324. }, 1500);
  325. debounced_calculate();
  326. });
  327. $(document).on('click', 'div.divTableHead.bdelete span.ticon-trash', function(){
  328. check_duplicate();
  329. setTimeout(do_delete_duplicate, 200);//200ms make GUI refresh
  330. });
  331. function fade_and_delete(el)
  332. {
  333. $(el).fadeOut(300);
  334. setTimeout(function(){
  335. $(el).remove();
  336. },300);
  337. }
  338. function add_new_empty_job(job){
  339. var title = "";
  340. if (typeof job == 'undefined' || ! (job instanceof Job) ){
  341. job = new Job({empty:true});
  342. job.is_new = true;
  343. title = "Create New Job ";
  344. }else if (job instanceof Job){
  345. title = "Create new Job by Copy Existing one";
  346. }
  347. job.editorid = Math.floor(Math.random() * Math.floor(99999)); // a random number;
  348. //show editor
  349. var html = $('#jobv1_editor').html();
  350. html = Mustache.render(html, job);
  351. set_modal_content('editor', html);
  352. //update GUI
  353. open_modal('editor');
  354. set_modal_title('editor', title);
  355. dtp_init();
  356. //init editor
  357. var e = new JobEditor('#editor_' + job.editorid, job);
  358. console.log("%o is instance of JobEditor %o", e, e instanceof JobEditor);
  359. }
  360. $(document).on('click', 'div[name="copyschedule"]', function(e){
  361. e.stopPropagation();
  362. add_new_empty_job();
  363. });
  364. function remove_job_from_gui(el)
  365. {
  366. el = $(el);
  367. var newjob_id = el.data().newjob_id;
  368. var id = el.data().id;
  369. if (typeof newjob_id != 'undefined' && newjob_id !=''){
  370. delete bts().job_map_new[newjob_id];
  371. }else if (typeof id != 'undefined' && id != ''){
  372. delete bts().job_map[id];
  373. }
  374. el.addClass('blink_me');
  375. el.fadeOut(500);
  376. setTimeout(function(){
  377. el.remove();
  378. debounced_calculate();
  379. }, 500);
  380. }
  381. $(document).on('click', 'div.divTableCell.bdelete', function(){
  382. var el = $(this).closest('div.jobTable');
  383. var data = el.data();
  384. if (typeof data.id =='undefined' || data.id == ''){//not saved
  385. remove_job_from_gui(el);//remove direclty
  386. }else{
  387. var id = data.id;
  388. if (confirm('delete this job?')){
  389. $.post(bts().ajax_url, { // POST request
  390. _ajax_nonce: bts().nonce, // nonce
  391. action: "delete_job", // action
  392. jobid: id,
  393. }, function(response, status, xhr){
  394. if (response.status=='success'){
  395. remove_job_from_gui(el);
  396. }else{
  397. alert( 'error deleting job, please check your network');
  398. }
  399. });
  400. }
  401. }
  402. });
  403. $(document).on('mouseenter', 'div.divTableCell', function(){
  404. $(this).closest('div.divTable').addClass('highlight');
  405. });
  406. $(document).on('mouseleave', 'div.divTableCell', function(){
  407. $(this).closest('div.divTable').removeClass('highlight');
  408. });
  409. $(document).on('click', 'div.workspace span.ticon.ticon-save', function(){
  410. var table = $(this).closest('div.jobTable');
  411. var data = table.data();
  412. if (data.id == "" && data.newjob_id != "" && data.newjob_id.substring(0,4) == "new_" ){
  413. job = bts().job_map_new[data.newjob_id];
  414. console.assert(typeof job != 'undefined');
  415. do_save_new_job(job.get_record(), table);
  416. return;
  417. }
  418. alert("Error occured");
  419. $(this).fadeOut();
  420. });
  421. $(document).on('click', '.divTableHeading span.ticon.ticon-save', function(){
  422. //save all
  423. $('div.workspace span.ticon.ticon-save').each(function (i,e){
  424. if ($(this).is(":visible"))
  425. $(this).trigger('click');
  426. });
  427. });
  428. $(document).on('click', 'span.ticon.ticon-copy', function(){
  429. var table = $(this).closest('div.jobTable');
  430. var record = bts().job_map[table.data().id].get_record();
  431. //create new job;
  432. var newj = clone_data_create_new_job(record);
  433. add_new_empty_job(newj);
  434. });
  435. function do_save_new_job(job_tobe_saved, table){
  436. $.post(bts().ajax_url, { // POST request
  437. _ajax_nonce: bts().nonce, // nonce
  438. action: "save_job", // action
  439. record: job_tobe_saved,
  440. }, function(response, status, xhr){
  441. if (response.status=='success'){
  442. var job = new Job(response.newdata);
  443. job.saved = true;
  444. job.is_new = response.isNew;
  445. bts().job_map[job.id] = job;
  446. //delete that old job and display the new one
  447. var jobs=[job];
  448. var html = Mustache.render($('#jobv1_item').html(), {jobs:jobs});
  449. delete bts().job_map_new[table.data().newjob_id];
  450. table.after(html);
  451. table.remove();
  452. }else{
  453. console.error("error saving job %o, response=%o", job_tobe_saved, response);
  454. alert( 'error saving data, please check your network');
  455. }
  456. });
  457. }
  458. function mark_highlight_me(el, ms){
  459. el.addClass('blink_me');
  460. el.addClass('highlight');
  461. el.addClass('newcopy');
  462. setTimeout(function(){
  463. el.removeClass('blink_me');
  464. el.removeClass('highlight');
  465. el.removeClass('newcopy');
  466. },ms);
  467. }
  468. class Job{
  469. constructor(record)
  470. {
  471. this.original_attr = Object.keys(record);
  472. $.extend(this, record);
  473. this.derive_attr();
  474. }
  475. get_record()
  476. {//without extended attributes;
  477. var self = this;
  478. var r = {};
  479. this.original_attr.forEach(function(attr){
  480. r[attr] = self[attr];
  481. });
  482. return r;
  483. }
  484. derive_attr()
  485. {
  486. this.tos_name(this);
  487. this.staff_name(this);
  488. this.client_name(this);
  489. this.rate_name(this);
  490. this.rating_range(this);
  491. this.identify_job_week(this);
  492. this.job_acked(this);
  493. this.job_disabled(this);
  494. }
  495. tos_name(e){
  496. if (typeof bts().tos[e.tos] != 'undefined'){
  497. e.tos_name = bts().tos[e.tos].tos_full_str;
  498. }else{
  499. e.tos_name = "(deleted) ";
  500. e.tos_err="Missing: " + e.tos;
  501. }
  502. }
  503. staff_name(e){
  504. if (typeof bts().staff_map[e.staff] != 'undefined'){
  505. e.staff_name = bts().staff_map[e.staff].display_name;
  506. }else{
  507. e.staff_name = "(deleted) ";
  508. e.staff_err="Missing: " + e.staff;
  509. }
  510. }
  511. client_name(e){
  512. if (typeof bts().client_map[e.client] != 'undefined'){
  513. e.client_name = bts().client_map[e.client].display_name;
  514. }else{
  515. e.client_name ="(deleted)";
  516. e.client_err ="Missing: " + e.client;
  517. }
  518. }
  519. rate_name(e){
  520. if (typeof bts().earnings_rate[e.rate] != 'undefined') {
  521. e.rate_name = bts().earnings_rate[e.rate].RatePerUnit + "-" + bts().earnings_rate[e.rate].Name;
  522. if (! has_txt_hour( bts().earnings_rate[e.rate].TypeOfUnits )){
  523. e.rate_err = `Rate unit must be ⟦ Hours ⟧
  524. Possible solution:
  525. 1. Change it in Xero
  526. 2. Delete this job`;
  527. }
  528. }else{
  529. e.rate_name = "(deleted)";
  530. e.rate_err = "Missing: " + e.rate;
  531. }
  532. }
  533. rating_range(e){
  534. if (e.rating <0 || e.rating >5){
  535. e.rating_err = "Rating 0-5 Only";
  536. }
  537. }
  538. identify_job_week(e){
  539. if (job_is_week1(e.start)){
  540. e.is_week1=true;
  541. }else if (job_is_week2(e.start)){
  542. e.is_week2=true;
  543. }
  544. }
  545. job_acked(e){
  546. if (e.ack != 0){
  547. e.is_confirmed = true;
  548. }
  549. }
  550. job_disabled(e){
  551. var allow = allow_editing(e.start);
  552. if (!allow)
  553. e.disabled =true;
  554. else
  555. delete e.disabled;
  556. }
  557. is_job_valid(){
  558. var error_found = false;
  559. var self = this;
  560. this.original_attr.forEach(function(attr){
  561. var col = attr + "_err";
  562. if (typeof self[col] == 'undefined')
  563. return;
  564. if (self[attr+"_err"] != "")
  565. error_found = true;
  566. });
  567. return !error_found;
  568. }
  569. is_high_pay()
  570. {
  571. var job = this;
  572. var rate_info = bts().earnings_rate[job.rate];
  573. var keywords =bts().high_pay_keywords;
  574. var found = false;
  575. keywords.forEach(function(e){
  576. if (-1 != rate_info.Name.toLowerCase().indexOf(e.toLowerCase()) )
  577. found = true;
  578. });
  579. return found;
  580. }
  581. get_payment_summary()
  582. {
  583. var job = this;
  584. var result ={};
  585. result.ot = job.is_high_pay();
  586. result.hour = job.get_working_duration();
  587. result.money = job.get_wages();
  588. return result;
  589. }
  590. get_working_duration()
  591. {
  592. var job = this;
  593. //finish - start
  594. var f = new Date(job.finish);
  595. var s = new Date(job.start);
  596. var diff = f.getTime() - s.getTime();
  597. var hours = Math.floor(diff / 1000 / 60 / 60);
  598. diff -= hours * 1000 * 60 * 60;
  599. var minutes = Math.floor(diff / 1000 / 60);
  600. var minute_to_hour = minutes/60;
  601. return (hours + minute_to_hour);
  602. }
  603. get_wages()
  604. {
  605. var job = this;
  606. var hour = job.get_working_duration(job);
  607. var rate_info = bts().earnings_rate[job.rate];
  608. if ( has_txt_hour( bts().earnings_rate[job.rate].TypeOfUnits ) )
  609. {
  610. return hour * rate_info.RatePerUnit;
  611. }else{
  612. return 1 * rate_info.RatePerUnit;
  613. }
  614. }
  615. allow_edit(){
  616. return allow_editing(this.start);
  617. }
  618. };
  619. class JobEditor{ //save data for the record, and display it as GUI
  620. constructor(selector, job){
  621. this.el = $(selector);
  622. this.load_data(job);
  623. console.assert(job instanceof Job);
  624. this.init_event_handler();
  625. }
  626. load_data(data)
  627. {
  628. //save to html element
  629. this.data = data;
  630. this.el.data({job:this, data:data});
  631. //draw GUI
  632. this.clear_err_msg();
  633. this.set_job_id(data.id);
  634. this.set_tos(data.tos);
  635. this.set_start(data.start);
  636. this.set_finish(data.finish);
  637. this.set_rate(data.rate);
  638. this.set_staff(data.staff);
  639. this.set_client(data.client);
  640. this.set_ack(data.ack);
  641. this.set_rating(data.rating);
  642. //draw GUI by other
  643. this.mark_dirty_on_new_record(data);
  644. this.mark_week_color();
  645. //this.validate(); //also triggers mark errors
  646. }
  647. init_event_handler(){
  648. var self = this;
  649. this.el.find("div.btos select").change(function(){
  650. if ( self.validate_tos() ) {
  651. self.data.tos = self.get_tos();
  652. self.set_err_msg_tos('');
  653. }
  654. });
  655. this.el.find("div.bstart input").change(function(){
  656. if (self.validate_start()){
  657. self.data.start = self.get_start();
  658. self.set_err_msg_start('');
  659. self.validate_start_and_finish();
  660. }
  661. });
  662. this.el.find("div.bfinish input").change(function(){
  663. if (self.validate_finish()){
  664. console.log(self);
  665. self.data.finish = self.get_finish();
  666. self.set_err_msg_finish('');
  667. self.validate_start_and_finish();
  668. }
  669. });
  670. this.el.find("div.bstaff select").change(function(){
  671. if (self.validate_staff()){
  672. self.data.staff = self.get_staff();
  673. self.set_err_msg_staff('');
  674. }
  675. });
  676. this.el.find("div.bclient select").change(function(){
  677. if (self.validate_client()){
  678. self.data.client = self.get_client();
  679. self.set_err_msg_client('');
  680. }
  681. });
  682. this.el.find("div.brate select").change(function(){
  683. if (self.validate_rate()){
  684. self.data.rate = self.get_rate();
  685. self.set_err_msg_rate('');
  686. }
  687. });
  688. this.el.find("div.bconfirmed input").change(function(){
  689. if(self.validate_ack()){
  690. self.data.ack = self.get_ack();
  691. }
  692. });
  693. this.el.find("div.brating select").change(function(){
  694. if( self.validate_rating()){
  695. self.data.rating =self.get_rating();
  696. }
  697. });
  698. this.el.find("div.bsave span.ticon-save").click(function(e){
  699. if ( self.validate() ){
  700. self.do_save_record();
  701. }else{
  702. self.set_err_msg_save('Data Error');
  703. }
  704. });
  705. }
  706. off_event_handler(){
  707. this.el.off('change',"div.btos select");
  708. this.el.off('change',"div.bstart input");
  709. this.el.off('change',"div.bfinish input");
  710. this.el.off('change',"div.bstaff select");
  711. this.el.off('change',"div.bclient select");
  712. this.el.off('change',"div.brate select");
  713. this.el.off('change',"div.bconfirmed input");
  714. this.el.off('change',"div.brating select");
  715. this.el.off('change',"div.bsave span.ticon-save");
  716. }
  717. get_job_id(){
  718. return this.el.attr('data-id');
  719. }
  720. set_job_id(val){
  721. if (typeof val == 'undefined' || val == '')
  722. {//remove data-id and id
  723. this.el.removeAttr('data-id');
  724. this.el.removeAttr('id');
  725. }else{
  726. this.el.attr('data-id', val);
  727. this.el.attr('id', 'job_' + val);
  728. }
  729. }
  730. get_tos()
  731. {
  732. return this.el.find('div.btos select').children("option:selected").val();
  733. }
  734. set_tos(val)
  735. {
  736. if (typeof(val) =="undefined")
  737. return;
  738. this.el.find('div.btos select option[value="'+val+'"]').prop('selected',true);
  739. if ( this.get_tos() != val ){
  740. this.set_err_msg_tos("Missing:" + this.data.tos)
  741. var o = new Option("(deleted)", this.data.tos);
  742. this.el.find('div.btos select').prepend(o);
  743. this.el.find('div.btos select option[value="'+this.data.tos+'"]').prop('selected',true);
  744. }
  745. }
  746. get_start(){
  747. return this.el.find('div.bstart input').val();
  748. }
  749. set_start(val)
  750. {
  751. if (typeof(val) =="undefined"){
  752. this.set_err_msg_start("need start");
  753. return;
  754. }
  755. this.el.find('div.bstart input').val(val);
  756. }
  757. get_finish()
  758. {
  759. return this.el.find('div.bfinish input').val();
  760. }
  761. set_finish(val)
  762. {
  763. if (typeof(val) == "undefined"){
  764. this.set_err_msg_finish("need finish");
  765. return;
  766. }
  767. this.el.find('div.bfinish input').val(val);
  768. }
  769. get_rate()
  770. {
  771. return this.el.find('div.brate select').children("option:selected").val();
  772. }
  773. set_rate(val)
  774. {
  775. if (typeof(val) =="undefined")
  776. return;
  777. this.el.find('div.brate select option[value="'+val+'"]').prop('selected',true);
  778. if ( this.get_rate() != val ){
  779. var o = new Option("(deleted)", this.data.rate);
  780. this.el.find('div.brate select').prepend(o);
  781. this.set_err_msg_rate('Missing:' + this.data.rate);
  782. this.el.find('div.brate select option[value="'+this.data.rate+'"]').prop('selected',true);
  783. }
  784. }
  785. get_staff()
  786. {
  787. return this.el.find('div.bstaff select').children("option:selected").val();
  788. }
  789. set_staff(val)
  790. {
  791. if (typeof(val) =="undefined")
  792. return;
  793. this.el.find('div.bstaff select option[value="'+val+'"]').prop('selected',true);
  794. if ( this.get_staff() != val ){
  795. var o = new Option("(deleted)", this.data.staff);
  796. this.el.find('div.bstaff select').prepend(o);
  797. this.set_err_msg_staff('Missing:' + this.data.staff);
  798. this.el.find('div.bstaff select option[value="'+this.data.staff+'"]').prop('selected',true);
  799. }
  800. }
  801. get_client()
  802. {
  803. return this.el.find('div.bclient select').children("option:selected").val();
  804. }
  805. set_client(val)
  806. {
  807. if (typeof(val) =="undefined")
  808. return;
  809. this.el.find('div.bclient select option[value="'+val+'"]').prop('selected',true);
  810. if ( this.get_client() != val ){
  811. var o = new Option("(deleted)", this.data.client);
  812. this.el.find('div.bclient select').prepend(o);
  813. this.set_err_msg_client('Missing:' + this.data.client);
  814. this.el.find('div.bclient select option[value="'+this.data.client+'"]').prop('selected',true);
  815. }
  816. }
  817. get_ack()
  818. {
  819. return this.el.find('div.bconfirmed input:checked').length > 0? 'true':0;
  820. }
  821. set_ack(val)
  822. {
  823. if (typeof(val) =="undefined")
  824. return;
  825. return this.el.find('div.bconfirmed input').prop('checked', val!=0);
  826. }
  827. get_rating(){
  828. return this.el.find('div.brating select').children("option:selected").val();
  829. }
  830. set_rating(num){
  831. if (!(0 <= num && num <=5))
  832. return;
  833. this.el.find('div.brating select option[value="'+num+'"]').prop('selected',true);
  834. }
  835. get_record_from_ui(){
  836. var record = {};
  837. record.id = this.get_job_id();
  838. record.tos = this.get_tos();
  839. record.start = this.get_start();
  840. record.finish = this.get_finish();
  841. record.rate = this.get_rate();
  842. record.staff = this.get_staff();
  843. record.client = this.get_client();
  844. record.ack = this.get_ack();
  845. record.rating = this.get_rating();
  846. return record;
  847. }
  848. do_save_record(){
  849. var self = this;
  850. $.post(bts().ajax_url, { // POST request
  851. _ajax_nonce: bts().nonce, // nonce
  852. action: "save_job", // action
  853. record: self.get_record_from_ui(),
  854. }, function(response, status, xhr){
  855. if (response.status=='success'){
  856. self.load_data(response.newdata);
  857. var job = new Job(response.newdata);
  858. job.saved = true;
  859. job.is_new = response.isNew;
  860. bts().job_map[job.id] = job;
  861. var data = {editor:self, job:job};
  862. self.el.trigger('jobEditor:close', data);
  863. close_editor();
  864. }else{
  865. self.self.set_err_msg_save('Not saved');
  866. alert( 'error saving data, please check your network');
  867. }
  868. });
  869. }
  870. mark_dirty_on_new_record(data){
  871. if (typeof(data.id) === 'undefined' || data.id == ''){
  872. this.mark_dirty();
  873. this.mark_new();
  874. }
  875. else{
  876. this.mark_saved();
  877. }
  878. }
  879. mark_dirty() //need save
  880. {
  881. var d = this.el.find('.bsave');
  882. d.removeClass('saved');
  883. d.addClass('blink_me');
  884. setTimeout(function(){
  885. d.removeClass('blink_me');
  886. d.removeClass('saved');
  887. },1000);
  888. }
  889. mark_saved()
  890. {
  891. var d = this.el.find('.bsave');
  892. d.addClass('blink_me');
  893. setTimeout(function(){
  894. d.removeClass('blink_me');
  895. d.addClass('saved');
  896. },1000);
  897. }
  898. //newly created empty record
  899. mark_new()
  900. {
  901. this.el.addClass('emptyrecord');
  902. }
  903. mark_old()
  904. {
  905. this.el.removeClass('emptyrecord');
  906. }
  907. is_start_valid(){
  908. var s = this.get_start();
  909. return is_valid_date_str(s);
  910. }
  911. is_finish_valid(){
  912. var f = this.get_finish();
  913. if (!is_valid_date_str(f))
  914. return false;
  915. }
  916. is_finish_resonable(){
  917. var f = this.get_finish();
  918. if (!is_valid_date_str(f))
  919. return false;
  920. var s = this.get_start();
  921. s = new Date(s);
  922. f = new Date(f);
  923. return (s < f);
  924. }
  925. validate()
  926. {
  927. var ok_tos = this.validate_tos();
  928. var ok_time = this.validate_start() && this.validate_finish() && this.validate_start_and_finish();
  929. var ok_staff = this.validate_staff();
  930. var ok_client = this.validate_client();
  931. var ok_rate = this.validate_rate() ; //make sure this validate is executed
  932. var ok = ok_tos && ok_time && ok_staff && ok_client && ok_rate;
  933. if (ok){
  934. this.el.removeClass('invalidjob');
  935. }else{
  936. this.el.addClass('invalidjob');
  937. }
  938. return ok;
  939. }
  940. validate_start(){
  941. var str = this.get_start();
  942. if (str == ""){
  943. this.set_err_msg_start('need start');
  944. return false;
  945. }
  946. if (!is_valid_date_str(str) ){
  947. this.mark_start_invalid();
  948. this.set_err_msg_start('wrong date');
  949. return false;
  950. }
  951. return true;
  952. }
  953. validate_finish()
  954. {
  955. var str = this.get_finish();
  956. if (str == ""){
  957. this.set_err_msg_finish('need finish');
  958. return false;
  959. }
  960. if (! is_valid_date_str(str)){
  961. this.set_err_msg_finish('wrong date');
  962. this.mark_finish_invalid();
  963. return false;
  964. }
  965. return true;
  966. }
  967. validate_start_and_finish()
  968. {
  969. if (! this.validate_start() || ! this.validate_finish())
  970. return;
  971. if (!this.is_finish_resonable()){
  972. this.set_err_msg_finish("older than start");
  973. this.set_err_msg_start("after finish");
  974. this.mark_start_invalid();
  975. this.mark_finish_invalid();
  976. return false;
  977. }else{
  978. this.mark_start_valid();
  979. this.mark_finish_valid();
  980. this.set_err_msg_finish("");
  981. this.set_err_msg_start("");
  982. return true;
  983. }
  984. }
  985. validate_rate()
  986. {
  987. var rate_info = this.get_rate_info_by_id(this.get_rate());
  988. if ( rate_info.RatePerUnit <= 0){
  989. this.set_err_msg_rate('bad rate');
  990. this.mark_rate_invalid();
  991. return false;
  992. }
  993. this.set_err_msg_rate('');
  994. this.mark_rate_valid();
  995. return true;
  996. }
  997. validate_tos(){
  998. if ( typeof bts().tos[this.get_tos()] == 'undefined') {
  999. this.set_err_msg_tos('missing ' + this.get_tos());
  1000. return false;
  1001. }else{
  1002. this.set_err_msg_tos('');
  1003. return true;
  1004. }
  1005. }
  1006. validate_staff(){
  1007. if ( typeof bts().staff_map[this.get_staff()] == 'undefined') {
  1008. this.set_err_msg_staff('missing ' + this.get_staff());
  1009. return false;
  1010. }else{
  1011. this.set_err_msg_staff('');
  1012. return true;
  1013. }
  1014. }
  1015. validate_client(){
  1016. if ( typeof bts().client_map[this.get_client()] == 'undefined') {
  1017. this.set_err_msg_client('missing ' + this.get_client());
  1018. return false;
  1019. }else{
  1020. this.set_err_msg_client('');
  1021. return true;
  1022. }
  1023. }
  1024. validate_rating(){
  1025. return;
  1026. }
  1027. clear_err_msg(){
  1028. this.el.find('.divTableRow.errmsg > div').html('');
  1029. }
  1030. set_err_msg_start(str)
  1031. {
  1032. this.el.find('div.bstart_err').html(str);
  1033. }
  1034. set_err_msg_finish(str)
  1035. {
  1036. this.el.find('div.bfinish_err').html(str);
  1037. }
  1038. set_err_msg_staff(str)
  1039. {
  1040. this.el.find('div.bstaff_err').html(str);
  1041. }
  1042. set_err_msg_client(str)
  1043. {
  1044. this.el.find('div.bclient_err').html(str);
  1045. }
  1046. set_err_msg_rate(str)
  1047. {
  1048. this.el.find('div.brate_err').html(str);
  1049. }
  1050. set_err_msg_save(str)
  1051. {
  1052. this.el.find('div.bsave_err').html(str);
  1053. }
  1054. set_err_msg_tos(str)
  1055. {
  1056. this.el.find('div.btos_err').html(str);
  1057. }
  1058. mark_tos_valid(){
  1059. this.el.find('div.btos select').removeClass('invalid');
  1060. }
  1061. mark_tos_invalid(){
  1062. this.el.find('div.btos select').addClass('invalid');
  1063. }
  1064. mark_start_valid(){
  1065. this.el.find('div.bstart input').removeClass('invalid');
  1066. }
  1067. mark_start_invalid(){
  1068. this.el.find('div.bstart input').addClass('invalid');
  1069. }
  1070. mark_finish_valid(){
  1071. this.el.find('div.bfinish input').removeClass('invalid');
  1072. }
  1073. mark_finish_invalid(){
  1074. this.el.find('div.bfinish input').addClass('invalid');
  1075. }
  1076. mark_rate_valid(){
  1077. this.el.find('div.brate select').removeClass('invalid');
  1078. }
  1079. mark_rate_invalid(){
  1080. this.el.find('div.brate select').addClass('invalid');
  1081. }
  1082. mark_week_color(){
  1083. this.el.find('div.brating').removeClass('week1color');
  1084. this.el.find('div.brating').removeClass('week2color');
  1085. if (this.is_week1()){
  1086. this.el.find('div.brating').addClass('week1color');
  1087. }else if (this.is_week2()){
  1088. this.el.find('div.brating').addClass('week2color');
  1089. }
  1090. }
  1091. is_week1()
  1092. {
  1093. var w1_begin = new Date($('span[name="w1d1"]').data().date) ;
  1094. var w1_end = new Date($('span[name="w1d7"]').data().date);
  1095. w1_begin.setHours(0,0,0,0);
  1096. w1_end.setHours(23,59,59);
  1097. //console.log("week1 begin %o, end %o", w1_begin, w1_end);
  1098. //w1_end = new Date (w1_end.setDate(w1_end.getDate()+1)); //from 00:00 to 23:59;
  1099. var me = new Date(this.data.start);
  1100. return (w1_begin <= me && me <= w1_end );
  1101. }
  1102. is_week2()
  1103. {
  1104. var w2_begin = new Date($('span[name="w2d1"]').data().date);
  1105. var w2_end = new Date($('span[name="w2d7"]').data().date);
  1106. w2_begin.setHours(0,0,0,0);
  1107. w2_end.setHours(23,59,59);
  1108. var me = new Date(this.data.start);
  1109. return (w2_begin <= me && me <= w2_end );
  1110. }
  1111. get_payment_summary(){
  1112. var result ={};
  1113. result.ot = this.get_is_high_pay();
  1114. result.hour = this.get_working_duration();
  1115. result.money = this.get_wages();
  1116. return result;
  1117. }
  1118. get_is_high_pay()
  1119. {
  1120. var rate_info = this.get_rate_info_by_id(this.get_rate());
  1121. return this.is_high_pay_hour(rate_info);
  1122. }
  1123. get_working_duration()
  1124. {
  1125. //finish - start
  1126. var f = new Date(this.get_finish());
  1127. var s = new Date(this.get_start());
  1128. var diff = f.getTime() - s.getTime();
  1129. var hours = Math.floor(diff / 1000 / 60 / 60);
  1130. diff -= hours * 1000 * 60 * 60;
  1131. var minutes = Math.floor(diff / 1000 / 60);
  1132. var minute_to_hour = minutes/60;
  1133. return (hours + minute_to_hour);
  1134. }
  1135. get_wages(){
  1136. var hour = this.get_working_duration();
  1137. var rate_info = this.get_rate_info_by_id(this.get_rate());
  1138. return hour * rate_info.RatePerUnit;
  1139. }
  1140. get_rate_info_by_id(id){
  1141. var rate_info = {};
  1142. var rates = bts().earnings_rate;
  1143. for(var i =0; i< rates.length; i++){
  1144. var r = rates[i];
  1145. if(r.EarningsRateID == id){
  1146. rate_info = $.extend(true,{}, r);//make a copy
  1147. break;
  1148. }
  1149. }
  1150. return rate_info;
  1151. }
  1152. is_high_pay_hour(rate_info){
  1153. var keywords =bts().high_pay_keywords;
  1154. var found = false;
  1155. return false;
  1156. keywords.forEach(function(e){
  1157. if (-1 != rate_info.Name.toLowerCase().indexOf(e.toLowerCase()) )
  1158. found = true;
  1159. });
  1160. return found;
  1161. }
  1162. }//end of class Job
  1163. //global GUI summary
  1164. function get_wages()
  1165. {
  1166. var txt = $('div.wages div').html();
  1167. return parseInt(txt);
  1168. }
  1169. function set_wages(num){
  1170. $('div.wages div').html(num);
  1171. }
  1172. function set_working_hours(num){
  1173. $('input#woh').val(num);
  1174. }
  1175. function get_working_hours(){
  1176. var txt = $('input#woh').val();
  1177. return parseFloat(txt);
  1178. }
  1179. //modal box
  1180. function set_modal_title(selector, title){
  1181. var s = 'div.bts_'+ selector +' .ult_modal-title';
  1182. $(s).html(title);
  1183. }
  1184. function set_modal_content(selector, content){
  1185. var s = 'div.bts_'+ selector +' div.ult_modal-body.ult-html';
  1186. $(s).html(content);
  1187. }
  1188. function open_modal (selector){
  1189. var s='div.bts_'+selector+'_button';
  1190. $(s).trigger('click');
  1191. }
  1192. function set_modal_data(selector, data){
  1193. var s = 'div.bts_'+ selector;
  1194. $(s).data(data);
  1195. }
  1196. function get_modal_data(selector, data){
  1197. var s = 'div.bts_'+ selector;
  1198. $(s).data();
  1199. }
  1200. var blink_by_date_timer;
  1201. $(document).on('mouseenter', 'div.week1 > div, div.week2 > div', function(){
  1202. var self = this;
  1203. blink_by_date_timer = setTimeout (function(){
  1204. $(self).addClass('blink_me');
  1205. get_week2_partner(self).addClass('blink_me');
  1206. blink_same_date_by_div(self);
  1207. }, 1500);
  1208. });
  1209. $(document).on('mouseleave', 'div.week1 div, div.week2 > div', function(){
  1210. clearTimeout(blink_by_date_timer);
  1211. $(this).removeClass('blink_me');
  1212. get_week2_partner(this).removeClass('blink_me');
  1213. unblink_all_date();
  1214. });
  1215. function get_week2_partner(div){
  1216. var index = $(div).index()+1;
  1217. return $('div.week2 div:nth-child('+index+')');
  1218. }
  1219. function init_weekdays(){
  1220. var curr = new Date; // get current date
  1221. init_weekdays_by_anchor(curr, true);
  1222. return;
  1223. }
  1224. function init_weekdays_by_anchor(anchor, is_week1){
  1225. var curr = new Date(anchor); // get the date;
  1226. if (!is_week1){ //it is week2, shift for 7 days;
  1227. curr.setDate(curr.getDate() -7); //curr will be changed;
  1228. }
  1229. var first = curr.getDate() - curr.getDay() + 1; //+1 we want Mon as first
  1230. var last = first + 6; // last day is the first day + 6
  1231. if (curr.getDay() == 0 ){// it's Sunday;
  1232. last = curr.getDate();
  1233. first = last - 6;
  1234. }
  1235. var pos = 1; //first lot
  1236. for (var i=first; i<=last; i++)
  1237. {
  1238. var now = new Date(curr);
  1239. var d1 = new Date(now.setDate(i));
  1240. now = new Date(curr);
  1241. var d2 = new Date(now.setDate(i+7));
  1242. set_day_number(1,pos, d1); //week 1
  1243. set_day_number(2,pos, d2); //week 2
  1244. pos +=1;
  1245. }
  1246. }
  1247. function set_day_number(week, index, date){
  1248. var selector = 'span[name="w'+week+'d'+index+'"]';
  1249. $(selector).html(date.getDate());
  1250. $(selector).data({date:date});
  1251. //console.log('set w%d-d%d %o', week,index,date);
  1252. }
  1253. function set_today(){
  1254. var selector = 'div.sheettitle span[name="today"]';
  1255. var curr = new Date;
  1256. $(selector).html(format_date(curr));
  1257. }
  1258. Date.prototype.get_week_number = function(){
  1259. var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
  1260. var dayNum = d.getUTCDay() || 7;
  1261. d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  1262. var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
  1263. return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
  1264. };
  1265. function set_week_number(){
  1266. var date = $('span[name="w1d1"]').data().date;
  1267. //console.log("date %o", date);
  1268. var num = date.get_week_number();
  1269. $('div.weekly span[name="week1"]').html(num);
  1270. $('div.weekly span[name="week2"]').html(num+1);
  1271. set_week_boundry();
  1272. }
  1273. function set_week_boundry()
  1274. {
  1275. var date = $('span[name="w1d1"]').data().date;
  1276. $('#week1b').val(format_date(date));
  1277. var date = $('span[name="w2d7"]').data().date;
  1278. $('#week2b').val(format_date(date));
  1279. }
  1280. function number_of_unsaved_job(){
  1281. var count =0;
  1282. var total_job = $('div.jobTable').length;
  1283. var total_saved = $('div.jobTable.saved').length;
  1284. var empty = $('div.emptyrecord').length;
  1285. count = total_job - total_saved - empty;
  1286. return count;
  1287. }
  1288. $('div.prevweek.left').click(function(){
  1289. if (number_of_unsaved_job() > 0){
  1290. if(!confirm("you have unsaved jobs, proceed will lost them"))
  1291. return;
  1292. }
  1293. $('div.weekdays span.weekday').each(function(i, e){
  1294. var date = $(e).data().date;
  1295. var newdate = new Date(date.setDate(date.getDate() -7 ));
  1296. $(e).html(newdate.getDate());
  1297. $(e).data({data:newdate});
  1298. });
  1299. set_week_number();
  1300. debounced_load_timesheet();
  1301. });
  1302. $('div.nextweek.right').click(function(){
  1303. if (number_of_unsaved_job() > 0){
  1304. if(!confirm("you have unsaved jobs,proceed will lost them"))
  1305. return;
  1306. }
  1307. $('div.weekdays span.weekday').each(function(i, e){
  1308. var date = $(e).data().date;
  1309. var newdate = new Date(date.setDate(date.getDate() +7 ));
  1310. $(e).html(newdate.getDate());
  1311. $(e).data({data:newdate});
  1312. });
  1313. set_week_number();
  1314. debounced_load_timesheet();
  1315. });
  1316. $('div.weekly div.weekname.prev >input ').click(function(e){
  1317. e.stopPropagation();
  1318. });
  1319. $('div.weekly div.weekname.prev >input ').change(function(e){
  1320. var date = $('#week1b').val();
  1321. init_weekdays_by_anchor(date, true);
  1322. set_week_number();
  1323. debounced_load_timesheet();
  1324. });
  1325. $('div.weekly div.weekname.prev').click(function(){
  1326. if (!confirm ('copy entire week to next week?'))
  1327. return;
  1328. var jobs = [];
  1329. $('div.week1 >div').each(function(i,e){
  1330. var date = new Date($(e).find('span.weekday').data().date);
  1331. var strDate = format_date(date); //yyyy-mm-dd
  1332. $('div.bstart:visible').each(function(i,e){
  1333. var value = $(e).html();
  1334. if( -1 != value.indexOf(strDate) ) //found
  1335. {
  1336. var el = $(e).closest('div.jobTable');
  1337. if (el.is(":visible") && el.hasClass('saved') && ! el.hasClass('disabled')){
  1338. var id = el.data().id;
  1339. var j = bts().job_map[id];
  1340. var newj = clone_data_create_new_job(j.get_record(),7);//add 7 days
  1341. add_new_job_to_map(newj);
  1342. jobs.push(newj);
  1343. }
  1344. }
  1345. });
  1346. });
  1347. show_jobs(jobs);
  1348. debounced_calculate();
  1349. alert("Copied " + jobs.length + " jobs");
  1350. });
  1351. $('div.weekly div.weekname.next > input').click(function(e){
  1352. e.stopPropagation();
  1353. });
  1354. $('div.weekly div.weekname.next >input ').change(function(e){
  1355. e.stopPropagation();
  1356. var date = $('#week2b').val();
  1357. init_weekdays_by_anchor(date, false);
  1358. set_week_number();
  1359. debounced_load_timesheet();
  1360. });
  1361. $('div.weekly div.weekname.next').click(function(e){
  1362. $(e).find('input').trigger('click');
  1363. });
  1364. $('div.week1 > div').click(copy_to_next_week);
  1365. function copy_to_next_week (e){
  1366. e.stopPropagation();
  1367. debounced_copy_to_next_week(e, this);
  1368. }
  1369. var debounced_copy_to_next_week = debounce(function (e, self) {
  1370. blink_same_date_by_div(self);
  1371. if ($('div.bstart.blink_me').length == 0){
  1372. alert("nothing to copy");
  1373. return;
  1374. }
  1375. if (!confirm ('copy to next week'))
  1376. return;
  1377. var new_jobs = [];
  1378. $('div.bstart.blink_me').each(function(i,e){
  1379. var r = copy_single_day_to_next_week(e);
  1380. if (r != false){
  1381. add_new_job_to_map(r);
  1382. new_jobs.push(r);
  1383. }
  1384. });
  1385. show_jobs(new_jobs);
  1386. unblink_all_date();
  1387. //alert("Copied " + new_jobs.length + " jobs");
  1388. }, 500);
  1389. $('div.week1,div.week2').click(function(e){
  1390. e.stopPropagation();
  1391. $(this).toggleClass('filtered');
  1392. do_filter_workspace();
  1393. });
  1394. function copy_single_day_to_next_week(el){
  1395. var tb = $(el).closest('div.jobTable');
  1396. if (tb.is(':visible') && tb.hasClass('saved')){
  1397. var id = tb.data().id;
  1398. var j = bts().job_map[id];
  1399. if (! j.allow_edit())
  1400. return false;
  1401. var newj = clone_data_create_new_job(j.get_record() , 7); // +7 days
  1402. return newj;
  1403. }
  1404. return false;
  1405. }
  1406. function clone_data_create_new_job(val, num_of_shifted_days){
  1407. var data = $.extend(true, {}, val);//make a copy
  1408. num_of_shifted_days = typeof num_of_shifted_days !=='undefined'? num_of_shifted_days: 0;// 0 days
  1409. //reset
  1410. data.id='';
  1411. data.ack = 0;
  1412. data.rating = 0;
  1413. if (is_valid_date_str(data.start)){
  1414. var s = new Date(data.start);
  1415. var s1 = s.getDate() + num_of_shifted_days;
  1416. s = new Date(s.setDate(s1));
  1417. data.start = format_date_time(s);
  1418. }
  1419. if (is_valid_date_str(data.finish)){
  1420. var f = new Date(data.finish);
  1421. var f1 = f.getDate() + num_of_shifted_days;
  1422. f = new Date(f.setDate(f1));
  1423. data.finish = format_date_time(f);
  1424. }
  1425. var newj = new Job(data);
  1426. //return;
  1427. return newj;
  1428. }
  1429. function add_new_job_to_map(newj)
  1430. {
  1431. //add to job map
  1432. newj.newjob_id = "new_" + bts_unique_ID();
  1433. if (typeof bts().job_map_new == 'undefined'){
  1434. bts().job_map_new = [];
  1435. }
  1436. bts().job_map_new[newj.newjob_id] = newj;
  1437. }
  1438. function is_valid_date_str(val){
  1439. var d = new Date(val);
  1440. if (d.toString()== 'Invalid Date')
  1441. return false;
  1442. return true;
  1443. }
  1444. function blink_same_date_by_div(div){
  1445. var date = new Date($(div).find('span.weekday').data().date);
  1446. blink_same_date(date);
  1447. }
  1448. function blink_same_date(date){
  1449. var strDate = format_date(date); //yyyy-mm-dd
  1450. var els=[];
  1451. unblink_all_date();
  1452. var first_into_view = false; //make sure first row in match is visible
  1453. $('div.workspace div.bstart:visible').each(function(i,e){
  1454. var value = $(e).html();
  1455. if( -1 != value.indexOf(strDate) ) //found
  1456. {
  1457. if ( !first_into_view ){ //scroll to top
  1458. first_into_view = true;
  1459. ensure_visible(e);
  1460. }
  1461. els.push($(e));
  1462. $(e).addClass('blink_me');
  1463. }
  1464. });
  1465. }
  1466. function ensure_visible(el){
  1467. $(el).get(0).scrollIntoView();
  1468. }
  1469. function unblink_all_date(){
  1470. $('div.bstart').removeClass('blink_me');
  1471. }
  1472. $('div.sheettitle h1 span').click(function(){
  1473. reset_title_to_today();
  1474. load_timesheet();
  1475. });
  1476. function reset_title_to_today(){
  1477. set_today();
  1478. init_weekdays();
  1479. set_week_number();
  1480. }
  1481. var debounced_load_timesheet = debounce(load_timesheet,1000);
  1482. function load_timesheet()
  1483. {
  1484. clear_workspace();
  1485. var first = $('span[name="w1d1"]').data().date;
  1486. var last = $('span[name="w2d7"]').data().date;
  1487. $.post(bts().ajax_url, { // POST request
  1488. _ajax_nonce: bts().nonce, // nonce
  1489. action: "list_jobv1", // action
  1490. start: format_date(first),
  1491. finish: format_date(last),
  1492. }, function(response, status, xhr){
  1493. if (response.status =='success'){
  1494. display_jobs_after_staff_client_tos_info_ready(response);
  1495. }else{
  1496. alert('error loading job');
  1497. hide_loading_jobs();
  1498. }
  1499. });
  1500. }
  1501. function display_jobs_after_staff_client_tos_info_ready(response)
  1502. {
  1503. var b = bts();
  1504. if ((typeof b.staff_map != "undefined" && Object.keys(b.staff_map).length > 0) &&
  1505. (typeof b.client_map != "undefined" && Object.keys(b.client_map).length > 0) &&
  1506. (typeof b.tos != "undefined" && Object.keys(b.tos).length > 0 ) &&
  1507. (typeof b.earnings_rate != "undefined" && Object.keys(b.earnings_rate).length > 0 ))
  1508. {
  1509. var job_map={};
  1510. var jobs = [];
  1511. //map data for each jobTable
  1512. response.jobs.forEach(function(e){
  1513. //job_derive_attr(e);
  1514. var j = new Job(e)
  1515. j.saved=true; //this is a record from database;
  1516. job_map[e.id] = j;
  1517. jobs.push(j);
  1518. });
  1519. bts().job_map = job_map;
  1520. //we do works, load timesheets
  1521. var template = $("#jobv1_item").html();
  1522. var html = Mustache.render(template, {jobs:jobs});
  1523. $('div.workspace').append(html);
  1524. hide_loading_jobs();
  1525. //filter it if reqired
  1526. debounced_filter_workspace();
  1527. return;
  1528. }
  1529. //console.log('wating staff/client/tos info to be ready');
  1530. setTimeout(function(){
  1531. display_jobs_after_staff_client_tos_info_ready(response);
  1532. }, 500); //try it half seconds later
  1533. }
  1534. function has_txt_hour(str){
  1535. if (str == null){
  1536. console.warn('null');
  1537. return;
  1538. }
  1539. var s = str.toLowerCase();
  1540. return s.indexOf('hour') != -1;
  1541. }
  1542. function show_jobs(jobs){
  1543. if (jobs.length >0){
  1544. var templ = $("#jobv1_item").html();
  1545. var html = Mustache.render(templ, {jobs:jobs}); //job id should be available;
  1546. var el = $(html);
  1547. $('div.workspace').append(el);
  1548. el.get(0).scrollIntoView();
  1549. }
  1550. debounced_calculate();
  1551. }
  1552. function format_date(date){
  1553. var dd = date.getDate();
  1554. var mm = date.getMonth() + 1; //January is 0!
  1555. var yyyy = date.getFullYear();
  1556. if (dd < 10) {
  1557. dd = '0' + dd;
  1558. }
  1559. if (mm < 10) {
  1560. mm = '0' + mm;
  1561. }
  1562. return yyyy + '-' + mm + '-' +dd ;
  1563. }
  1564. function format_date_time(date){
  1565. var strdate = format_date(date);
  1566. var hh = date.getHours();
  1567. if (hh<10){
  1568. hh= '0' + hh;
  1569. }
  1570. var mm = date.getMinutes();
  1571. if (mm<10){
  1572. mm='0' + mm;
  1573. }
  1574. return strdate + ' ' + hh + ":" + mm;
  1575. }
  1576. function clear_workspace()//clear all timesheet jobs
  1577. {
  1578. $('div.workspace > div.divTable').remove();
  1579. //clear datetime picker
  1580. $('div.xdsoft_datetimepicker').remove();
  1581. //
  1582. bts().job_map = {};
  1583. bts().job_map_new = {};
  1584. show_loading_jobs();
  1585. }
  1586. $('div.workinghours').click(function(){
  1587. $('div.bts_message_button').trigger('click');
  1588. });
  1589. function check_workspace_error(){
  1590. var els = $('div.workspace').find('.error');
  1591. if(els.length >0){
  1592. els.get(0).scrollIntoView();
  1593. return true;
  1594. }
  1595. return false;
  1596. }
  1597. $('button[name="confirmschedule"]').click(function(){
  1598. if( check_workspace_error() ){
  1599. return;
  1600. }
  1601. if (!confirm('sending email to each staff for their job arrangement?'))
  1602. return;
  1603. $('div.bts_message .ult-overlay-close-inside').hide();
  1604. $('div.bts_message_button').trigger('click');
  1605. setTimeout(do_email_jobs, 2000);//2 seconds for dialog to popup
  1606. });
  1607. $('button[name="confirmschedule"]').mouseenter(function(){
  1608. $('div.week2').addClass('blink_me');
  1609. })
  1610. $('button[name="confirmschedule"]').mouseleave(function(){
  1611. $('div.week2').removeClass('blink_me');
  1612. })
  1613. var debounced_filter_workspace = debounce(do_filter_workspace, 1000);
  1614. $(document).on('click','div.userlist', debounced_filter_workspace);
  1615. function do_filter_workspace(){
  1616. var staffs =[];
  1617. $('div.stafflist div.peopleitem :checked').each(function(i, e){
  1618. if ($(e).parent().is(':visible')){
  1619. var id = $(e).parent().attr('data-id');
  1620. //console.log("%o, id=%s", e, id);
  1621. staffs.push(id.substring(1));
  1622. }
  1623. });
  1624. var clients =[];
  1625. $('div.clientlist div.peopleitem :checked').each(function(i, e){
  1626. if ($(e).parent().is(':visible')){
  1627. var id = $(e).parent().attr('data-id');
  1628. //console.log("%o, id=%s", e, id);
  1629. clients.push(id.substring(1));
  1630. }
  1631. });
  1632. $('div.jobTable').show();//show non-week1 and none-week2
  1633. filter_workspace(staffs, clients);
  1634. filter_workspace_by_weeks();
  1635. debounced_calculate();
  1636. }
  1637. function filter_workspace(staffs, clients){
  1638. //if both array is empty
  1639. if( (staffs === undefined || staffs.length ==0) &&
  1640. (clients===undefined || clients.length ==0)){
  1641. //show all
  1642. $('div.workspace div.divTable').show();
  1643. return;
  1644. }
  1645. //if staffs is empty, we only filter by client
  1646. if (staffs === undefined || staffs.length ==0){
  1647. filter_workspace_by_client(clients);
  1648. return;
  1649. }
  1650. //if clients is empty, we only filter by staff
  1651. if (clients===undefined || clients.length ==0){
  1652. filter_workspace_by_staff(staffs);
  1653. return;
  1654. }
  1655. //filter by both
  1656. filter_workspace_by_both(staffs, clients);
  1657. }
  1658. function filter_workspace_by_staff(staffs)
  1659. {
  1660. var class_name='to_be_shown';
  1661. //filter some of them;
  1662. staffs.forEach(function(e){
  1663. $('div.workspace div.jobTable[data-staff="' + e + '"]').addClass(class_name);
  1664. $('div.workspace div.jobTable[data-driver="' + e + '"]').addClass(class_name);
  1665. });
  1666. $('div.workspace div.jobTable.' + class_name).fadeIn();
  1667. $('div.workspace div.jobTable:not(.'+ class_name +')').hide();
  1668. $('.' + class_name).removeClass(class_name);
  1669. }
  1670. function filter_workspace_by_client(clients)
  1671. {
  1672. var class_name='to_be_shown';
  1673. //filter some of them;
  1674. clients.forEach(function(e){
  1675. $('div.workspace div.jobTable[data-client="' + e + '"]').addClass(class_name);
  1676. });
  1677. $('div.workspace div.jobTable.' + class_name).fadeIn();
  1678. $('div.workspace div.jobTable:not(.'+ class_name +')').hide();
  1679. $('.' + class_name).removeClass(class_name);
  1680. }
  1681. function filter_workspace_by_both(staffs, clients)
  1682. {
  1683. var class_name='hide';
  1684. //filter some of them;
  1685. clients.forEach(function(e){
  1686. $('div.workspace div.jobTable:not([data-client="' + e + '"])').addClass(class_name);
  1687. });
  1688. staffs.forEach(function(e){
  1689. $('div.workspace div.jobTable:not([data-staff="' + e + '"])').addClass(class_name);
  1690. });
  1691. $('div.workspace div.jobTable.' + class_name).hide();
  1692. $('div.workspace div.jobTable:not(.'+ class_name +')').show();
  1693. $('.' + class_name).removeClass(class_name);
  1694. }
  1695. function filter_workspace_by_weeks(){
  1696. var hide_week1 = $('div.week1').hasClass('filtered');
  1697. var hide_week2 = $('div.week2').hasClass('filtered');
  1698. if (hide_week1 && hide_week2 ){
  1699. alert("You are hiding both weeks");
  1700. //$('div.jobTable').show();//show non-week1 and none-week2
  1701. $('div.jobTable.week1job,div.jobTable.week2job').hide(); //hide week1 or week2;
  1702. }else if (hide_week1){
  1703. //$('div.jobTable:not(.week1job)').show();//show non-week1
  1704. $('div.jobTable.week1job').hide(); //hide week1;
  1705. }else if (hide_week2){
  1706. $('div.jobTable.week2job').hide(); //show non-week2
  1707. //$('div.jobTable:not(.week2job)').show(); //hide week2
  1708. }
  1709. }
  1710. var debounced_calculate = debounce(calculate_total_hour_and_money, 2000);
  1711. function calculate_total_hour_and_money()
  1712. {
  1713. //init pays for all staff;
  1714. var pays={
  1715. total: 0,
  1716. hours: 0,
  1717. };
  1718. $('.stafflist > div.peopleitem').each(function(i,e){
  1719. var people = $(this).data().obj;
  1720. people.reset_summary();
  1721. });
  1722. $('div.workspace > .divTable.jobTable:visible').each(function(i,e){
  1723. job = get_job_by_jobTable(e);
  1724. if (typeof job === 'undefined' || !job.is_job_valid() )
  1725. return;
  1726. if (is_dummy_driving(job.staff))
  1727. return;
  1728. var ps = job.get_payment_summary();
  1729. pays.total += ps.money;
  1730. pays.hours += ps.hour;
  1731. var staff = job.staff;
  1732. var people = bts().staff_people[staff]; //class People
  1733. if (people !=false)
  1734. people.add_payment_summary(ps);
  1735. });
  1736. set_wages(pays.total.toFixed(2));
  1737. set_working_hours(pays.hours.toFixed(2));
  1738. calculate_driving();
  1739. }
  1740. function is_dummy_driving(staff){
  1741. return staff == bts().driving;
  1742. }
  1743. function get_job_by_jobTable(div)
  1744. {
  1745. var e = div;
  1746. var id = $(e).attr('data-id');
  1747. var job = bts().job_map[id];
  1748. if (id == ''){
  1749. //is this a new Job without id?
  1750. var newjob_id = $(e).attr('data-newjob_id');
  1751. if ( typeof newjob_id != "undefined"){
  1752. id = newjob_id;
  1753. job = bts().job_map_new[newjob_id];
  1754. }
  1755. }
  1756. return job;
  1757. }
  1758. function calculate_driving(){
  1759. var id = bts().driving;
  1760. var kms={};
  1761. $('div.jobTable[data-staff="' + id + '"]:visible').each(function(){
  1762. var el = this;
  1763. var match = find_driving_partner_job(el);
  1764. if (match == false)
  1765. return;
  1766. var staff = $('#' + match).data().staff;
  1767. if (typeof kms[staff] =='undefined'){
  1768. kms[staff] = 0;
  1769. }
  1770. kms[staff] += convert_driving_to_km(el);
  1771. //console.log($(this).attr('id'), matches, kms);
  1772. });
  1773. //console.log(kms);
  1774. for (var staff in kms ){
  1775. bts().staff_people[staff].set_km(kms[staff]);
  1776. //console.log(bts().staff_map[staff]);
  1777. ensure_visible(bts().staff_people[staff].selector);
  1778. }
  1779. }
  1780. function find_driving_partner_job(selector){
  1781. return false;
  1782. if (typeof $(selector).attr('data-parent') != "undefined" && $(selector).attr('data-parent') !="")
  1783. return $(selector).attr('data-parent');
  1784. var job = $(selector).data();
  1785. var start = new Date(job.start);
  1786. var client = job.client;
  1787. var matches = [];
  1788. $('div.workspace > .divTable.jobTable:visible').each(function(i,e){
  1789. var match = $(this).data();
  1790. staff = match.staff;
  1791. s = new Date(match.start);
  1792. c = match.client;
  1793. if ((start - s == 0) && (client == c) && staff != bts().driving){
  1794. matches.push({parent:$(this).attr('id'), driver: staff});
  1795. }
  1796. });
  1797. if (matches.length != 1){
  1798. //$(selector).find('.bstart').addClass("error");
  1799. //$(selector).find(".bstart_err").html("No matched driving Job");
  1800. //ensure_visible(selector);
  1801. console.warn("1 driving job has more than 1 matching", $(selector).attr('id'), matches);
  1802. return false;
  1803. }
  1804. $(selector).attr('data-driver', matches[0].driver);
  1805. $(selector).attr('data-parent', matches[0].parent);
  1806. $(selector).find('.bstaff').html("Driving/" + bts().staff_map[matches[0].driver].display_name);
  1807. return matches[0].parent;
  1808. }
  1809. function convert_driving_to_km(selector){
  1810. var data = $(selector).data();
  1811. var tos = data.tos;
  1812. var start = new Date(data.start);
  1813. var finish = new Date(data.finish);
  1814. var hours = Math.abs(finish - start) / 36e5; //in hours
  1815. var rate = parseFloat(bts().tos[tos].price);
  1816. var pay = hours * rate;
  1817. var km = pay / 1.2; //$1.2 per km
  1818. return km;
  1819. }
  1820. function find_staff(login)
  1821. {
  1822. var d = $('#p'+login).data();
  1823. if (typeof d === 'undefined')
  1824. return false;
  1825. return $('#p'+login).data().obj;
  1826. }
  1827. $(document).on('change', '.divTableRow input[name="ack"]', function(e) {
  1828. var el = $(this).closest('.jobTable');
  1829. var data = el.data();
  1830. data.ack = e.checked? 1: 0;
  1831. job_mark_dirty(el);
  1832. });
  1833. function job_mark_dirty(el)
  1834. {
  1835. el.removeClass('saved');
  1836. el.addClass('dirty');
  1837. }
  1838. function job_mark_clean(el)
  1839. {
  1840. el.addClass('saved');
  1841. el.removeClass('dirty');
  1842. }
  1843. function job_is_week1(t)
  1844. {
  1845. var w1_begin = new Date($('span[name="w1d1"]').data().date) ;
  1846. var w1_end = new Date($('span[name="w1d7"]').data().date);
  1847. w1_begin.setHours(0,0,0,0);
  1848. w1_end.setHours(23,59,59);
  1849. //console.log("week1 begin %o, end %o", w1_begin, w1_end);
  1850. //w1_end = new Date (w1_end.setDate(w1_end.getDate()+1)); //from 00:00 to 23:59;
  1851. var me = new Date(t);
  1852. return (w1_begin <= me && me <= w1_end );
  1853. }
  1854. function job_is_week2(t)
  1855. {
  1856. var w2_begin = new Date($('span[name="w2d1"]').data().date);
  1857. var w2_end = new Date($('span[name="w2d7"]').data().date);
  1858. w2_begin.setHours(0,0,0,0);
  1859. w2_end.setHours(23,59,59);
  1860. var me = new Date(t);
  1861. return (w2_begin <= me && me <= w2_end );
  1862. }
  1863. function init_ts(){
  1864. xero(false);
  1865. wifi(false);
  1866. csv(false);
  1867. show_loading_jobs();
  1868. list_staff();
  1869. list_clients();
  1870. list_tos();
  1871. ajax_earning_rate();
  1872. //setTimeout(list_staff, 5000); // for testing delayed loading of jobs only
  1873. //setTimeout(list_clients, 8000); // for testing delayed loading of jobs only
  1874. //setTimeout(list_tos, 10000); // for testing delayed loading of jobs only
  1875. init_user_search();
  1876. reset_title_to_today();
  1877. load_timesheet();
  1878. }
  1879. function do_email_jobs()
  1880. {
  1881. var selector = 'div.bts_message div.ult_modal-body';
  1882. $(selector).html('Analysis staff jobs ... ok');
  1883. var staff = bts().staff.slice(0);//copy this array;
  1884. var s = staff.pop();
  1885. //week2 start
  1886. var w2_begin = new Date($('span[name="w2d1"]').data().date);
  1887. var w2_end = new Date($('span[name="w2d7"]').data().date);
  1888. var start = format_date(w2_begin);
  1889. var finish = format_date(w2_end);
  1890. function do_staff(){
  1891. var el = $('<p> Checking ' + s.firstname + "....</p>");
  1892. $(selector).append(el);
  1893. el[0].scrollIntoView();
  1894. $.post(bts().ajax_url, { // POST request
  1895. _ajax_nonce: bts().nonce, // nonce
  1896. action: "email_job", // action
  1897. staff : s.login,
  1898. start : start,
  1899. finish: finish,
  1900. }, function(response, status, xhr){
  1901. if (response.status == 'success'){
  1902. if (response.sent){
  1903. el.append('<span class="sent">' + response.emailstatus + '</span>');
  1904. }else{
  1905. el.append('<span class="nojob">' + response.emailstatus + '</span>');
  1906. }
  1907. }else{
  1908. el.append('<span class="error"> Error[' + response.error + ' ...]</span>');
  1909. }
  1910. }).fail(function(){
  1911. el.append('<span class="error">' + 'Network Error occured' + '</span>');
  1912. //clear staff pending list, stop further processing
  1913. s = [];
  1914. }).always(function(){//next staff
  1915. if (staff.length >0){
  1916. s = staff.pop();
  1917. setTimeout(do_staff, 100); //a short delay makes it looks nice
  1918. }else{
  1919. $('div.bts_message .ult-overlay-close-inside').show();
  1920. $('div.bts_message .ult-overlay-close-inside').addClass('blink_me');
  1921. $('div.week2').removeClass('blink_me');
  1922. $(selector).append('<span class="sent">All staff confirmed! </span>');
  1923. }
  1924. });
  1925. }
  1926. //execute
  1927. do_staff();
  1928. }
  1929. function ajax_earning_rate(){
  1930. $.post(bts().ajax_url, { // POST request
  1931. _ajax_nonce: bts().nonce, // nonce
  1932. action: "earnings_rate", // action
  1933. }, function(response, status, xhr){
  1934. bts().earnings_rate = {};
  1935. response.options.forEach(function(e){
  1936. bts().earnings_rate[e.EarningsRateID]=e;
  1937. });
  1938. //console.log("%o", bts().earnings_rate);
  1939. });
  1940. }
  1941. function do_delete_duplicate()
  1942. {
  1943. var len = $('div.jobTable.to_be_deleted_duplicate').length;
  1944. if (len <= 0){
  1945. return;
  1946. }
  1947. if (!confirm("Delete " + len + " duplicates? ")){
  1948. return;
  1949. }
  1950. $('div.jobTable.to_be_deleted_duplicate:not(.saved)').each(function(){
  1951. remove_job_from_gui(this);
  1952. });
  1953. var ids = [];
  1954. $('div.jobTable.to_be_deleted_duplicate.saved').each(function(){
  1955. var id = $(this).attr('data-id');
  1956. if (id != '')
  1957. ids.push(id);
  1958. });
  1959. if ( ids.length >0 ){
  1960. $.post(bts().ajax_url, { // POST request
  1961. _ajax_nonce: bts().nonce, // nonce
  1962. action: "delete_jobv1", // action
  1963. jobs: ids, //delete multiple ids
  1964. }, function(response, status, xhr){
  1965. if (response.status=='success'){
  1966. $('div.jobTable.to_be_deleted_duplicate.saved').each(function(){
  1967. remove_job_from_gui(this);
  1968. });
  1969. debounced_calculate();
  1970. }else{
  1971. alert( 'error deleting duplicates:\n\nError:\n\n' + response.error + "\n\n");
  1972. }
  1973. });
  1974. }
  1975. }
  1976. function check_duplicate()
  1977. {
  1978. var to_be_deleted=[];
  1979. //make a copy of all jobs
  1980. var alljobs = {};
  1981. $('div.jobTable:visible').each(function(e){
  1982. alljobs[$(this).attr('id')] = $.extend({}, $(this).data());
  1983. });
  1984. //loop through jobs
  1985. for(var id1 in alljobs){
  1986. var job1 = alljobs[id1];
  1987. if (typeof job1.parent != 'undefined')
  1988. continue; //bypass it it has already found parents
  1989. job1.compared_as_master = true;//mark it
  1990. job1.duplicates={};
  1991. //console.log('investigating %s' , job1.id);
  1992. //match job2
  1993. for(var id2 in alljobs){
  1994. if (id1 == id2)
  1995. continue;
  1996. var job2 = alljobs[id2];
  1997. if (typeof job2.compared_as_master != 'undefined')
  1998. continue;
  1999. if (typeof job2.parent != "undefined")
  2000. continue; //it has already parent;
  2001. //console.log('comareing %s vs %s', job1.id, job2.id);
  2002. if (is_same_job(job1,job2)){
  2003. job2.parent = job1.id;
  2004. job1.duplicates[id2] = job2;
  2005. //console.warn("found: %s = %s", job1.id, job2.id);
  2006. to_be_deleted.push(id2);
  2007. }
  2008. }
  2009. }
  2010. if (to_be_deleted.length == 0){
  2011. alert("No duplicate found!");
  2012. return;
  2013. }
  2014. //console.log('all-done, found %d duplicates: %o', to_be_deleted.length, to_be_deleted);
  2015. mark_duplicate(to_be_deleted);
  2016. return to_be_deleted;
  2017. }
  2018. function is_same_job(job1, job2)
  2019. {
  2020. var s1 = new Date(job1.start);
  2021. var s2 = new Date(job2.start);
  2022. var f1 = new Date(job1.finish);
  2023. var f2 = new Date(job2.finish);
  2024. if ( (job1.tos == job2.tos) &&
  2025. (job1.staff == job2.staff) &&
  2026. (job1.client == job2.client) &&
  2027. (s1 - s2 == 0) &&
  2028. (f1 - f2 == 0) )
  2029. {
  2030. return true;
  2031. }
  2032. return false;
  2033. }
  2034. function mark_duplicate(ids)
  2035. {
  2036. ids.forEach(function(id){
  2037. var selector = '#' + id;
  2038. ensure_visible(selector);
  2039. $(selector).addClass('to_be_deleted_duplicate');
  2040. });
  2041. }
  2042. function do_edit_new_job(id)
  2043. {
  2044. open_modal('editor');
  2045. set_modal_title('editor', "Editing New Job ");
  2046. var new_job = bts().job_map_new[id];
  2047. new_job.editorid = id;
  2048. //set_modal_data('editor', {jobid: id, job_copy:job_copy});
  2049. var html = $('#jobv1_editor').html();
  2050. html = Mustache.render(html, new_job);
  2051. set_modal_content('editor', html);
  2052. //update GUI
  2053. dtp_init();
  2054. //init editor
  2055. var e = new JobEditor('#editor_' + id, new_job);
  2056. //console.log("e is instance of JobEditor %o", e instanceof JobEditor);
  2057. }
  2058. function do_edit_job(id)
  2059. {
  2060. //make a copy of the job
  2061. var child = bts().job_map[id];
  2062. if (! child.allow_edit()){
  2063. var msg =`You should not Edit this job,
  2064. it's locked by Xero,
  2065. Unless you insist to proceed
  2066. Are you sure you want edit it?
  2067. `;
  2068. if(!confirm(msg))
  2069. return;
  2070. }
  2071. var el = $("#job_" + id);
  2072. el.addClass('Editing');
  2073. open_modal('editor');
  2074. set_modal_title('editor', "Editing Job: " + id);
  2075. var job_copy = Object.assign(Object.create(Object.getPrototypeOf(child)), child); //a shallow copy only;
  2076. job_copy.editorid = bts_random_number();
  2077. //set_modal_data('editor', {jobid: id, job_copy:job_copy});
  2078. var html = $('#jobv1_editor').html();
  2079. html = Mustache.render(html, job_copy);
  2080. set_modal_content('editor', html);
  2081. //update GUI
  2082. dtp_init();
  2083. //init editor
  2084. var e = new JobEditor('#editor_' + job_copy.editorid, job_copy);
  2085. //console.log("e is instance of JobEditor %o", e instanceof JobEditor);
  2086. }
  2087. $( ".boundary_datepicker" ).datepicker();
  2088. $( ".boundary_datepicker" ).datepicker("option", "dateFormat", "yy-mm-dd");
  2089. $(document).on('click', 'div.clientlist div[name="title"] a', function(e){
  2090. e.preventDefault();
  2091. e.stopPropagation();
  2092. var id = $(this).closest('label.peopleitem').attr('data-id').substring(1);
  2093. var str = 'https://acaresydncy.com.au/feedback_card/' + id;
  2094. var name = $(this).html();
  2095. if ( confirm ("Email feedback link of : " + name + "\n\n\n" + str + "\n\n\n to helen@acaresydney.com.au?")){
  2096. $.post(bts().ajax_url, { // POST request
  2097. _ajax_nonce: bts().nonce, // nonce
  2098. action: "email_feedback_url", // action
  2099. client : id,
  2100. }, function(response, status, xhr){
  2101. //alert('please check your email on the phone and SMS the link to your client');
  2102. }).fail(function(){
  2103. alert('network error ');
  2104. });
  2105. }
  2106. });
  2107. init_ts();
  2108. $('div.divTableHeading div.bsave span.ticon-save').mouseenter(function(){//highlight unsaved
  2109. var el = $('div.jobTable.dirty .bsave');
  2110. if (el.length > 0){
  2111. el.addClass('blink_me');
  2112. el.get(0).scrollIntoView();
  2113. }
  2114. })
  2115. $('div.divTableHeading div.bsave span.ticon-save').mouseleave(function(){//highlight unsaved
  2116. var el = $('div.jobTable.dirty .bsave');
  2117. if (el.length > 0 ) {
  2118. el.removeClass('blink_me');
  2119. }
  2120. })
  2121. $(document).on('click', 'div.jobTable.to_be_deleted_duplicate div.bedit span.ticon-check-circle',function(){//highlight unsaved
  2122. var el = $(this).closest('div.jobTable');
  2123. if (!confirm ("Mark this is none duplicate?")){
  2124. return;
  2125. }
  2126. el.removeClass('to_be_deleted_duplicate');
  2127. });
  2128. $('div.divTableHeading div.bsave span.ticon-save').click(save_unsaved_copy);
  2129. function save_unsaved_copy(event)
  2130. {
  2131. event.preventDefault();
  2132. var num = $('div.jobTable.dirty:visible').length;
  2133. if (num > 0){
  2134. if ( !confirm('save all '+ num + ' jobs?')){
  2135. return;
  2136. }
  2137. $('div.jobTable.dirty:visible').each(function(){
  2138. $(this).find('span.ticon.ticon-save').trigger('click');
  2139. })
  2140. }else{
  2141. alert("nothing to save");
  2142. }
  2143. }
  2144. $('div.divTableHeading div.bsave span.ticon-save').contextmenu(function(event){
  2145. //clearn all unsaved jobs.
  2146. event.preventDefault();
  2147. var num = $('div.jobTable.dirty:visible').length;
  2148. if (num > 0){
  2149. if ( !confirm('delete all '+ num + ' unsaved?')){
  2150. return;
  2151. }
  2152. $('div.jobTable.dirty:visible').each(function(){
  2153. var newjob_id = $(this).data().newjob_id;
  2154. delete bts().job_map_new[newjob_id]
  2155. $(this).remove();
  2156. })
  2157. }else{
  2158. alert("nothing to clean up");
  2159. }
  2160. });
  2161. /*________________________________________________________________________*/
  2162. });
  2163. })(jQuery);
  2164. /*______________scrolling______________________________________________*/
  2165. jQuery(document).ready(function(){
  2166. var timeoutid =0;
  2167. jQuery('button.peoplelist[name="down"]').mousedown(function(){
  2168. var button = this;
  2169. timeoutid = setInterval(function(){
  2170. //console.log("down scrotop %d ", jQuery(button).parent().find(".userlist").get(0).scrollTop );
  2171. jQuery(button).parent().find(".userlist").get(0).scrollTop +=240;
  2172. }, 100);
  2173. }).on('mouseup mouseleave', function(){
  2174. clearTimeout(timeoutid);
  2175. });
  2176. jQuery('button.peoplelist[name="up"]').mousedown(function(){
  2177. var button = this;
  2178. timeoutid = setInterval(function(){
  2179. //console.log("up scrotop %d ",jQuery(button).parent().find(".userlist").get(0).scrollTop );
  2180. jQuery(button).parent().find(".userlist").get(0).scrollTop -=240;
  2181. }, 100);
  2182. }).on('mouseup mouseleave', function(){
  2183. clearTimeout(timeoutid);
  2184. });
  2185. });