timesheet source code
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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