timesheet source code
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

2384 lines
67KB

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