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

2362 line
66KB

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