timesheet source code
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

2198 行
62KB

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