timesheet source code
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

2410 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).attr('value');
  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? 1: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(function(e){
  1362. e.stopPropagation();
  1363. blink_same_date_by_div(this);
  1364. if ($('div.bstart.blink_me').length == 0){
  1365. alert("nothing to copy");
  1366. return;
  1367. }
  1368. if (!confirm ('copy to next week'))
  1369. return;
  1370. var new_jobs = [];
  1371. $('div.bstart.blink_me').each(function(i,e){
  1372. var r = copy_single_day_to_next_week(e);
  1373. if (r != false){
  1374. add_new_job_to_map(r);
  1375. new_jobs.push(r);
  1376. }
  1377. });
  1378. show_jobs(new_jobs);
  1379. unblink_all_date();
  1380. alert("Copied " + new_jobs.length + " jobs");
  1381. });
  1382. $('div.week1,div.week2').click(function(e){
  1383. e.stopPropagation();
  1384. $(this).toggleClass('filtered');
  1385. do_filter_workspace();
  1386. });
  1387. function copy_single_day_to_next_week(el){
  1388. var tb = $(el).closest('div.jobTable');
  1389. if (tb.is(':visible') && tb.hasClass('saved')){
  1390. var id = tb.data().id;
  1391. var j = bts().job_map[id];
  1392. if (! j.allow_edit())
  1393. return false;
  1394. var newj = clone_data_create_new_job(j.get_record() , 7); // +7 days
  1395. return newj;
  1396. }
  1397. return false;
  1398. }
  1399. function clone_data_create_new_job(val, num_of_shifted_days){
  1400. var data = $.extend(true, {}, val);//make a copy
  1401. num_of_shifted_days = typeof num_of_shifted_days !=='undefined'? num_of_shifted_days: 0;// 0 days
  1402. //reset
  1403. data.id='';
  1404. data.ack = 0;
  1405. data.rating = 0;
  1406. if (is_valid_date_str(data.start)){
  1407. var s = new Date(data.start);
  1408. var s1 = s.getDate() + num_of_shifted_days;
  1409. s = new Date(s.setDate(s1));
  1410. data.start = format_date_time(s);
  1411. }
  1412. if (is_valid_date_str(data.finish)){
  1413. var f = new Date(data.finish);
  1414. var f1 = f.getDate() + num_of_shifted_days;
  1415. f = new Date(f.setDate(f1));
  1416. data.finish = format_date_time(f);
  1417. }
  1418. var newj = new Job(data);
  1419. //return;
  1420. return newj;
  1421. }
  1422. function add_new_job_to_map(newj)
  1423. {
  1424. //add to job map
  1425. newj.newjob_id = "new_" + bts_unique_ID();
  1426. if (typeof bts().job_map_new == 'undefined'){
  1427. bts().job_map_new = [];
  1428. }
  1429. bts().job_map_new[newj.newjob_id] = newj;
  1430. }
  1431. function is_valid_date_str(val){
  1432. var d = new Date(val);
  1433. if (d.toString()== 'Invalid Date')
  1434. return false;
  1435. return true;
  1436. }
  1437. function blink_same_date_by_div(div){
  1438. var date = new Date($(div).find('span.weekday').data().date);
  1439. blink_same_date(date);
  1440. }
  1441. function blink_same_date(date){
  1442. var strDate = format_date(date); //yyyy-mm-dd
  1443. var els=[];
  1444. unblink_all_date();
  1445. var first_into_view = false; //make sure first row in match is visible
  1446. $('div.workspace div.bstart:visible').each(function(i,e){
  1447. var value = $(e).html();
  1448. if( -1 != value.indexOf(strDate) ) //found
  1449. {
  1450. if ( !first_into_view ){ //scroll to top
  1451. first_into_view = true;
  1452. ensure_visible(e);
  1453. }
  1454. els.push($(e));
  1455. $(e).addClass('blink_me');
  1456. }
  1457. });
  1458. }
  1459. function ensure_visible(el){
  1460. $(el).get(0).scrollIntoView();
  1461. }
  1462. function unblink_all_date(){
  1463. $('div.bstart').removeClass('blink_me');
  1464. }
  1465. $('div.sheettitle h1 span').click(function(){
  1466. reset_title_to_today();
  1467. load_timesheet();
  1468. });
  1469. function reset_title_to_today(){
  1470. set_today();
  1471. init_weekdays();
  1472. set_week_number();
  1473. }
  1474. var debounced_load_timesheet = debounce(load_timesheet,1000);
  1475. function load_timesheet()
  1476. {
  1477. clear_workspace();
  1478. var first = $('span[name="w1d1"]').data().date;
  1479. var last = $('span[name="w2d7"]').data().date;
  1480. $.post(bts().ajax_url, { // POST request
  1481. _ajax_nonce: bts().nonce, // nonce
  1482. action: "list_jobv1", // action
  1483. start: format_date(first),
  1484. finish: format_date(last),
  1485. }, function(response, status, xhr){
  1486. if (response.status =='success'){
  1487. display_jobs_after_staff_client_tos_info_ready(response);
  1488. }else{
  1489. alert('error loading job');
  1490. hide_loading_jobs();
  1491. }
  1492. });
  1493. }
  1494. function display_jobs_after_staff_client_tos_info_ready(response)
  1495. {
  1496. var b = bts();
  1497. if ((typeof b.staff_map != "undefined" && Object.keys(b.staff_map).length > 0) &&
  1498. (typeof b.client_map != "undefined" && Object.keys(b.client_map).length > 0) &&
  1499. (typeof b.tos != "undefined" && Object.keys(b.tos).length > 0 ) &&
  1500. (typeof b.earnings_rate != "undefined" && Object.keys(b.earnings_rate).length > 0 ))
  1501. {
  1502. var job_map={};
  1503. var jobs = [];
  1504. //map data for each jobTable
  1505. response.jobs.forEach(function(e){
  1506. //job_derive_attr(e);
  1507. var j = new Job(e)
  1508. j.saved=true; //this is a record from database;
  1509. job_map[e.id] = j;
  1510. jobs.push(j);
  1511. });
  1512. bts().job_map = job_map;
  1513. //we do works, load timesheets
  1514. var template = $("#jobv1_item").html();
  1515. var html = Mustache.render(template, {jobs:jobs});
  1516. $('div.workspace').append(html);
  1517. hide_loading_jobs();
  1518. //filter it if reqired
  1519. debounced_filter_workspace();
  1520. return;
  1521. }
  1522. //console.log('wating staff/client/tos info to be ready');
  1523. setTimeout(function(){
  1524. display_jobs_after_staff_client_tos_info_ready(response);
  1525. }, 500); //try it half seconds later
  1526. }
  1527. function has_txt_hour(str){
  1528. if (str == null){
  1529. console.warn('null');
  1530. return;
  1531. }
  1532. var s = str.toLowerCase();
  1533. return s.indexOf('hour') != -1;
  1534. }
  1535. function show_jobs(jobs){
  1536. if (jobs.length >0){
  1537. var templ = $("#jobv1_item").html();
  1538. var html = Mustache.render(templ, {jobs:jobs}); //job id should be available;
  1539. var el = $(html);
  1540. $('div.workspace').append(el);
  1541. el.get(0).scrollIntoView();
  1542. }
  1543. debounced_calculate();
  1544. }
  1545. function format_date(date){
  1546. var dd = date.getDate();
  1547. var mm = date.getMonth() + 1; //January is 0!
  1548. var yyyy = date.getFullYear();
  1549. if (dd < 10) {
  1550. dd = '0' + dd;
  1551. }
  1552. if (mm < 10) {
  1553. mm = '0' + mm;
  1554. }
  1555. return yyyy + '-' + mm + '-' +dd ;
  1556. }
  1557. function format_date_time(date){
  1558. var strdate = format_date(date);
  1559. var hh = date.getHours();
  1560. if (hh<10){
  1561. hh= '0' + hh;
  1562. }
  1563. var mm = date.getMinutes();
  1564. if (mm<10){
  1565. mm='0' + mm;
  1566. }
  1567. return strdate + ' ' + hh + ":" + mm;
  1568. }
  1569. function clear_workspace()//clear all timesheet jobs
  1570. {
  1571. $('div.workspace > div.divTable').remove();
  1572. //clear datetime picker
  1573. $('div.xdsoft_datetimepicker').remove();
  1574. //
  1575. bts().job_map = {};
  1576. bts().job_map_new = {};
  1577. show_loading_jobs();
  1578. }
  1579. $('div.workinghours').click(function(){
  1580. $('div.bts_message_button').trigger('click');
  1581. });
  1582. function check_workspace_error(){
  1583. var els = $('div.workspace').find('.error');
  1584. if(els.length >0){
  1585. els.get(0).scrollIntoView();
  1586. return true;
  1587. }
  1588. return false;
  1589. }
  1590. $('button[name="confirmschedule"]').click(function(){
  1591. if( check_workspace_error() ){
  1592. return;
  1593. }
  1594. if (!confirm('sending email to each staff for their job arrangement?'))
  1595. return;
  1596. $('div.bts_message .ult-overlay-close-inside').hide();
  1597. $('div.bts_message_button').trigger('click');
  1598. setTimeout(do_email_jobs, 2000);//2 seconds for dialog to popup
  1599. });
  1600. $('button[name="confirmschedule"]').mouseenter(function(){
  1601. $('div.week2').addClass('blink_me');
  1602. })
  1603. $('button[name="confirmschedule"]').mouseleave(function(){
  1604. $('div.week2').removeClass('blink_me');
  1605. })
  1606. var debounced_filter_workspace = debounce(do_filter_workspace, 1000);
  1607. $(document).on('click','div.userlist', debounced_filter_workspace);
  1608. function do_filter_workspace(){
  1609. var staffs =[];
  1610. $('div.stafflist div.peopleitem :checked').each(function(i, e){
  1611. if ($(e).parent().is(':visible')){
  1612. var id = $(e).parent().attr('data-id');
  1613. //console.log("%o, id=%s", e, id);
  1614. staffs.push(id.substring(1));
  1615. }
  1616. });
  1617. var clients =[];
  1618. $('div.clientlist div.peopleitem :checked').each(function(i, e){
  1619. if ($(e).parent().is(':visible')){
  1620. var id = $(e).parent().attr('data-id');
  1621. //console.log("%o, id=%s", e, id);
  1622. clients.push(id.substring(1));
  1623. }
  1624. });
  1625. filter_workspace(staffs, clients);
  1626. filter_workspace_by_weeks();
  1627. debounced_calculate();
  1628. }
  1629. function filter_workspace(staffs, clients){
  1630. //if both array is empty
  1631. if( (staffs === undefined || staffs.length ==0) &&
  1632. (clients===undefined || clients.length ==0)){
  1633. //show all
  1634. $('div.workspace div.divTable').show();
  1635. return;
  1636. }
  1637. //if staffs is empty, we only filter by client
  1638. if (staffs === undefined || staffs.length ==0){
  1639. filter_workspace_by_client(clients);
  1640. return;
  1641. }
  1642. //if clients is empty, we only filter by staff
  1643. if (clients===undefined || clients.length ==0){
  1644. filter_workspace_by_staff(staffs);
  1645. return;
  1646. }
  1647. //filter by both
  1648. filter_workspace_by_both(staffs, clients);
  1649. }
  1650. function filter_workspace_by_staff(staffs)
  1651. {
  1652. var class_name='to_be_shown';
  1653. //filter some of them;
  1654. staffs.forEach(function(e){
  1655. $('div.workspace div.jobTable[data-staff="' + e + '"]').addClass(class_name);
  1656. $('div.workspace div.jobTable[data-driver="' + e + '"]').addClass(class_name);
  1657. });
  1658. $('div.workspace div.jobTable.' + class_name).fadeIn();
  1659. $('div.workspace div.jobTable:not(.'+ class_name +')').hide();
  1660. $('.' + class_name).removeClass(class_name);
  1661. }
  1662. function filter_workspace_by_client(clients)
  1663. {
  1664. var class_name='to_be_shown';
  1665. //filter some of them;
  1666. clients.forEach(function(e){
  1667. $('div.workspace div.jobTable[data-client="' + e + '"]').addClass(class_name);
  1668. });
  1669. $('div.workspace div.jobTable.' + class_name).fadeIn();
  1670. $('div.workspace div.jobTable:not(.'+ class_name +')').hide();
  1671. $('.' + class_name).removeClass(class_name);
  1672. }
  1673. function filter_workspace_by_both(staffs, clients)
  1674. {
  1675. var class_name='hide';
  1676. //filter some of them;
  1677. clients.forEach(function(e){
  1678. $('div.workspace div.jobTable:not([data-client="' + e + '"])').addClass(class_name);
  1679. });
  1680. staffs.forEach(function(e){
  1681. $('div.workspace div.jobTable:not([data-staff="' + e + '"])').addClass(class_name);
  1682. });
  1683. $('div.workspace div.jobTable.' + class_name).hide();
  1684. $('div.workspace div.jobTable:not(.'+ class_name +')').show();
  1685. $('.' + class_name).removeClass(class_name);
  1686. }
  1687. function filter_workspace_by_weeks(){
  1688. var hide_week1 = $('div.week1').hasClass('filtered');
  1689. var hide_week2 = $('div.week2').hasClass('filtered');
  1690. if (hide_week1 && hide_week2 ){
  1691. alert("You are hiding both weeks");
  1692. $('div.jobTable').show();//show non-week1 and none-week2
  1693. $('div.jobTable.week1job,div.jobTable.week2job').hide(); //hide week1 or week2;
  1694. }else if (hide_week1){
  1695. $('div.jobTable:not(.week1job)').show();//show non-week1
  1696. $('div.jobTable.week1job').hide(); //hide week1;
  1697. }else if (hide_week2){
  1698. $('div.jobTable.week2job').hide(); //show non-week2
  1699. $('div.jobTable:not(.week2job)').show(); //hide week2
  1700. }
  1701. }
  1702. var debounced_calculate = debounce(calculate_total_hour_and_money, 2000);
  1703. function calculate_total_hour_and_money()
  1704. {
  1705. //init pays for all staff;
  1706. var pays={
  1707. total: 0,
  1708. hours: 0,
  1709. };
  1710. $('.stafflist > div.peopleitem').each(function(i,e){
  1711. var people = $(this).data().obj;
  1712. people.reset_summary();
  1713. });
  1714. $('div.workspace > .divTable.jobTable:visible').each(function(i,e){
  1715. job = get_job_by_jobTable(e);
  1716. if (typeof job === 'undefined' || !job.is_job_valid() )
  1717. return;
  1718. if (is_dummy_driving(job.staff))
  1719. return;
  1720. var ps = job.get_payment_summary();
  1721. pays.total += ps.money;
  1722. pays.hours += ps.hour;
  1723. var staff = job.staff;
  1724. var people = bts().staff_people[staff]; //class People
  1725. if (people !=false)
  1726. people.add_payment_summary(ps);
  1727. });
  1728. set_wages(pays.total.toFixed(2));
  1729. set_working_hours(pays.hours.toFixed(2));
  1730. calculate_driving();
  1731. }
  1732. function is_dummy_driving(staff){
  1733. return staff == bts().driving;
  1734. }
  1735. function get_job_by_jobTable(div)
  1736. {
  1737. var e = div;
  1738. var id = $(e).attr('data-id');
  1739. var job = bts().job_map[id];
  1740. if (id == ''){
  1741. //is this a new Job without id?
  1742. var newjob_id = $(e).attr('data-newjob_id');
  1743. if ( typeof newjob_id != "undefined"){
  1744. id = newjob_id;
  1745. job = bts().job_map_new[newjob_id];
  1746. }
  1747. }
  1748. return job;
  1749. }
  1750. function calculate_driving(){
  1751. var id = bts().driving;
  1752. var kms={};
  1753. $('div.jobTable[data-staff="' + id + '"]:visible').each(function(){
  1754. var el = this;
  1755. var match = find_driving_partner_job(el);
  1756. if (match == false)
  1757. return;
  1758. var staff = $('#' + match).data().staff;
  1759. if (typeof kms[staff] =='undefined'){
  1760. kms[staff] = 0;
  1761. }
  1762. kms[staff] += convert_driving_to_km(el);
  1763. //console.log($(this).attr('id'), matches, kms);
  1764. });
  1765. //console.log(kms);
  1766. for (var staff in kms ){
  1767. bts().staff_people[staff].set_km(kms[staff]);
  1768. //console.log(bts().staff_map[staff]);
  1769. ensure_visible(bts().staff_people[staff].selector);
  1770. }
  1771. }
  1772. function find_driving_partner_job(selector){
  1773. if (typeof $(selector).attr('data-parent') != "undefined" && $(selector).attr('data-parent') !="")
  1774. return $(selector).attr('data-parent');
  1775. var job = $(selector).data();
  1776. var start = new Date(job.start);
  1777. var client = job.client;
  1778. var matches = [];
  1779. $('div.workspace > .divTable.jobTable:visible').each(function(i,e){
  1780. var match = $(this).data();
  1781. staff = match.staff;
  1782. s = new Date(match.start);
  1783. c = match.client;
  1784. if ((start - s == 0) && (client == c) && staff != bts().driving){
  1785. matches.push({parent:$(this).attr('id'), driver: staff});
  1786. }
  1787. });
  1788. if (matches.length != 1){
  1789. $(selector).find('.bstart').addClass("error");
  1790. $(selector).find(".bstart_err").html("No matching Job");
  1791. ensure_visible(selector);
  1792. console.warn("1 driving job has more than 1 matching", $(selector).attr('id'), matches);
  1793. return false;
  1794. }
  1795. $(selector).attr('data-driver', matches[0].driver);
  1796. $(selector).attr('data-parent', matches[0].parent);
  1797. $(selector).find('.bstaff').html("Driving/" + bts().staff_map[matches[0].driver].display_name);
  1798. return matches[0].parent;
  1799. }
  1800. function convert_driving_to_km(selector){
  1801. var data = $(selector).data();
  1802. var tos = data.tos;
  1803. var start = new Date(data.start);
  1804. var finish = new Date(data.finish);
  1805. var hours = Math.abs(finish - start) / 36e5; //in hours
  1806. var rate = parseFloat(bts().tos[tos].price);
  1807. var pay = hours * rate;
  1808. var km = pay / 1.2; //$1.2 per km
  1809. return km;
  1810. }
  1811. function find_staff(login)
  1812. {
  1813. var d = $('#p'+login).data();
  1814. if (typeof d === 'undefined')
  1815. return false;
  1816. return $('#p'+login).data().obj;
  1817. }
  1818. $(document).on('change', '.divTableRow input[name="ack"]', function(e) {
  1819. var el = $(this).closest('.jobTable');
  1820. var data = el.data();
  1821. data.ack = e.checked? 1: 0;
  1822. job_mark_dirty(el);
  1823. });
  1824. function job_mark_dirty(el)
  1825. {
  1826. el.removeClass('saved');
  1827. el.addClass('dirty');
  1828. }
  1829. function job_mark_clean(el)
  1830. {
  1831. el.addClass('saved');
  1832. el.removeClass('dirty');
  1833. }
  1834. function job_is_week1(t)
  1835. {
  1836. var w1_begin = new Date($('span[name="w1d1"]').data().date) ;
  1837. var w1_end = new Date($('span[name="w1d7"]').data().date);
  1838. w1_begin.setHours(0,0,0,0);
  1839. w1_end.setHours(23,59,59);
  1840. //console.log("week1 begin %o, end %o", w1_begin, w1_end);
  1841. //w1_end = new Date (w1_end.setDate(w1_end.getDate()+1)); //from 00:00 to 23:59;
  1842. var me = new Date(t);
  1843. return (w1_begin <= me && me <= w1_end );
  1844. }
  1845. function job_is_week2(t)
  1846. {
  1847. var w2_begin = new Date($('span[name="w2d1"]').data().date);
  1848. var w2_end = new Date($('span[name="w2d7"]').data().date);
  1849. w2_begin.setHours(0,0,0,0);
  1850. w2_end.setHours(23,59,59);
  1851. var me = new Date(t);
  1852. return (w2_begin <= me && me <= w2_end );
  1853. }
  1854. function init_ts(){
  1855. xero(false);
  1856. wifi(false);
  1857. csv(false);
  1858. show_loading_jobs();
  1859. list_staff();
  1860. list_clients();
  1861. list_tos();
  1862. ajax_earning_rate();
  1863. //setTimeout(list_staff, 5000); // for testing delayed loading of jobs only
  1864. //setTimeout(list_clients, 8000); // for testing delayed loading of jobs only
  1865. //setTimeout(list_tos, 10000); // for testing delayed loading of jobs only
  1866. init_user_search();
  1867. reset_title_to_today();
  1868. load_timesheet();
  1869. }
  1870. function do_email_jobs()
  1871. {
  1872. var selector = 'div.bts_message div.ult_modal-body';
  1873. $(selector).html('Analysis staff jobs ... ok');
  1874. var staff = bts().staff.slice(0);//copy this array;
  1875. var s = staff.pop();
  1876. //week2 start
  1877. var w2_begin = new Date($('span[name="w2d1"]').data().date);
  1878. var w2_end = new Date($('span[name="w2d7"]').data().date);
  1879. var start = format_date(w2_begin);
  1880. var finish = format_date(w2_end);
  1881. function do_staff(){
  1882. var el = $('<p> Checking ' + s.firstname + "....</p>");
  1883. $(selector).append(el);
  1884. el[0].scrollIntoView();
  1885. $.post(bts().ajax_url, { // POST request
  1886. _ajax_nonce: bts().nonce, // nonce
  1887. action: "email_job", // action
  1888. staff : s.login,
  1889. start : start,
  1890. finish: finish,
  1891. }, function(response, status, xhr){
  1892. if (response.status == 'success'){
  1893. if (response.sent){
  1894. el.append('<span class="sent">' + response.emailstatus + '</span>');
  1895. }else{
  1896. el.append('<span class="nojob">' + response.emailstatus + '</span>');
  1897. }
  1898. }else{
  1899. el.append('<span class="error"> Error[' + response.error + ' ...]</span>');
  1900. }
  1901. }).fail(function(){
  1902. el.append('<span class="error">' + 'Network Error occured' + '</span>');
  1903. //clear staff pending list, stop further processing
  1904. s = [];
  1905. }).always(function(){//next staff
  1906. if (staff.length >0){
  1907. s = staff.pop();
  1908. setTimeout(do_staff, 100); //a short delay makes it looks nice
  1909. }else{
  1910. $('div.bts_message .ult-overlay-close-inside').show();
  1911. $('div.bts_message .ult-overlay-close-inside').addClass('blink_me');
  1912. $('div.week2').removeClass('blink_me');
  1913. $(selector).append('<span class="sent">All staff confirmed! </span>');
  1914. }
  1915. });
  1916. }
  1917. //execute
  1918. do_staff();
  1919. }
  1920. function ajax_earning_rate(){
  1921. $.post(bts().ajax_url, { // POST request
  1922. _ajax_nonce: bts().nonce, // nonce
  1923. action: "earnings_rate", // action
  1924. }, function(response, status, xhr){
  1925. bts().earnings_rate = {};
  1926. response.options.forEach(function(e){
  1927. bts().earnings_rate[e.EarningsRateID]=e;
  1928. });
  1929. //console.log("%o", bts().earnings_rate);
  1930. });
  1931. }
  1932. function do_delete_duplicate()
  1933. {
  1934. var len = $('div.jobTable.to_be_deleted_duplicate').length;
  1935. if (len <= 0){
  1936. return;
  1937. }
  1938. if (!confirm("Delete " + len + " duplicates? ")){
  1939. return;
  1940. }
  1941. $('div.jobTable.to_be_deleted_duplicate:not(.saved)').each(function(){
  1942. remove_job_from_gui(this);
  1943. });
  1944. var ids = [];
  1945. $('div.jobTable.to_be_deleted_duplicate.saved').each(function(){
  1946. var id = $(this).attr('data-id');
  1947. if (id != '')
  1948. ids.push(id);
  1949. });
  1950. if ( ids.length >0 ){
  1951. $.post(bts().ajax_url, { // POST request
  1952. _ajax_nonce: bts().nonce, // nonce
  1953. action: "delete_jobv1", // action
  1954. jobs: ids, //delete multiple ids
  1955. }, function(response, status, xhr){
  1956. if (response.status=='success'){
  1957. $('div.jobTable.to_be_deleted_duplicate.saved').each(function(){
  1958. remove_job_from_gui(this);
  1959. });
  1960. debounced_calculate();
  1961. }else{
  1962. alert( 'error deleting duplicates:\n\nError:\n\n' + response.error + "\n\n");
  1963. }
  1964. });
  1965. }
  1966. }
  1967. function check_duplicate()
  1968. {
  1969. var to_be_deleted=[];
  1970. //make a copy of all jobs
  1971. var alljobs = {};
  1972. $('div.jobTable:visible').each(function(e){
  1973. alljobs[$(this).attr('id')] = $.extend({}, $(this).data());
  1974. });
  1975. //loop through jobs
  1976. for(var id1 in alljobs){
  1977. var job1 = alljobs[id1];
  1978. if (typeof job1.parent != 'undefined')
  1979. continue; //bypass it it has already found parents
  1980. job1.compared_as_master = true;//mark it
  1981. job1.duplicates={};
  1982. //console.log('investigating %s' , job1.id);
  1983. //match job2
  1984. for(var id2 in alljobs){
  1985. if (id1 == id2)
  1986. continue;
  1987. var job2 = alljobs[id2];
  1988. if (typeof job2.compared_as_master != 'undefined')
  1989. continue;
  1990. if (typeof job2.parent != "undefined")
  1991. continue; //it has already parent;
  1992. //console.log('comareing %s vs %s', job1.id, job2.id);
  1993. if (is_same_job(job1,job2)){
  1994. job2.parent = job1.id;
  1995. job1.duplicates[id2] = job2;
  1996. //console.warn("found: %s = %s", job1.id, job2.id);
  1997. to_be_deleted.push(id2);
  1998. }
  1999. }
  2000. }
  2001. if (to_be_deleted.length == 0){
  2002. alert("No duplicate found!");
  2003. return;
  2004. }
  2005. //console.log('all-done, found %d duplicates: %o', to_be_deleted.length, to_be_deleted);
  2006. mark_duplicate(to_be_deleted);
  2007. return to_be_deleted;
  2008. }
  2009. function is_same_job(job1, job2)
  2010. {
  2011. var s1 = new Date(job1.start);
  2012. var s2 = new Date(job2.start);
  2013. var f1 = new Date(job1.finish);
  2014. var f2 = new Date(job2.finish);
  2015. if ( (job1.tos == job2.tos) &&
  2016. (job1.staff == job2.staff) &&
  2017. (job1.client == job2.client) &&
  2018. (s1 - s2 == 0) &&
  2019. (f1 - f2 == 0) )
  2020. {
  2021. return true;
  2022. }
  2023. return false;
  2024. }
  2025. function mark_duplicate(ids)
  2026. {
  2027. ids.forEach(function(id){
  2028. var selector = '#' + id;
  2029. ensure_visible(selector);
  2030. $(selector).addClass('to_be_deleted_duplicate');
  2031. });
  2032. }
  2033. function do_edit_new_job(id)
  2034. {
  2035. open_modal('editor');
  2036. set_modal_title('editor', "Editing New Job ");
  2037. var new_job = bts().job_map_new[id];
  2038. new_job.editorid = id;
  2039. //set_modal_data('editor', {jobid: id, job_copy:job_copy});
  2040. var html = $('#jobv1_editor').html();
  2041. html = Mustache.render(html, new_job);
  2042. set_modal_content('editor', html);
  2043. //update GUI
  2044. dtp_init();
  2045. //init editor
  2046. var e = new JobEditor('#editor_' + id, new_job);
  2047. //console.log("e is instance of JobEditor %o", e instanceof JobEditor);
  2048. }
  2049. function do_edit_job(id)
  2050. {
  2051. //make a copy of the job
  2052. var child = bts().job_map[id];
  2053. if (! child.allow_edit()){
  2054. var msg =`You should not Edit this job,
  2055. it's locked by Xero,
  2056. Unless you insist to proceed
  2057. Are you sure you want edit it?
  2058. `;
  2059. if(!confirm(msg))
  2060. return;
  2061. }
  2062. var el = $("#job_" + id);
  2063. el.addClass('Editing');
  2064. open_modal('editor');
  2065. set_modal_title('editor', "Editing Job: " + id);
  2066. var job_copy = Object.assign(Object.create(Object.getPrototypeOf(child)), child); //a shallow copy only;
  2067. job_copy.editorid = bts_random_number();
  2068. //set_modal_data('editor', {jobid: id, job_copy:job_copy});
  2069. var html = $('#jobv1_editor').html();
  2070. html = Mustache.render(html, job_copy);
  2071. set_modal_content('editor', html);
  2072. //update GUI
  2073. dtp_init();
  2074. //init editor
  2075. var e = new JobEditor('#editor_' + job_copy.editorid, job_copy);
  2076. //console.log("e is instance of JobEditor %o", e instanceof JobEditor);
  2077. }
  2078. $( ".boundary_datepicker" ).datepicker();
  2079. $( ".boundary_datepicker" ).datepicker("option", "dateFormat", "yy-mm-dd");
  2080. $(document).on('click', 'div.clientlist div[name="title"] a', function(e){
  2081. e.preventDefault();
  2082. e.stopPropagation();
  2083. var id = $(this).closest('label.peopleitem').attr('data-id').substring(1);
  2084. var str = 'https://acaresydncy.com.au/feedback_card/' + id;
  2085. var name = $(this).html();
  2086. if ( confirm ("Email feedback link of : " + name + "\n\n\n" + str + "\n\n\n to helen@acaresydney.com.au?")){
  2087. $.post(bts().ajax_url, { // POST request
  2088. _ajax_nonce: bts().nonce, // nonce
  2089. action: "email_feedback_url", // action
  2090. client : id,
  2091. }, function(response, status, xhr){
  2092. //alert('please check your email on the phone and SMS the link to your client');
  2093. }).fail(function(){
  2094. alert('network error ');
  2095. });
  2096. }
  2097. });
  2098. init_ts();
  2099. $('div.divTableHeading div.bsave span.ticon-search').mouseenter(function(){//highlight unsaved
  2100. var el = $('div.jobTable.dirty .bsave');
  2101. if (el.length > 0){
  2102. el.addClass('blink_me');
  2103. el.get(0).scrollIntoView();
  2104. }
  2105. })
  2106. $('div.divTableHeading div.bsave span.ticon-search').mouseleave(function(){//highlight unsaved
  2107. var el = $('div.jobTable.dirty .bsave');
  2108. if (el.length > 0 ) {
  2109. el.removeClass('blink_me');
  2110. }
  2111. })
  2112. $(document).on('click', 'div.jobTable.to_be_deleted_duplicate div.bedit span.ticon-check-circle',function(){//highlight unsaved
  2113. var el = $(this).closest('div.jobTable');
  2114. if (!confirm ("Mark this is none duplicate?")){
  2115. return;
  2116. }
  2117. el.removeClass('to_be_deleted_duplicate');
  2118. });
  2119. $('div.divTableHeading div.bsave span.ticon-search').click(do_delete_unsaved_copy);
  2120. function do_delete_unsaved_copy()
  2121. { //TODO: remove this search function
  2122. var num = $('div.jobTable.dirty').length;
  2123. if (num > 0){
  2124. if ( !confirm('delete all '+ num + ' unsaved?')){
  2125. return;
  2126. }
  2127. $('div.jobTable.dirty').each(function(){
  2128. var newjob_id = $(this).data().newjob_id;
  2129. delete bts().job_map_new[newjob_id]
  2130. $(this).remove();
  2131. })
  2132. }else{
  2133. alert("nothing to clean up");
  2134. }
  2135. }
  2136. /*________________________________________________________________________*/
  2137. });
  2138. })(jQuery);
  2139. /*______________scrolling______________________________________________*/
  2140. jQuery(document).ready(function(){
  2141. var timeoutid =0;
  2142. jQuery('button.peoplelist[name="down"]').mousedown(function(){
  2143. var button = this;
  2144. timeoutid = setInterval(function(){
  2145. //console.log("down scrotop %d ", jQuery(button).parent().find(".userlist").get(0).scrollTop );
  2146. jQuery(button).parent().find(".userlist").get(0).scrollTop +=240;
  2147. }, 100);
  2148. }).on('mouseup mouseleave', function(){
  2149. clearTimeout(timeoutid);
  2150. });
  2151. jQuery('button.peoplelist[name="up"]').mousedown(function(){
  2152. var button = this;
  2153. timeoutid = setInterval(function(){
  2154. //console.log("up scrotop %d ",jQuery(button).parent().find(".userlist").get(0).scrollTop );
  2155. jQuery(button).parent().find(".userlist").get(0).scrollTop -=240;
  2156. }, 100);
  2157. }).on('mouseup mouseleave', function(){
  2158. clearTimeout(timeoutid);
  2159. });
  2160. });