1<template>
2  <b-container fluid="xl">
3    <page-title />
4    <b-row class="align-items-start">
5      <b-col sm="8" xl="6" class="d-sm-flex align-items-end mb-4">
6        <search
7          :placeholder="$t('pagePostCodeLogs.table.searchLogs')"
8          @change-search="onChangeSearchInput"
9          @clear-search="onClearSearchInput"
10        />
11        <div class="ml-sm-4">
12          <table-cell-count
13            :filtered-items-count="filteredRows"
14            :total-number-of-cells="allLogs.length"
15          ></table-cell-count>
16        </div>
17      </b-col>
18      <b-col sm="8" md="7" xl="6">
19        <table-date-filter @change="onChangeDateTimeFilter" />
20      </b-col>
21    </b-row>
22    <b-row>
23      <b-col xl="12" class="text-right">
24        <b-button
25          variant="link"
26          :disabled="allLogs.length === 0"
27          @click="deleteAllLogs"
28        >
29          <icon-delete /> {{ $t('global.action.deleteAll') }}
30        </b-button>
31        <b-button
32          variant="primary"
33          :disabled="allLogs.length === 0"
34          :download="exportFileNameByDate()"
35          :href="href"
36        >
37          <icon-export /> {{ $t('pagePostCodeLogs.button.exportAll') }}
38        </b-button>
39      </b-col>
40    </b-row>
41    <b-row>
42      <b-col>
43        <table-toolbar
44          ref="toolbar"
45          :selected-items-count="selectedRows.length"
46          @clear-selected="clearSelectedRows($refs.table)"
47        >
48          <template #toolbar-buttons>
49            <table-toolbar-export
50              :data="batchExportData"
51              :file-name="exportFileNameByDate()"
52            />
53          </template>
54        </table-toolbar>
55        <b-table
56          id="table-post-code-logs"
57          ref="table"
58          responsive="md"
59          selectable
60          no-select-on-click
61          sort-icon-left
62          hover
63          no-sort-reset
64          sort-desc
65          show-empty
66          sort-by="id"
67          :fields="fields"
68          :items="filteredLogs"
69          :empty-text="$t('global.table.emptyMessage')"
70          :empty-filtered-text="$t('global.table.emptySearchMessage')"
71          :per-page="perPage"
72          :current-page="currentPage"
73          :filter="searchFilter"
74          :busy="isBusy"
75          @filtered="onFiltered"
76          @row-selected="onRowSelected($event, filteredLogs.length)"
77        >
78          <!-- Checkbox column -->
79          <template #head(checkbox)>
80            <b-form-checkbox
81              v-model="tableHeaderCheckboxModel"
82              data-test-id="postCode-checkbox-selectAll"
83              :indeterminate="tableHeaderCheckboxIndeterminate"
84              @change="onChangeHeaderCheckbox($refs.table)"
85            >
86              <span class="sr-only">{{ $t('global.table.selectAll') }}</span>
87            </b-form-checkbox>
88          </template>
89          <template #cell(checkbox)="row">
90            <b-form-checkbox
91              v-model="row.rowSelected"
92              :data-test-id="`postCode-checkbox-selectRow-${row.index}`"
93              @change="toggleSelectRow($refs.table, row.index)"
94            >
95              <span class="sr-only">{{ $t('global.table.selectItem') }}</span>
96            </b-form-checkbox>
97          </template>
98          <!-- Date column -->
99          <template #cell(date)="{ value }">
100            <p class="mb-0">{{ value | formatDate }}</p>
101            <p class="mb-0">{{ value | formatTime }}</p>
102          </template>
103
104          <!-- Actions column -->
105          <template #cell(actions)="row">
106            <table-row-action
107              v-for="(action, index) in row.item.actions"
108              :key="index"
109              :value="action.value"
110              :title="action.title"
111              :row-data="row.item"
112              :btn-icon-only="true"
113              :export-name="exportFileNameByDate(action.value)"
114              :download-location="row.item.uri"
115              :download-in-new-tab="true"
116              :show-button="false"
117            >
118              <template #icon>
119                <icon-export v-if="action.value === 'export'" />
120                <icon-download v-if="action.value === 'download'" />
121              </template>
122            </table-row-action>
123          </template>
124        </b-table>
125      </b-col>
126    </b-row>
127
128    <!-- Table pagination -->
129    <b-row>
130      <b-col sm="6">
131        <b-form-group
132          class="table-pagination-select"
133          :label="$t('global.table.itemsPerPage')"
134          label-for="pagination-items-per-page"
135        >
136          <b-form-select
137            id="pagination-items-per-page"
138            v-model="perPage"
139            :options="itemsPerPageOptions"
140          />
141        </b-form-group>
142      </b-col>
143      <b-col sm="6">
144        <b-pagination
145          v-model="currentPage"
146          first-number
147          last-number
148          :per-page="perPage"
149          :total-rows="getTotalRowCount(filteredRows)"
150          aria-controls="table-post-code-logs"
151        />
152      </b-col>
153    </b-row>
154  </b-container>
155</template>
156
157<script>
158import IconDelete from '@carbon/icons-vue/es/trash-can/20';
159import IconDownload from '@carbon/icons-vue/es/download/20';
160import IconExport from '@carbon/icons-vue/es/document--export/20';
161import { omit } from 'lodash';
162import PageTitle from '@/components/Global/PageTitle';
163import Search from '@/components/Global/Search';
164import TableCellCount from '@/components/Global/TableCellCount';
165import TableDateFilter from '@/components/Global/TableDateFilter';
166import TableRowAction from '@/components/Global/TableRowAction';
167import TableToolbar from '@/components/Global/TableToolbar';
168import TableToolbarExport from '@/components/Global/TableToolbarExport';
169import LoadingBarMixin from '@/components/Mixins/LoadingBarMixin';
170import TableFilterMixin from '@/components/Mixins/TableFilterMixin';
171import BVPaginationMixin, {
172  currentPage,
173  perPage,
174  itemsPerPageOptions,
175} from '@/components/Mixins/BVPaginationMixin';
176import BVTableSelectableMixin, {
177  selectedRows,
178  tableHeaderCheckboxModel,
179  tableHeaderCheckboxIndeterminate,
180} from '@/components/Mixins/BVTableSelectableMixin';
181import BVToastMixin from '@/components/Mixins/BVToastMixin';
182import TableSortMixin from '@/components/Mixins/TableSortMixin';
183import TableRowExpandMixin, {
184  expandRowLabel,
185} from '@/components/Mixins/TableRowExpandMixin';
186import SearchFilterMixin, {
187  searchFilter,
188} from '@/components/Mixins/SearchFilterMixin';
189
190export default {
191  components: {
192    IconDelete,
193    IconExport,
194    IconDownload,
195    PageTitle,
196    Search,
197    TableCellCount,
198    TableRowAction,
199    TableToolbar,
200    TableToolbarExport,
201    TableDateFilter,
202  },
203  mixins: [
204    BVPaginationMixin,
205    BVTableSelectableMixin,
206    BVToastMixin,
207    LoadingBarMixin,
208    TableFilterMixin,
209    TableSortMixin,
210    TableRowExpandMixin,
211    SearchFilterMixin,
212  ],
213  beforeRouteLeave(to, from, next) {
214    // Hide loader if the user navigates to another page
215    // before request is fulfilled.
216    this.hideLoader();
217    next();
218  },
219  data() {
220    return {
221      isBusy: true,
222      fields: [
223        {
224          key: 'checkbox',
225          sortable: false,
226        },
227        {
228          key: 'date',
229          label: this.$t('pagePostCodeLogs.table.created'),
230          sortable: true,
231        },
232        {
233          key: 'timeStampOffset',
234          label: this.$t('pagePostCodeLogs.table.timeStampOffset'),
235        },
236        {
237          key: 'bootCount',
238          label: this.$t('pagePostCodeLogs.table.bootCount'),
239        },
240        {
241          key: 'postCode',
242          label: this.$t('pagePostCodeLogs.table.postCode'),
243        },
244        {
245          key: 'actions',
246          label: '',
247          tdClass: 'text-right text-nowrap',
248        },
249      ],
250      expandRowLabel,
251      activeFilters: [],
252      currentPage: currentPage,
253      filterStartDate: null,
254      filterEndDate: null,
255      itemsPerPageOptions: itemsPerPageOptions,
256      perPage: perPage,
257      searchFilter: searchFilter,
258      searchTotalFilteredRows: 0,
259      selectedRows: selectedRows,
260      tableHeaderCheckboxModel: tableHeaderCheckboxModel,
261      tableHeaderCheckboxIndeterminate: tableHeaderCheckboxIndeterminate,
262    };
263  },
264  computed: {
265    href() {
266      return `data:text/json;charset=utf-8,${this.exportAllLogsString()}`;
267    },
268    filteredRows() {
269      return this.searchFilter
270        ? this.searchTotalFilteredRows
271        : this.filteredLogs.length;
272    },
273    allLogs() {
274      return this.$store.getters['postCodeLogs/allPostCodes'].map(
275        (postCodes) => {
276          return {
277            ...postCodes,
278            actions: [
279              {
280                value: 'export',
281                title: this.$t('pagePostCodeLogs.action.exportLogs'),
282              },
283              {
284                value: 'download',
285                title: this.$t('pagePostCodeLogs.action.downloadDetails'),
286              },
287            ],
288          };
289        },
290      );
291    },
292    batchExportData() {
293      return this.selectedRows.map((row) => omit(row, 'actions'));
294    },
295    filteredLogsByDate() {
296      return this.getFilteredTableDataByDate(
297        this.allLogs,
298        this.filterStartDate,
299        this.filterEndDate,
300      );
301    },
302    filteredLogs() {
303      return this.getFilteredTableData(
304        this.filteredLogsByDate,
305        this.activeFilters,
306      );
307    },
308  },
309  created() {
310    this.startLoader();
311    this.$store.dispatch('postCodeLogs/getPostCodesLogData').finally(() => {
312      this.endLoader();
313      this.isBusy = false;
314    });
315  },
316  methods: {
317    deleteAllLogs() {
318      this.$bvModal
319        .msgBoxConfirm(this.$t('pageEventLogs.modal.deleteAllMessage'), {
320          title: this.$t('pageEventLogs.modal.deleteAllTitle'),
321          okTitle: this.$t('global.action.delete'),
322          okVariant: 'danger',
323          cancelTitle: this.$t('global.action.cancel'),
324          autoFocusButton: 'cancel',
325        })
326        .then((deleteConfirmed) => {
327          if (deleteConfirmed) {
328            this.$store
329              .dispatch('postCodeLogs/deleteAllPostCodeLogs', this.allLogs)
330              .then((message) => this.successToast(message))
331              .catch(({ message }) => this.errorToast(message));
332          }
333        });
334    },
335    exportAllLogsString() {
336      {
337        return this.$store.getters['postCodeLogs/allPostCodes'].map(
338          (postCodes) => {
339            const allLogsString = JSON.stringify(postCodes);
340            return allLogsString;
341          },
342        );
343      }
344    },
345    onFilterChange({ activeFilters }) {
346      this.activeFilters = activeFilters;
347    },
348    onChangeDateTimeFilter({ fromDate, toDate }) {
349      this.filterStartDate = fromDate;
350      this.filterEndDate = toDate;
351    },
352    onFiltered(filteredItems) {
353      this.searchTotalFilteredRows = filteredItems.length;
354    },
355    // Create export file name based on date and action
356    exportFileNameByDate(value) {
357      let date = new Date();
358      date =
359        date.toISOString().slice(0, 10) +
360        '_' +
361        date.toString().split(':').join('-').split(' ')[4];
362      let fileName;
363      if (value === 'download') {
364        fileName = this.$t('pagePostCodeLogs.downloadFilePrefix');
365      } else if (value === 'export') {
366        fileName = this.$t('pagePostCodeLogs.exportFilePrefix');
367      } else {
368        fileName = this.$t('pagePostCodeLogs.allExportFilePrefix');
369      }
370      return fileName + date;
371    },
372  },
373};
374</script>
375