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

2108 lines
59KB

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