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

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