Best JavaScript code snippet using stryker-parent
reports.js
Source:reports.js
1(function($) {2 'use strict';3 $(document).ready(function() {4 var devMode = false;5 // if (!devMode || !window.console) {6 // var console = {7 // log: function() {}8 // };9 // }10 var generateReport = {11 rules: {12 CONSUMPTION: ['selectAllPremises', 'segmentSelection', 'updateSelectionText'],13 MAXIMUMIMPORTCAPACITY: ['intervalOnly', 'hideTabs'],14 TARIFF: ['hideTabsConditionally', 'oneTypeOnly', 'updateSelectionText', 'segmentSelection'],15 JOHNLYNN: ['hideTabsIntervalConditionally', 'intervalOnlyMulti', 'segmentSelection', 'updateSelectionText'],16 DEFAULT: ['selectAllPremises', 'hideTabs', 'updateSelectionText']17 },18 premisesLimit: 450,19 $errorTemplate: $('<div class="report-error"><h3></h3></div>'),20 $premisesCheckbox: $('#accounts-content tr.pa-dt-mprn-level input'),21 $accountsCheckbox: $('tr.pa-dt-account-level input[name="account-selected"]'),22 $segmentCheckbox: $('#segments-content tr.pa-dt-mprn-level input'),23 $allPremisesCheckbox: $('tr.pa-dt-mprn-level input'),24 $intervalRows: $('tr.interval'),25 $nonIntervalRows: $('tr.non-interval'),26 $allRows: $('tr.pa-dt-mprn-level'),27 $tabs: $('.pa-inner-tabs'),28 $mixedSegments: $('.segment-mixed'),29 $notAllIntervalSegments: $('.segment-not-all-interval'),30 $selectAllPremisesLink: $('.select-all.premises'),31 $selectAllAccountBox: $('.pa-dt-account-details input[name=account-selected]'),32 $selectAllGroupLink: $('.select-all.group'),33 $selectAllMasterLink: $('.select-all.master'),34 $viewAllPremisesLink: $('.pa-dt-toggle-link'),35 $unselectSegmentLink: $('a.unselect-segment'),36 $infoBox: $('div[data-id="#info-box"]'),37 $infoCallout: $('.info-callout'),38 $cbdTableSelects: $('table.cbd-report-selects'),39 log: function() {40 var args;41 if (window.console && window.console.log && window.console.log.apply && devMode) {42 args = Array.prototype.slice.call(arguments);43 window.console.log.apply(window.console, args);44 }45 },46 bindUI: function() {47 $('.btn-report-usage').removeAttr('disabled');48 $('.btn-report-usage').click(function(e) {49 // submit the form50 generateReport.doGoReportPremises("USAGE");51 generateReport.forceReflow();52 e.preventDefault();53 })54 $('.pa-inner-tabs a').click(function(e) {55 var reportType = $("[name=reportType]:checked").val();56 var rules = generateReport.rules[reportType];57 generateReport.reset();58 generateReport.applyRules(rules);59 e.preventDefault();60 })61 $('.btn-report-csv').removeAttr('disabled');62 $('.btn-report-csv').click(function(e) {63 e.preventDefault();64 // submit the form65 generateReport.doGoReportPremises("CSV");66 generateReport.forceReflow();67 })68 $('.report-error-tooltip a.close').click(function(e) {69 $('.report-error-tooltip').hide();70 e.preventDefault();71 })72 },73 forceReflow: function() {74 var classes = $('body').attr('class');75 $('body').attr('class', classes);76 },77 setLayout: function(rules, dateParams, $button) {78 generateReport.reset();79 generateReport.resetAll();80 generateReport.applyRules(rules);81 generateReport.log(dateParams);82 generateReport.dateRange(dateParams);83 //generateReport.updateSelectionText();84 // add the selected class85 $button.parents('table').find('tr').removeClass('row-selected');86 $button.parents('tr').addClass('row-selected');87 },88 reset: function() {89 generateReport.allowAllTypes();90 generateReport.showNextSections();91 generateReport.resetAccordion();92 generateReport.resetRows();93 generateReport.resetCheckboxes();94 generateReport.resetSelectAll();95 generateReport.hideRadioSelects();96 generateReport.changeSelectionText();97 generateReport.removeAllErrorMessages();98 generateReport.checkPremisesLimit();99 },100 resetAll: function() {101 generateReport.resetTabs();102 },103 applyRules: function(rules) {104 if (rules) {105 for (var i = 0; i < rules.length; i++) {106 generateReport.log(rules[i]);107 var fn = generateReport[rules[i]];108 if (typeof fn === 'function') fn();109 }110 }111 },112 resetTabs: function() {113 $('.pa-inner-tab-content').hide();114 $('.pa-inner-tabs li').removeClass('current');115 $("a[href='#accounts-content']").parent().addClass('current');116 $('#accounts-content').show();117 generateReport.showTabs();118 generateReport.makeMixedSegmentsAvailable();119 generateReport.makeNotAllIntervalSegmentsAvailable();120 },121 showTabs: function() {122 generateReport.$tabs.show();123 },124 hideTabs: function() {125 generateReport.$tabs.hide();126 },127 makeMixedSegmentsUnavailable: function() {128 generateReport.$mixedSegments.addClass('unavailable');129 },130 makeMixedSegmentsAvailable: function() {131 generateReport.$mixedSegments.removeClass('unavailable');132 },133 hideTabsConditionally: function() {134 if ($('.segment-not-mixed').length === 0) {135 generateReport.hideTabs();136 } else if (generateReport.$mixedSegments.length > 0) {137 generateReport.makeMixedSegmentsUnavailable();138 }139 },140 makeNotAllIntervalSegmentsUnavailable: function() {141 generateReport.$notAllIntervalSegments.addClass('unavailable');142 },143 makeNotAllIntervalSegmentsAvailable: function() {144 generateReport.$notAllIntervalSegments.removeClass('unavailable');145 },146 hideTabsIntervalConditionally: function() {147 if ($('.segment-all-interval').length === 0) {148 generateReport.hideTabs();149 } else if (generateReport.$notAllIntervalSegments.length > 0) {150 generateReport.makeNotAllIntervalSegmentsUnavailable();151 }152 },153 resetAccordion: function() {154 $('[data-account-level="mprn"]').hide();155 $('[data-account-level="group"]').addClass('pa-row-closed').css('display', 'none');156 $('[data-account-level="account"]').addClass('pa-row-closed').css('display', 'none');157 $('[data-account-level="master"]').addClass('pa-row-open');158 $('.pa-dynamic-table a.pa-dt-toggle').removeClass('pa-dt-toggle-active');159 },160 resetCheckboxes: function() {161 generateReport.changeRadioGroupToCheckbox(function() {162 generateReport.$premisesCheckbox.prop('checked', false).removeAttr('disabled');163 generateReport.$segmentCheckbox.prop('checked', false).removeAttr('disabled');164 });165 },166 resetRows: function() {167 generateReport.$allRows.removeClass('dimmed unavailable row-selected');168 },169 resetSelectAll: function() {170 $('a.select-all').hide();171 generateReport.$selectAllMasterLink.text('Select all').removeClass('all-selected');172 generateReport.$selectAllGroupLink.text('Select all in this group account');173 generateReport.$selectAllPremisesLink.text('Select all premises');174 generateReport.unselectAllSegments(function() {});175 $('a.select-all').unbind();176 },177 showRadioSelects: function() {178 generateReport.$cbdTableSelects.show();179 generateReport.$cbdTableSelects.find('input[type=radio]').prop('checked', false);180 },181 hideRadioSelects: function() {182 generateReport.$cbdTableSelects.hide();183 },184 selectByType: function() {185 generateReport.$cbdTableSelects.find('input[type=radio]').change(function() {186 var value = $(this).val();187 if (value == 'interval') {188 generateReport.makeIntervalAvailable();189 generateReport.makeNonIntervalUnavailable();190 generateReport.$intervalRows.addClass('row-selected');191 generateReport.$nonIntervalRows.removeClass('row-selected');192 generateReport.$intervalRows.find('input').prop('checked', true);193 generateReport.$nonIntervalRows.find('input').prop('checked', false);194 } else if (value == 'non-interval') {195 generateReport.makeIntervalUnavailable();196 generateReport.makeNonIntervalAvailable();197 generateReport.$intervalRows.removeClass('row-selected');198 generateReport.$nonIntervalRows.addClass('row-selected');199 generateReport.$intervalRows.find('input').prop('checked', false);200 generateReport.$nonIntervalRows.find('input').prop('checked', true);201 } else {202 generateReport.makeIntervalAvailable();203 generateReport.makeNonIntervalAvailable();204 generateReport.$intervalRows.removeClass('row-selected');205 generateReport.$nonIntervalRows.removeClass('row-selected');206 generateReport.$intervalRows.find('input').prop('checked', false);207 generateReport.$nonIntervalRows.find('input').prop('checked', false);208 }209 })210 },211 restrictToOneTypeAfterSelection: function() {212 generateReport.$premisesCheckbox.change(function() {213 generateReport.syndicateCheckboxChange($(this));214 var numChecked = $('#accounts-content tr.pa-dt-mprn-level input:checked').length;215 if ($(this).is(':checked')) {216 if ($(this).closest('tr').hasClass('non-interval')) {217 generateReport.makeNonIntervalAvailable();218 generateReport.makeIntervalUnavailable();219 } else {220 generateReport.makeIntervalAvailable();221 generateReport.makeNonIntervalUnavailable();222 }223 } else if (numChecked == 0) {224 generateReport.makeIntervalAvailable();225 generateReport.makeNonIntervalAvailable();226 }227 })228 },229 showNextSections: function() {230 $('.step:nth-child(1)').next().show();231 $('.step:nth-child(2)').next().show();232 $('.step:nth-child(3)').next().show();233 },234 makeNonIntervalUnavailable: function() {235 generateReport.$nonIntervalRows.addClass('unavailable');236 generateReport.$nonIntervalRows.find('input').attr('disabled', 'disabled');237 },238 makeNonIntervalAvailable: function() {239 generateReport.$nonIntervalRows.removeClass('unavailable');240 generateReport.$nonIntervalRows.find('input').removeAttr('disabled');241 },242 makeIntervalUnavailable: function() {243 generateReport.$intervalRows.addClass('unavailable');244 generateReport.$intervalRows.find('input').attr('disabled', 'disabled');245 },246 makeIntervalAvailable: function() {247 generateReport.$intervalRows.removeClass('unavailable');248 generateReport.$intervalRows.find('input').removeAttr('disabled');249 },250 oneTypeOnly: function() {251 generateReport.showRadioSelects();252 generateReport.selectByType();253 generateReport.restrictToOneTypeAfterSelection();254 },255 allowAllTypes: function() {256 generateReport.$premisesCheckbox.unbind();257 },258 changeCheckboxToRadioGroup: function() {259 if ($('.lt-ie9').length > 0) {260 generateReport.$premisesCheckbox.each(function() {261 var $radio = $('<input type="radio" name="radio-group" />');262 $radio.val($(this).val());263 $(this).before($radio);264 $(this).remove();265 });266 generateReport.$premisesCheckbox = $('#accounts-content tr.pa-dt-mprn-level input');267 } else {268 generateReport.$premisesCheckbox.prop('type', 'radio');269 generateReport.$premisesCheckbox.prop('name', 'radio-group');270 }271 },272 changeRadioGroupToCheckbox: function(cb) {273 if ($('.lt-ie9').length > 0) {274 generateReport.$premisesCheckbox.each(function() {275 var $checkbox = $('<input type="checkbox" />');276 $checkbox.val($(this).val());277 $(this).before($checkbox);278 $(this).remove();279 });280 generateReport.$premisesCheckbox = $('#accounts-content tr.pa-dt-mprn-level input');281 } else {282 generateReport.$premisesCheckbox.prop('type', 'checkbox');283 generateReport.$premisesCheckbox.prop('name', '');284 }285 generateReport.$nonIntervalRows.find('input').removeAttr('disabled');286 generateReport.$premisesCheckbox.prop('checked', false);287 generateReport.$segmentCheckbox.prop('checked', false);288 cb();289 },290 intervalOnly: function() {291 generateReport.changeCheckboxToRadioGroup();292 generateReport.makeNonIntervalUnavailable();293 },294 intervalOnlyMulti: function() {295 generateReport.makeNonIntervalUnavailable();296 },297 syndicateCheckboxChange: function($checkbox) {298 var value = $checkbox.val();299 var isChecked = $checkbox.prop('checked');300 var equivalentCheckboxes = $('input[type="checkbox"][value="' + value + '"]');301 equivalentCheckboxes.prop('checked', isChecked);302 if (isChecked) {303 equivalentCheckboxes.parents('tr').addClass('row-selected');304 } else {305 equivalentCheckboxes.parents('tr').removeClass('row-selected');306 }307 },308 changeSelectionText: function() {309 var $premisesChecked = $('tr.pa-dt-mprn-level input:checked');310 var uniqueSelectedPremises = [];311 var selectedPremises = [];312 //Create an array of premises313 $.each($premisesChecked, function() {314 selectedPremises.push($(this).val());315 })316 //Remove duplicates from the array317 $.each(selectedPremises, function(i, el) {318 if ($.inArray(el, uniqueSelectedPremises) === -1) uniqueSelectedPremises.push(el);319 });320 var numSelected = uniqueSelectedPremises.length;321 // var numSelected = $('tr.pa-dt-mprn-level input:checked').length;322 if (numSelected == 0) {323 $('.number-selected').hide();324 } else {325 $('.number-selected').text(numSelected + ' unique premises selected').show();326 // remove any error messages if necessary327 generateReport.removeErrorMessage($('p.pa-inner-tab-intro'));328 }329 },330 checkPremisesLimit: function() {331 var selectedPremises = [],332 uniqueSelectedPremises = [];333 $('tr.pa-dt-mprn-level input').each(function() {334 if ($(this).is(':checked')) {335 selectedPremises.push($(this).val());336 }337 });338 $.each(selectedPremises, function(i, el) {339 if ($.inArray(el, uniqueSelectedPremises) === -1) uniqueSelectedPremises.push(el);340 });341 if (uniqueSelectedPremises.length > generateReport.premisesLimit) {342 generateReport.showErrorTooltip();343 } else {344 generateReport.hideErrorTooltip();345 }346 },347 updateSelectAllLinks: function() {348 $('tr.pa-dt-mprn-level').removeClass('row-selected');349 $('tr.pa-dt-mprn-level input:checked').parents('tr').addClass('row-selected');350 $.each(generateReport.$selectAllMasterLink, function() {351 if ($(this).hasClass('all-selected')) {352 $(this).text('Unselect all');353 } else {354 $(this).text('Select all');355 }356 })357 $.each(generateReport.$selectAllGroupLink, function() {358 if ($(this).hasClass('all-selected')) {359 $(this).text('Unselect all in this group account');360 } else {361 $(this).text('Select all in this group account');362 }363 })364 $.each(generateReport.$selectAllPremisesLink, function() {365 if ($(this).hasClass('all-selected')) {366 $(this).text('Unselect all premises');367 } else {368 $(this).text('Select all premises');369 }370 })371 },372 updateSelectionText: function() {373 generateReport.$premisesCheckbox.change(function() {374 generateReport.syndicateCheckboxChange($(this));375 generateReport.changeSelectionText();376 generateReport.checkPremisesLimit();377 if ($(this).is(':checked')) {378 $(this).parents('tr').addClass('row-selected');379 } else {380 $(this).parents('tr').removeClass('row-selected');381 }382 });383 $('input[name=cbd-select]').change(function(e) {384 generateReport.changeSelectionText();385 generateReport.checkPremisesLimit();386 });387 },388 selectAllPremises: function() {389 var propValue;390 // $('a.select-all').show();391 generateReport.$selectAllMasterLink.show();392 generateReport.$selectAllGroupLink.show();393 var value = $("[name=reportType]:checked").val();394 if(value !== 'DEFAULT') {395 generateReport.$selectAllPremisesLink.show();396 }397 generateReport.$selectAllPremisesLink.click(function(e) {398 var $containerDiv = $(this).closest('table').next();399 if ($(this).hasClass('all-selected')) {400 propValue = false;401 } else {402 propValue = true;403 }404 $(this).toggleClass('all-selected');405 $containerDiv.find(generateReport.$premisesCheckbox).prop('checked', propValue);406 generateReport.changeSelectionText();407 generateReport.checkPremisesLimit();408 generateReport.updateSelectAllLinks();409 e.preventDefault();410 });411 generateReport.$selectAllAccountBox.click(function(e) {412 var $containerDiv = $(this).parents('[data-account-level="account"]');413 if ($(this).hasClass('all-selected')) {414 propValue = false;415 $(this).removeClass('all-selected');416 // remove the class for all accounts in this group417 $containerDiv.find('a.select-all').removeClass('all-selected');418 } else {419 propValue = true;420 $(this).addClass('all-selected');421 // add the class for all accounts in this group422 $containerDiv.find('a.select-all').addClass('all-selected');423 generateReport.removeAllErrorMessages();424 }425 $containerDiv.find(generateReport.$premisesCheckbox).prop('checked', propValue);426 $containerDiv.find(generateReport.$accountsCheckbox).prop('checked', propValue);427 generateReport.checkPremisesLimit();428 generateReport.updateSelectAllLinks();429 // e.preventDefault();430 });431 generateReport.$selectAllGroupLink.click(function(e) {432 var $containerDiv = $(this).parents('[data-account-level="group"]');433 if ($(this).hasClass('all-selected')) {434 propValue = false;435 $(this).removeClass('all-selected');436 // remove the class for all accounts in this group437 $containerDiv.find('a.select-all').removeClass('all-selected');438 } else {439 propValue = true;440 $(this).addClass('all-selected');441 // add the class for all accounts in this group442 $containerDiv.find('a.select-all').addClass('all-selected');443 }444 $containerDiv.find(generateReport.$premisesCheckbox).prop('checked', propValue);445 $containerDiv.find(generateReport.$accountsCheckbox).prop('checked', propValue);446 generateReport.changeSelectionText();447 generateReport.checkPremisesLimit();448 generateReport.updateSelectAllLinks();449 e.preventDefault();450 });451 generateReport.$selectAllMasterLink.click(function(e) {452 if ($(this).hasClass('all-selected')) {453 propValue = false;454 // remove the class for all accounts in this group455 $('a.select-all').removeClass('all-selected');456 $(this).removeClass('all-selected');457 } else {458 propValue = true;459 // add the class for all accounts in this group460 $('a.select-all').addClass('all-selected');461 $(this).addClass('all-selected');462 }463 generateReport.$premisesCheckbox.prop('checked', propValue);464 generateReport.$accountsCheckbox.prop('checked', propValue);465 generateReport.changeSelectionText();466 generateReport.checkPremisesLimit();467 generateReport.updateSelectAllLinks();468 e.preventDefault();469 });470 },471 unselectAllSegments: function(cb) {472 generateReport.$segmentCheckbox.prop('checked', false);473 $('a.use-segment').removeClass('segment-selected');474 $('a.use-segment').prev(generateReport.$unselectSegmentLink).hide();475 $('a.use-segment').find('span').text('Use segment');476 $('a.use-segment').parents('tr').removeClass('row-selected');477 cb();478 },479 unselectSegment: function($button, $containerDiv) {480 $containerDiv.find(generateReport.$segmentCheckbox).prop('checked', false);481 // this is for the unselect link482 if ($button.hasClass('unselect-segment')) {483 $button.text('Unselect').hide();484 $button.next('a.btn').removeClass('segment-selected');485 $button.next('a.btn').find('span').text('Use segment');486 }487 // this is for the unselect blue button488 else {489 $button.removeClass('segment-selected');490 $button.prev(generateReport.$unselectSegmentLink).hide();491 $button.find('span').text('Use segment');492 }493 $button.parents('tr').removeClass('row-selected');494 },495 selectSegment: function($button, $containerDiv) {496 $containerDiv.find(generateReport.$segmentCheckbox).prop('checked', true);497 $button.addClass('segment-selected');498 $button.prev(generateReport.$unselectSegmentLink).show();499 $button.find('span').text('Selected');500 $button.parents('tr').addClass('row-selected');501 },502 segmentSelection: function() {503 //hide by default504 generateReport.$unselectSegmentLink.hide();505 $('a.use-segment').unbind('click').bind('click', function(e) {506 var $button = $(this);507 var $containerDiv = $(this).parents('table').next('.pa-mprn-summary');508 // clicked on a segment that's already selected509 generateReport.log($(this));510 if ($button.hasClass('segment-selected')) {511 generateReport.unselectSegment($button, $containerDiv);512 generateReport.log('segment-selected');513 }514 // clicked on an unselected segment515 else {516 generateReport.unselectAllSegments(function() {517 // select this segment518 generateReport.selectSegment($button, $containerDiv);519 });520 }521 e.preventDefault();522 })523 generateReport.$unselectSegmentLink.click(function(e) {524 var $button = $(this);525 var $containerDiv = $(this).parents('table').next('.pa-mprn-summary');526 generateReport.unselectSegment($button, $containerDiv);527 e.preventDefault();528 })529 },530 steps: function() {531 $("[name=reportType]").prop('checked', false);532 $("[name=reportType]").change(function() {533 var parentId = $(this).parents('div.step').attr('id');534 var formEmpty = true;535 if (parentId == 'pa-choose-report-types') {536 var errorMessage = 'Please select a report type to continue';537 var value = $("[name=reportType]:checked").val();538 var selectedReportTypes = '';539 if (value.length == 0) {540 selectedReportTypes = '<li>None selected</li>';541 } else {542 selectedReportTypes = ('<li>' + $('label[for=' + value + ']').html() + '</li>');543 }544 if (selectedReportTypes) {545 formEmpty = false;546 // $('.btn-report-account-csv').removeClass('btn-report-account-csv').addClass('btn-report-csv');547 $('.interval-consumption-ui').show();548 $('.invoice-summary-ui').hide();549 if (value == 'CONSUMPTION') {550 generateReport.setLayout(generateReport.rules.CONSUMPTION, 'MM yy', $(this));551 } else if (value == 'MAXIMUMIMPORTCAPACITY') {552 generateReport.setLayout(generateReport.rules.MAXIMUMIMPORTCAPACITY, 'dd/mm/yy', $(this));553 } else if (value == 'JOHNLYNN') {554 generateReport.setLayout(generateReport.rules.JOHNLYNN, 'dd/mm/yy', $(this));555 } else if (value == 'DEFAULT') {556 // $('.btn-report-csv').removeClass('btn-report-csv').addClass('btn-report-account-csv');557 $('.interval-consumption-ui').hide();558 $('.invoice-summary-ui').show();559 generateReport.setLayout(generateReport.rules.DEFAULT, 'dd/mm/yy', $(this));560 } else {561 generateReport.setLayout(generateReport.rules.TARIFF, 'MM yy', $(this));562 }563 generateReport.setInformationBox(value);564 }565 }566 if (parentId == 'pa-reporting-period') {567 var errorMessage = 'Please select a start and end date to continue';568 $('#' + parentId).find("input[type=text]").each(function() {569 generateReport.log($(this).val());570 if ($(this).val() == '') {571 formEmpty = false;572 return false;573 }574 });575 }576 if (parentId == 'pa-reporting-accounts-or-segments') {577 var errorMessage = 'Please select a checkbox to continue';578 $('#' + parentId + ' .pa-report-selection').find("input[type=checkbox]").each(function() {579 if ($(this).is(':checked')) {580 formEmpty = false;581 return false;582 }583 });584 }585 if (parentId == 'pa-reporting-period') {586 var errorMessage = 'Please select a reporting period to continue';587 var selectStartValue = $('#datepickerStart').val();588 var selectEndValue = $('#datepickerEnd').val();589 formEmpty = false;590 $('#pa-reporting-period .pa-report-summary .pa-reports-step-data').addClass('pa-reports-step-data-open').html('<p class="statement-number">' + selectStartValue + ' - ' + selectEndValue + '</p>');591 }592 if (formEmpty === true) {593 alert(errorMessage);594 } else {595 return;596 }597 })598 },599 triggerErrorMessage: function(msg, $element) {600 if ($element.next().hasClass('report-error') == false) {601 generateReport.$errorTemplate.find('h3').text(msg);602 generateReport.$errorTemplate.insertAfter($element);603 generateReport.log('trigger error message: ', msg);604 }605 },606 showErrorTooltip: function() {607 $('.report-error-tooltip').show();608 $('.btn-report-usage').attr('disabled', 'disabled');609 $('.btn-report-csv').attr('disabled', 'disabled');610 },611 hideErrorTooltip: function() {612 $('.report-error-tooltip').hide();613 $('.btn-report-usage').removeAttr('disabled');614 $('.btn-report-csv').removeAttr('disabled');615 },616 removeErrorMessage: function($element) {617 $.each($element, function(){618 var $el = $(this);619 if ($el.next().hasClass('report-error')) {620 $el.next().remove();621 generateReport.log('remove error message: ', $el);622 }623 });624 },625 removeAllErrorMessages: function() {626 $('div.report-error').remove();627 generateReport.log('remove all error messages');628 },629 dateRange: function(format) {630 var minDate,631 dateFromSelectedDate = null,632 dateToSelectedDate = null;633 // initialise the datepickers634 $('#date-from, #date-to').datepicker({635 changeMonth: true,636 changeYear: true,637 hideIfNoPrevNext: true,638 onSelect: function() {639 if ($('#date-to').datepicker('getDate') < $('#date-from').datepicker('getDate')) {640 generateReport.triggerErrorMessage('Please select a valid date range', $('div.date-picker'));641 } else {642 generateReport.removeErrorMessage($('div.date-picker'));643 }644 }645 });646 // update the dateFormat after initialisation647 $('#date-from, #date-to').datepicker("option", "dateFormat", format);648 // set the minDate649 if (format === 'MM yy') {650 minDate = new Date(2012, 0);651 } else {652 minDate = new Date(2012, 0, 1);653 }654 $('#date-from, #date-to').datepicker("option", "minDate", minDate);655 // set maxDate656 $('#date-from, #date-to').datepicker("option", "maxDate", 0);657 // update the panel button after initialisation658 if (format === 'MM yy') {659 $('#date-from, #date-to').datepicker("option", "showButtonPanel", true);660 } else {661 $('#date-from, #date-to').datepicker("option", "showButtonPanel", false);662 }663 //update the onClose event after initialisation664 $('#date-from, #date-to').datepicker("option", "onClose", function(date) {665 if (format === 'MM yy') {666 var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();667 var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();668 var newDate = new Date(year, month, 1);669 $(this).datepicker('setDate', newDate);670 var fromParts = $('#date-from').datepicker().val().split(' ');671 var toParts = $('#date-to').datepicker().val().split(' ');672 var newMonthFrom = new Date(Date.parse(fromParts[0] + " 1, 2012")).getMonth();673 var newMonthTo = new Date(Date.parse(toParts[0] + " 1, 2012")).getMonth();674 var newDateFrom = new Date(fromParts[1], newMonthFrom, 1);675 var newDateTo = new Date(toParts[1], newMonthTo, 1);676 if (newDateTo < newDateFrom) {677 generateReport.triggerErrorMessage('Please select a valid date range', $('div.date-picker'));678 } else {679 generateReport.removeErrorMessage($('div.date-picker'));680 }681 } else {682 return;683 }684 });685 // bind event to focus of date input fields so we can show/hide the day picker accordingly686 $('#date-from, #date-to').focus(function(event) {687 if (format == 'MM yy') {688 generateReport.hideCalendar();689 } else {690 generateReport.showCalendar();691 }692 });693 // set a default date value694 var now = new Date(),695 prettyDateFrom,696 prettyDateTo,697 monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];698 if (format === 'MM yy') {699 // set the date to700 prettyDateTo = monthNames[now.getMonth()] + ' ' + now.getFullYear();701 // set the date from702 now.setDate(0);703 prettyDateFrom = monthNames[now.getMonth()] + ' ' + now.getFullYear();704 $('#date-from, #date-to').datepicker("option", "beforeShow", function(input, inst) {705 var d = $.datepicker.parseDate('d MM yy', '1 ' + $(this).val());706 $(this).datepicker('option', 'defaultDate', d);707 $(this).datepicker('setDate', d);708 });709 } else {710 $('#date-from, #date-to').datepicker("option", "beforeShow", function(input, inst) {});711 // set the date to712 prettyDateTo = now.getDate() + '/' + (now.getMonth() + 1) + '/' + now.getFullYear();713 // set the date from714 now.setMonth(now.getMonth() - 1);715 prettyDateFrom = now.getDate() + '/' + (now.getMonth() + 1) + '/' + now.getFullYear();716 }717 $("#date-from").val(prettyDateFrom);718 $("#date-to").val(prettyDateTo);719 },720 hideCalendar: function() {721 $('.ui-datepicker-calendar').hide();722 },723 showCalendar: function() {724 $('.ui-datepicker-calendar').show();725 },726 oldReportsInfo: function() {727 $('a[href="#old-reports"]').click(function() {728 $(this).parent().next('div[data-id="#old-reports"]').toggle();729 })730 },731 setInformationBox: function(reportType) {732 if (reportType == 'CONSUMPTION') {733 generateReport.$infoBox.hide();734 generateReport.$infoCallout.find('p').hide();735 generateReport.$infoCallout.find('h2').text('Choose accounts or segments for reports');736 } else if (reportType == 'DEFAULT') {737 generateReport.$infoBox.find('h3').text('This report should be run for all the premises under a single account.')738 generateReport.$infoBox.show();739 generateReport.$infoCallout.find('p').text('Select the account you wish to use.').show();740 generateReport.$infoCallout.find('h2').text('Select an account');741 } else if (reportType == 'MAXIMUMIMPORTCAPACITY') {742 generateReport.$infoBox.find('h3').text('This report can only contain a single Interval premises')743 generateReport.$infoBox.show();744 generateReport.$infoCallout.find('p').text('Select the premises you wish to use. The premises are based on your SSE Airtricity account setup.').show();745 generateReport.$infoCallout.find('h2').text('Select a premises');746 } else if (reportType == 'JOHNLYNN') {747 generateReport.$infoBox.find('h3').text('This report can only contain Interval premises')748 generateReport.$infoBox.show();749 generateReport.$infoCallout.find('p').text('Select the accounts you wish to use. Accounts can be used for Billing, Usage, Reports & Meter reading. They are based on your SSE Airtricity account setup.').show();750 generateReport.$infoCallout.find('h2').text('Choose accounts or segments for reports');751 } else {752 generateReport.$infoBox.find('h3').text('This report cannot contain a mix of Interval and Non-Interval premises.')753 generateReport.$infoBox.show();754 generateReport.$infoCallout.find('p').text('Select the accounts you wish to use. Accounts can be used for Billing, Usage, Reports & Meter reading. They are based on your SSE Airtricity account setup.').show();755 generateReport.$infoCallout.find('h2').text('Choose accounts or segments for reports');756 }757 },758 doGoReportPremises: function(reportPage) {759 generateReport.forceReflow();760 var reportSelected,761 numSelected,762 $premisesChecked,763 selectedPremises,764 uniqueSelectedPremises,765 uniqueSelectedAccounts,766 premisesList,767 accountList,768 segmentId,769 dateFormats,770 selectedPremises,771 selectedAccounts,772 accountsTab,773 url;774 //Get the report name775 reportSelected = $("[name=reportType]:checked").val();776 if (reportSelected == "") {777 generateReport.triggerErrorMessage("Report not selected. Required!!");778 return;779 } else {780 dateFormats = generateReport.getDates(reportSelected);781 }782 // if the dates are not correct get the flip out.783 if (!dateFormats) {784 return;785 }786 generateReport.log(reportSelected);787 if(reportSelected == 'DEFAULT') {788 // segment level premises and account level premises both have checkbox fields but they are hidden in segments789 // whichever tab is selected (segments or accounts), the logic to get all checked checkboxes is the same790 var accountList = $('tr.pa-dt-account-level input[name=account-selected]:checked');791 if (accountList.length == 0) {792 generateReport.triggerErrorMessage('Please select one or more accounts', $('.pa-inner-tab-content p.pa-inner-tab-intro:visible'));793 return;794 } else {795 generateReport.removeErrorMessage($('p.pa-inner-tab-intro'));796 var accountListUrl = '';797 $.each( accountList, function( key, value ) {798 accountListUrl += $(value).val() + ',';799 });800 accountListUrl = accountListUrl.substring(0, accountListUrl.length - 1);801 var aList = [];802 $.each( accountList, function( key, el ) {803 aList.push(el);804 });805 generateReport.populateDataLayer(aList, reportPage, dateFormats);806 if (reportPage == "CSV") {807 generateReport.generateURLandCSVSubmit(accountListUrl, dateFormats, reportSelected, 'invoice-summary');808 } else {809 generateReport.generateURLAndRedirect(accountListUrl, dateFormats, reportSelected, 'invoice-summary');810 }811 }812 } else {813 // segment level premises and account level premises both have checkbox fields but they are hidden in segments814 // whichever tab is selected (segments or accounts), the logic to get all checked checkboxes is the same815 $premisesChecked = $('tr.pa-dt-mprn-level input:checked');816 generateReport.log($premisesChecked);817 if ($premisesChecked.length == 0) {818 generateReport.triggerErrorMessage('Please select one or more premises', $('.pa-inner-tab-content p.pa-inner-tab-intro:visible'));819 return;820 } else {821 uniqueSelectedPremises = [];822 selectedPremises = [];823 //Create an array of premises824 $.each($premisesChecked, function() {825 selectedPremises.push($(this).val());826 })827 //Remove duplicates from the array828 $.each(selectedPremises, function(i, el) {829 if ($.inArray(el, uniqueSelectedPremises) === -1) uniqueSelectedPremises.push(el);830 });831 premisesList = uniqueSelectedPremises.toString();832 accountsTab = $('#pa-accounts-tab').attr("class");833 // If the accounts tab is active834 if (accountsTab == "current") {835 segmentId = null;836 } else {837 segmentId = $('tr.pa-dt-group-account-level.row-selected').attr('data-segment-id');838 }839 generateReport.populateDataLayer(uniqueSelectedPremises, reportPage, dateFormats);840 if (reportPage == "CSV") {841 generateReport.generateURLandCSVSubmit(premisesList, dateFormats, reportSelected, segmentId);842 } else {843 generateReport.generateURLAndRedirect(premisesList, dateFormats, reportSelected, segmentId);844 }845 }846 }847 },848 getDates: function(reportSelected) {849 //Convert the from and to dates entered850 //For Consumption and cost breakdown the report format enterd is Month Year851 //For MIC the format is DD/MM/YYYY852 var startDateEntered = $("#date-from").val();853 var endDateEntered = $("#date-to").val();854 function pad(s) {855 return (s < 10) ? '0' + s : s;856 }857 if (startDateEntered == "" || endDateEntered == "") {858 generateReport.triggerErrorMessage("Both start and End Date not entered");859 return;860 }861 var startDateEnteredDate = "";862 var endDateEnteredDate = "";863 if (reportSelected == "MAXIMUMIMPORTCAPACITY" || reportSelected == "JOHNLYNN" || reportSelected == "DEFAULT") {864 var partsStart = startDateEntered.split("/");865 var partsEnd = endDateEntered.split("/");866 startDateEnteredDate = new Date(partsStart[2], partsStart[1] - 1, partsStart[0]);867 endDateEnteredDate = new Date(partsEnd[2], partsEnd[1] - 1, partsEnd[0]);868 } else {869 startDateEnteredDate = generateReport.convertMonthYearToDate(startDateEntered, "F");870 endDateEnteredDate = generateReport.convertMonthYearToDate(endDateEntered, "L");871 }872 if (startDateEnteredDate > endDateEnteredDate) {873 generateReport.log('dates wrong');874 generateReport.triggerErrorMessage('Please select a valid date range', $('div.date-picker'));875 return false;876 } else {877 var startDayFormat = [pad(startDateEnteredDate.getDate()), pad(startDateEnteredDate.getMonth() + 1), startDateEnteredDate.getFullYear()].join('/');878 var endDayFormat = [pad(endDateEnteredDate.getDate()), pad(endDateEnteredDate.getMonth() + 1), endDateEnteredDate.getFullYear()].join('/');879 var dateFormats = {880 startDayFormat: startDayFormat,881 endDayFormat: endDayFormat882 };883 return dateFormats;884 }885 },886 convertMonthYearToDate: function(monthYear, firstLast) {887 var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];888 var monthNumber = {};889 for (var i = 0; i < monthNames.length; ++i) {890 monthNumber[monthNames[i]] = i;891 }892 var parts = monthYear.split(/\s* \s*/);893 var month = monthNumber[parts[0]];894 var year = parts[1];895 if (firstLast == "L") {896 var lastDay = new Date(year, month + 1, 0);897 return lastDay;898 } else {899 var firstDay = new Date(year, month, 1);900 return firstDay;901 }902 },903 populateDataLayer: function(uniqueSelectedPremises, reportPage, dateFormats) {904 //Populate GTM dataLayer905 if (typeof dataLayer !== 'undefined') {906 if (reportPage == "CSV") {907 dataLayer.push({908 'Category': 'Commercial Report',909 'Action': 'Download',910 'Label': retrieveReportName(),911 'Value': prnMonths(uniqueSelectedPremises.length, dateFormats),912 'event': 'Run Report'913 });914 } else {915 dataLayer.push({916 'Category': 'Commercial Report',917 'Action': 'View Graph',918 'Label': retrieveReportName(),919 'Value': uniqueSelectedPremises.length,920 'event': 'Run Report'921 });922 }923 }924 },925 generateURLAndRedirect: function(premisesList, dateFormats, reportSelected, segmentId) {926 //Different URL depending on if report run from segments of accounts927 var url = "go-do-report.htm?start=" + dateFormats.startDayFormat + "&end=" + dateFormats.endDayFormat + "&reportTypeSelected=" + reportSelected;928 if (segmentId !== null) {929 url += "&reportingSegment=" + segmentId;930 } else {931 url += "&reportingPremises=" + premisesList;932 }933 //generateReport.log(url);934 window.location.href = url;935 },936 generateURLandCSVSubmit: function(premisesList, dateFormats, reportSelected, segmentId) {937 $("#progressbarContainer").show('slow');938 if (cookiesEnabled()) {939 token = new Date().getTime(); //use the current timestamp as the token value940 $('#dltokenvalueid').val(token);941 }942 if(segmentId === 'invoice-summary') {943 $("#reportingSegment").val(null);944 $("#reportingPremices").val(null);945 $("#reportingDebtors").val(premisesList);946 $("#goReportForm").attr('action', 'oss-co-do-csv-reports.htm?reportingDebtors=' + premisesList + '&start=' + dateFormats.startDayFormat + '&end=' + dateFormats.endDayFormat + '&dltokenval=' + $("#dltokenvalueid").val()) + "&extractType=" + reportSelected;947 }948 else if (segmentId !== null) {949 $("#reportingSegment").val(segmentId);950 $("#reportingPremices").val(null);951 $("#reportingDebtors").val(null);952 $("#goReportForm").attr('action', 'oss-co-do-csv-reports.htm?reportingSegment=' + segmentId + '&start=' + dateFormats.startDayFormat + '&end=' + dateFormats.endDayFormat + '&dltokenval=' + $("#dltokenvalueid").val()) + "&extractType=" + reportSelected;953 } else {954 $("#reportingPremices").val(premisesList);955 $("#reportingSegment").val(null);956 $("#reportingDebtors").val(null);957 $("#goReportForm").attr('action', 'oss-co-do-csv-reports.htm?reportingPremices=' + premisesList + '&start=' + dateFormats.startDayFormat + '&end=' + dateFormats.endDayFormat + '&dltokenval=' + $("#dltokenvalueid").val()) + "&extractType=" + reportSelected;958 }959 $('#goReportForm').submit();960 if (cookiesEnabled()) {961 trackDownload();962 }963 }964 }965 var showReport = {966 dateRange: function(format) {967 // initialise the datepickers968 $('#date-from, #date-to').datepicker({969 changeMonth: true,970 changeYear: true,971 maxDate: '0',972 defaultDate: "-1m",973 hideIfNoPrevNext: true974 });975 generateReport.log(format);976 // update the dateFormat after initialisation977 $('#date-from, #date-to').datepicker("option", "dateFormat", format);978 // update the panel button after initialisation979 if (format === 'MM yy') {980 $('#date-from, #date-to').datepicker("option", "showButtonPanel", true);981 } else {982 $('#date-from, #date-to').datepicker("option", "showButtonPanel", false);983 }984 //update the onClose event after initialisation985 $('#date-from, #date-to').datepicker("option", "onClose", function(date) {986 if (format === 'MM yy') {987 var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();988 var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();989 $(this).datepicker('setDate', new Date(year, month, 1));990 } else {991 return;992 }993 });994 // bind event to focus of date input fields so we can show/hide the day picker accordingly995 $('#date-from, #date-to').focus(function(event) {996 if (format == 'MM yy') {997 generateReport.hideCalendar();998 } else {999 generateReport.showCalendar();1000 }1001 });1002 },1003 hideCalendar: function() {1004 $('.ui-datepicker-calendar').hide();1005 },1006 showCalendar: function() {1007 $('.ui-datepicker-calendar').show();1008 }1009 }1010 if ($('.pa-report-selection').length) {1011 $('#goReportForm').append('<input id="reportingDebtors" name="reportingDebtors" type="hidden">');1012 generateReport.bindUI();1013 generateReport.steps();1014 generateReport.oldReportsInfo();1015 };1016 if ($('form#chartsAndReportsForm').length) {1017 var reportType = $('form#chartsAndReportsForm').attr('class');1018 var format;1019 if (reportType == 'TARIFF' || reportType == 'CONSUMPTION') {1020 format = 'MM yy';1021 } else if (reportType == 'MAXIMUMIMPORTCAPACITY') {1022 format = 'dd/mm/yy';1023 //no tabs1024 $('.pa-tabs').hide();1025 }1026 showReport.dateRange(format);1027 generateReport.oldReportsInfo();1028 }1029 })...
index.js
Source:index.js
...29 this.setState({30 reportFrmData: this.generatePatientTable()31 })32 }33 generateReport(data) {34 this.setState({ reportFrmData: data });35 }36 handleClick() {37 const { modal } = this.state;38 this.setState({39 modal: !modal40 });41 }42 generatePatientTable() {43 let params = (new URL(document.location)).searchParams;44 const age = params.get("age") ? params.get("age") + "Yr" : "";45 let table = "<img src='https://xraidigital.com/assets/images/logo/logo-default.png'/><table>";46 let tableBody = "<tbody>";47 tableBody += "<tr>";...
testConnection.js
Source:testConnection.js
...26 createConnection (options) {27 return net.createConnection(options)28 }29 30 generateReport(status,err,content){31 let relay = -132 if (this.socket){33 if (this.socket instanceof MassBrowserTestScoket)34 {35 36 relay = this.socket._handle.relay.id37 }38 }39 40 return {41 'task': this.task.id,42 'return_code' : status,43 'error': (err)? err.message : null,44 'download_time': Date.now() - this.startTime,45 'connect_time': (this.connectTime)? this.connectTime - this.startTime: -1,46 'content_size': (content)? content.length : -1,47 'relay': relay48 }49 }50 async timedHTTPDownload() {51 52 return new Promise((resolve,reject) => {53 let req = http.get({54 hostname: this.targetUrl.hostname,55 port: this.targetUrl.port,56 timeout : TIMEOUT,57 createConnection : massbrowserCreateConnection58 }, (res) => {59 debug(res.headers)60 let rawData = '';61 res.on('data', (chunk) => { 62 rawData += chunk })63 res.on('end', () => {64 resolve(this.generateReport(res.statusCode,null,res.rawHeaders+rawData))65 66 })67 res.on('error',(error) => {68 resolve(this.generateReport(-1,error,null))69 })70 res.on('timeout',() => {71 resolve(this.generateReport(408,'TimeOut',null))72 })73 74 75 })76 77 req.on('error', (e) => {78 resolve(this.generateReport(-1,e,null))79 })80 req.on('socket',(socket)=>{81 this.socket = socket82 socket.on('connect',()=>{83 this.connectTime = Date.now()84 })85 })86 87 })88 }89 async timedHTTPSDownload() {90 91 return new Promise((resolve,reject) => {92 let req = https.get({93 hostname: this.targetUrl.hostname,94 port: this.targetUrl.port,95 timeout : TIMEOUT,96 createConnection : massbrowserCreateConnection97 }, (res) => {98 debug(res.headers)99 let rawData = '';100 res.on('data', (chunk) => { 101 rawData += chunk })102 res.on('end', () => {103 resolve(this.generateReport(res.statusCode,null,res.rawHeaders+rawData))104 105 })106 res.on('error',(error) => {107 resolve(this.generateReport(-1,error,null))108 })109 res.on('timeout',() => {110 resolve(this.generateReport(408,'TimeOut',null))111 })112 113 })114 115 req.on('error', (e) => {116 resolve(this.generateReport(-1,e,null))117 })118 req.on('socket',(socket)=>{119 this.socket = socket120 socket.on('connect',()=>{121 this.connectTime = Date.now()122 })123 })124 125 })126 }127 async timedDIRECTDownload() {128 129 return new Promise((resolve,reject) => {130 let req = https.get({131 hostname: this.targetUrl.hostname,132 port: this.targetUrl.port,133 requestCert: true,134 rejectUnauthorized: false,135 timeout : TIMEOUT136 }, (res) => {137 debug(res.headers)138 let rawData = '';139 res.on('data', (chunk) => { 140 rawData += chunk })141 res.on('end', () => {142 resolve(this.generateReport(res.statusCode,null,res.rawHeaders+rawData))143 144 })145 146 res.on('error',(error) => {147 resolve(this.generateReport(-1,error,null))148 })149 res.on('timeout',() => {150 resolve(this.generateReport(408,'TimeOut',null))151 })152 153 })154 155 req.on('error', (e) => {156 resolve(this.generateReport(-1,e,null))157 })158 req.on('socket',(socket)=>{159 this.socket = socket160 socket.on('connect',()=>{161 this.connectTime = Date.now()162 })163 })164 165 })166 }167 async timedTorDownload() {168 169 return new Promise((resolve,reject) => {170 let req = shttp.get({171 172 hostname: this.targetUrl.hostname,173 port: this.targetUrl.port,174 timeout : TIMEOUT,175 socksHost: 'localhost',176 requestCert: true,177 rejectUnauthorized: false,178 socksPort: config.tor.port179 }, (res) => {180 debug(res.headers)181 let rawData = '';182 res.on('data', (chunk) => { 183 rawData += chunk })184 res.on('end', () => {185 resolve(this.generateReport(res.statusCode,null,res.rawHeaders+rawData))186 187 })188 res.on('error',(error) => {189 resolve(this.generateReport(-1,error,null))190 })191 res.on('timeout',() => {192 resolve(this.generateReport(408,'TimeOut',null))193 })194 195 })196 197 req.on('error', (e) => {198 resolve(this.generateReport(-1,e,null))199 })200 req.on('socket',(socket)=>{201 this.socket = socket202 socket.on('connect',()=>{203 this.connectTime = Date.now()204 })205 })206 207 })208 }209 runMeasurement(){210 this.startTime = Date.now()211 return this.timedDIRECTDownload()212 // if (this.type === HTTP){213 // return this.timedHTTPDownload()214 // }215 // if (this.type === HTTPS){216 // return this.timedHTTPSDownload()217 // }218 // if (this.type === DIRECT){219 // return this.timedDIRECTDownload()220 // }221 // if (this.type === TOR){222 // return this.timedTorDownload()223 // }224 // if (this.type === CACHEBROWSE){225 // return this.generateReport(-1,'NOT IMPLEMENTED',null)226 // }227 }228}...
actions.js
Source:actions.js
1import { validateArrayResponse, validatePaginatedResponse, validateObjectResponse } from '@/utils/ResponseHandler';2import { serializeObjectToQueryString } from '@/utils/RequestUtil';3import GenerateReport from '@/models/GenerateReport';4import DataPagination from '@/models/DataPagination';5export default {6 async fetchGenerateReports({ commit }, payload) {7 try {8 let response = await this.$axios.$get(`/api/v1/cash-management/trans-kas?${serializeObjectToQueryString(payload)}`);9 let data = validatePaginatedResponse(response, 'fetchGenerateReports');10 commit('setGenerateReports', data.map(generateReport => new GenerateReport(generateReport)))11 commit('setTotalGenerateReport', response.data.total);12 let pagination = new DataPagination(response.data);13 return {14 success: true,15 message: 'Success fetch generateReports',16 pagination17 }18 } catch (err) {19 console.log(err);20 return {21 success: false,22 message: err.message23 }24 }25 },26 async fetchGenerateReport({ commit }, id) {27 try {28 let response = await this.$axios.$get(`/api/v1/cash-management/trans-kas/${id}`)29 let data = validateObjectResponse(response, "fetchGenerateReport");30 commit('setSelectedGenerateReport', new GenerateReport(data));31 return {32 success: true,33 message: 'Success fetch generateReport',34 }35 } catch (err) {36 console.log(err);37 return {38 success: false,39 message: err.message40 }41 }42 },43 async createGenerateReport({ commit }, generateReport = {}) {44 try {45 let response = await this.$axios.$post(`/api/v1/cash-management/trans-kas`, generateReport.payload)46 let data = validateObjectResponse(response, "createGenerateReport");47 return {48 success: true,49 message: 'Success create generateReport',50 }51 } catch (err) {52 console.log(err);53 return {54 success: false,55 message: err.message56 }57 }58 },59 async updateGenerateReport({ commit }, generateReport = {}) {60 try {61 let response = await this.$axios.$put(`/api/v1/cash-management/trans-kas/${generateReport.code}`, generateReport.payload)62 let data = validateObjectResponse(response, "updateGenerateReport");63 return {64 success: true,65 message: 'Success update generateReport',66 }67 } catch (err) {68 console.log(err);69 return {70 success: false,71 message: err.message72 }73 }74 },75 async deleteGenerateReport({ commit }, generateReport = {}) {76 try {77 let response = await this.$axios.$delete(`/api/v1/cash-management/trans-kas/${generateReport.transId}`)78 let data = validateObjectResponse(response, "deleteGenerateReport");79 return {80 success: true,81 message: 'Success delete generateReport',82 }83 } catch (err) {84 console.log(err);85 return {86 success: false,87 message: err.message88 }89 }90 },...
lista-participantes.pdf.ts
Source:lista-participantes.pdf.ts
1import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'2import { ListaProvider } from '../providers/lista.provider';3import { Injectable } from '@angular/core';4import { ListaModel } from '../models/lista.model';5import { ParticipanteModel } from '../models/participante.model';6const download = require('downloadjs');7import { format, compareAsc } from 'date-fns'8import { GenerateReport } from "../tools/generate-report";9@Injectable()10export class ListaParticipantesPdf{11 lista:ListaModel;12 13 constructor(14 private listaProvider:ListaProvider,15 private generateReport:GenerateReport16 ){}17 async generate(){18 19 await this.generateReport.init();20 this.listaProvider.listaAtual.subscribe(lista => {21 this.lista = lista;22 });23 24 this.generateReport.addTitle(this.lista.nomeCapela, {fontSize: 16});25 this.generateReport.addSubtitle(`Lista de participantes do dia ${format(new Date(this.lista.data), 'dd/MM/yyyy')} (${format(new Date(this.lista.horaInicial), 'HH:mm')} - ${format(new Date(this.lista.horaFinal), 'HH:mm')})`, {fontSize: 14});26 this.generateReport.addRow([27 {text: `Posição`, fontSize: 14, margin: 20},28 {text: `Presença`, fontSize: 14, margin: 80},29 {text: `Participante`, fontSize: 14, margin: 140},30 {text: `Telefone`, fontSize: 14, margin: 480},31 32 ]);33 let quantParticipantes = 1;34 for(let participante of this.lista.participantes){35 this.generateReport.addRow([36 {text: `${((quantParticipantes++))}`, fontSize: 14, margin: 20},37 {text: `${participante.nome}${participante.telefone}`, checkbox: true, margin: 80},38 {text: `${participante.nome}`, fontSize: 14, margin: 140},39 {text: `${this.maskTelefone(participante.telefone)}`, fontSize: 14, margin: 480}40 ]);41 for(let dependente of participante.dependentes){42 this.generateReport.addRow([43 {text: `${((quantParticipantes++))}`, fontSize: 14, margin: 20},44 {text: `${participante.nome}${participante.telefone}${dependente.nome}`, checkbox: true, margin: 80},45 {text: `${dependente.nome}`, fontSize: 14, margin: 180}46 ]);47 }48 }49 50 this.generateReport.downloadFile('lista-missa');51 }52 private maskTelefone(telefone:string):string{53 return `(${telefone.substring(0, 2)}) ${telefone.substring(2)}`;54 }...
Using AI Code Generation
1const stryker = require('stryker-parent');2stryker.generateReport();3const stryker = require('stryker');4module.exports = stryker;5const stryker = require('stryker-lib');6module.exports = stryker;7const stryker = require('stryker-api');8module.exports = stryker;9module.exports = {10 generateReport: function() {11 }12}
Using AI Code Generation
1const parent = require('stryker-parent');2parent.generateReport();3module.exports = require('./lib/index');4const generateReport = require('./generate-report');5module.exports = {6};7module.exports = function generateReport() {8};
Using AI Code Generation
1const generateReport = require('stryker-parent').generateReport;2generateReport({3});4const generateReport = require('stryker-parent').generateReport;5generateReport({6});7const generateReport = require('stryker-parent').generateReport;8generateReport({9});10const generateReport = require('stryker-parent').generateReport;11generateReport({
Using AI Code Generation
1const stryker = require('stryker-parent');2const strykerConfig = require('./stryker.conf.js');3var report = stryker.generateReport(strykerConfig);4const stryker = require('stryker');5const strykerConfig = require('./stryker.conf.js');6var report = stryker.generateReport(strykerConfig);7const stryker = require('stryker-parent');8const strykerConfig = require('./stryker.conf.js');9var report = stryker.generateReport(strykerConfig);10const stryker = require('stryker');11const strykerConfig = require('./stryker.conf.js');12var report = stryker.generateReport(strykerConfig);13const stryker = require('stryker-parent');14const strykerConfig = require('./stryker.conf.js');15var report = stryker.generateReport(strykerConfig);16const stryker = require('stryker');17const strykerConfig = require('./stryker.conf.js');18var report = stryker.generateReport(strykerConfig);19const stryker = require('stryker-parent');20const strykerConfig = require('./stryker.conf.js');21var report = stryker.generateReport(strykerConfig);22const stryker = require('stryker');23const strykerConfig = require('./stryker.conf.js');24var report = stryker.generateReport(strykerConfig);25const stryker = require('stryker-parent');26const strykerConfig = require('./stryker.conf.js');27var report = stryker.generateReport(strykerConfig);28const stryker = require('stryker');29const strykerConfig = require('./stryker.conf.js');30var report = stryker.generateReport(stryker
Using AI Code Generation
1const generateReport = require('stryker-parent').generateReport;2generateReport();3module.exports = {4 generateReport: function() {5 }6}7const generateReport = require('stryker-parent').generateReport;8generateReport();9module.exports = {10 generateReport: function() {11 }12}13In this example, we are using the generateReport method of stryker-parent in test.js . The stryker-parent module is a dependency of the current project. As we can see, we are not using the relative path to import the method. Instead, we are using the name of the module. This is possible because we have installed the stryker-parent module as a dependency of this project. Now, if we run the test.js file, it will run successfully
Using AI Code Generation
1const strykerParent = require('stryker-parent');2const path = require('path');3strykerParent.generateReport({4 basePath: path.resolve(__dirname, 'reports', 'mutation'),5});6{7 {8 },9 {10 }11 "files": {12 "src/Bar.js": {13 "sloc": {14 }15 }16 },17}18{19 {20 },21 {22 }23 "files": {24 "src/Bar.js": {25 "sloc": {26 }27 }28 },
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!