';
}).join('');
othersEl.hidden = false;
}).catch(function () {
// Nothing to show - the window works without it
});
}
// Merging: which way was picked, why, and whether the replies go too
othersEl.addEventListener('click', function (e) {
const pick = e.target.closest('[data-merge]');
if (pick && scheduling) {
const row = pick.closest('[data-other]');
const otherId = Number(row.dataset.other);
const otherRef = row.querySelector('a').textContent.split(' ')[0];
const keepThis = pick.dataset.merge === 'keep-this';
othersEl.querySelectorAll('[data-merge-form]').forEach(function (f) { f.remove(); });
const form = document.createElement('div');
form.className = 'bg-body-tertiary rounded p-2 mt-1';
form.setAttribute('data-merge-form', '');
form.dataset.child = String(keepThis ? otherId : scheduling.ticket.id);
form.dataset.parent = String(keepThis ? scheduling.ticket.id : otherId);
form.innerHTML = '
' + esc(keepThis ? otherRef : scheduling.ticket.reference) + ' is closed and merged into ' + esc(keepThis ? scheduling.ticket.reference : otherRef) + '.
'
+ ''
+ '
'
+ '
'
+ ''
+ '
';
row.appendChild(form);
form.querySelector('[data-merge-reason]').focus();
return;
}
if (e.target.closest('[data-merge-cancel]')) {
e.target.closest('[data-merge-form]').remove();
return;
}
const go = e.target.closest('[data-merge-go]');
if (go && scheduling) {
const form = go.closest('[data-merge-form]');
const child = Number(form.dataset.child);
go.disabled = true;
post({
dispatch_merge: 1,
child_id: child,
parent_id: form.dataset.parent,
comment: form.querySelector('[data-merge-reason]').value,
move_replies: form.querySelector('[data-merge-replies]').checked ? 1 : 0
}).then(function (json) {
toast(json.message, 'success');
if (child === scheduling.ticket.id) {
// This one is closed now - nothing left to book
bootstrap.Modal.getOrCreateInstance(scheduleModalEl).hide();
} else {
form.closest('[data-other]').remove();
if (!othersEl.querySelector('[data-other]')) {
othersEl.hidden = true;
}
}
loadQueue();
refreshBoard();
}).catch(function (error) {
go.disabled = false;
toast(error.message, 'error');
});
}
});
scheduleForm.addEventListener('submit', function (e) {
e.preventDefault();
if (!scheduling) {
return;
}
const button = scheduleForm.querySelector('[type=submit]');
button.disabled = true;
const tell = scheduleForm.elements.tell_client;
post({
dispatch_book: 1,
ticket_id: scheduling.ticket.id,
agent_id: scheduleForm.elements.agent_id.value,
start: scheduleForm.elements.start.value.replace('T', ' ') + ':00',
minutes: scheduleForm.elements.minutes.value,
onsite: scheduleForm.elements.onsite.value,
tell_client: tell ? (tell.checked ? 1 : 0) : 1
}).then(function (json) {
scheduling.done = true;
toast(json.message, 'success');
if (json.conflicts && json.conflicts.length) {
toast('Already booked then: ' + json.conflicts.join('; '), 'warning');
}
bootstrap.Modal.getOrCreateInstance(scheduleModalEl).hide();
reloadAll();
}).catch(function (error) {
scheduleError.textContent = error.message;
scheduleError.hidden = false;
}).finally(function () {
button.disabled = false;
});
});
scheduleModalEl.addEventListener('hidden.bs.modal', function () {
if (scheduling) {
const done = scheduling.done;
scheduling.resolve(done);
scheduling = null;
if (!done) {
refreshBoard(); // anything dragged goes back where it was
}
}
});
const confirmEl = document.getElementById('dispatchConfirmModal');
let confirming = null;
function confirmBox(title, text) {
return new Promise(function (resolve) {
confirming = {resolve: resolve, ok: false};
confirmEl.querySelector('[data-dispatch-confirm-title]').textContent = title;
confirmEl.querySelector('[data-dispatch-confirm-text]').textContent = text;
bootstrap.Modal.getOrCreateInstance(confirmEl).show();
});
}
confirmEl.querySelector('[data-dispatch-confirm-ok]').addEventListener('click', function () {
if (confirming) {
confirming.ok = true;
}
bootstrap.Modal.getOrCreateInstance(confirmEl).hide();
});
confirmEl.addEventListener('hidden.bs.modal', function () {
if (confirming) {
confirming.resolve(confirming.ok);
confirming = null;
}
});
function unbook(ticket) {
if (!canEdit) {
return;
}
confirmBox('Take ' + (ticket.reference || 'it') + ' off the schedule?', 'The agent - and the contact and watchers, when client emails are on - are sent the cancellation. It goes back to the queue.').then(function (ok) {
if (!ok) {
refreshBoard();
return;
}
post({dispatch_unbook: 1, ticket_id: ticket.id}).then(function (json) {
toast(json.message, 'success');
reloadAll();
}).catch(function (error) {
toast(error.message, 'error');
refreshBoard();
});
});
}
function moveEvent(props, start, end, allDay, from, to) {
post({
dispatch_event_move: 1, event_id: props.event_id, from: from, to: to, all_day: allDay ? 1 : 0,
start: ymd(start) + ' ' + (allDay ? '00:00' : hm(start)) + ':00',
end: end && !allDay ? ymd(end) + ' ' + hm(end) + ':00' : ''
}).then(function (json) {
toast(json.message, 'success');
refreshBoard();
}).catch(function (error) {
toast(error.message, 'error');
refreshBoard();
});
}
// ---------- the queue ----------
function ticketFromQueue(el) {
return queueTickets.find(function (t) {
return t.id === Number(el.dataset.ticket);
}) || {id: Number(el.dataset.ticket), reference: el.dataset.reference || ''};
}
function ticketFromItem(event, props) {
return {
id: Number(props.ticket_id),
reference: props.reference || '',
subject: event.title,
agent: Number(props.agent),
onsite: props.icon === 'fa-car' ? 1 : 0,
minutes: event.end && event.start ? Math.round((event.end - event.start) / 60000) : defaultMinutes
};
}
function loadQueue() {
request('GET', Object.assign({dispatch_queue: state.tab}, state.filters)).then(function (json) {
queueTickets = json.tickets || [];
Object.keys(json.counts || {}).forEach(function (key) {
const badge = root.querySelector('[data-dispatch-count="' + key + '"]');
if (badge) {
badge.textContent = json.counts[key] ? String(json.counts[key]) : '';
}
});
root.querySelectorAll('[data-dispatch-tab]').forEach(function (tab) {
tab.classList.toggle('active', tab.dataset.dispatchTab === state.tab);
});
if (!queueTickets.length) {
queueEl.innerHTML = '
' + esc({
unassigned: 'Every open ticket has an agent.',
unbooked: 'Nothing waiting - every ticket with an agent is booked.',
left_behind: 'Nothing left behind - every open ticket booked before today has been moved on or done.'
}[state.tab]) + '
';
return;
}
if (state.view === 'day') {
renderDay();
} else if (state.view === 'week') {
renderWeek();
} else {
renderWorkload();
}
}
// [scroll] opens the day at its first hour - a new day; a refresh keeps the place
function refreshBoard(scroll) {
if (state.view === 'day') {
loadItems().then(function (items) {
calendars.forEach(function (cal) {
cal.removeAllEventSources();
cal.addEventSource(items.filter(function (item) {
return Number(item.extendedProps.agent) === cal.dispatchAgent;
}));
});
dayTotals(items);
if (scroll === true) {
requestAnimationFrame(scrollDay);
}
});
} else {
render();
}
}
function reloadAll() {
loadQueue();
refreshBoard();
loadStats();
}
// An item drawn as on the calendar page: time, icon, title, and where / who
function itemContent(arg) {
const props = arg.event.extendedProps || {};
const wrap = document.createElement('div');
wrap.className = 'itflow-cal-event ' + (arg.event.allDay ? 'is-daygrid' : 'is-timegrid');
// Onsite work stands out - an orange strip with a car across the top, as on the calendar
if (props.icon === 'fa-car') {
wrap.classList.add('is-onsite');
if (!arg.event.allDay) {
const strip = document.createElement('div');
strip.className = 'itflow-cal-onsite';
strip.innerHTML = 'Onsite';
wrap.appendChild(strip);
}
}
if (arg.timeText && !arg.event.allDay) {
const time = document.createElement('span');
time.className = 'itflow-cal-time';
time.textContent = arg.timeText;
wrap.appendChild(time);
}
if (props.icon) {
const icon = document.createElement('i');
icon.className = 'fas fa-fw ' + props.icon + ' itflow-cal-icon';
wrap.appendChild(icon);
}
const title = document.createElement('span');
title.className = 'itflow-cal-title';
title.textContent = arg.event.title;
wrap.appendChild(title);
if (props.detail && !arg.event.allDay) {
const detail = document.createElement('div');
detail.className = 'itflow-cal-detail';
detail.textContent = props.detail;
wrap.appendChild(detail);
}
return {domNodes: [wrap]};
}
// The hours the day's grid shows - the working day, with room either side
function slotRange() {
if (zone || !businessHours || businessHours.startTime === '00:00') {
return ['00:00:00', '24:00:00'];
}
const start = businessHours.startTime < '06:00' ? businessHours.startTime : '06:00';
const end = businessHours.endTime > '21:00' ? businessHours.endTime : '21:00';
return [start + ':00', end === '24:00' ? '24:00:00' : end + ':00'];
}
// Day: a time grid for each agent, side by side
function renderDay() {
const shown = shownAgents();
board.innerHTML = '
' + shown.map(function (a) {
return '
'
+ dot(a.color) + esc(a.name) + '
';
}).join('') + '
';
const slots = slotRange();
board.querySelectorAll('.itflow-dispatch-col').forEach(function (col, index) {
const agentId = Number(col.dataset.agent);
const cal = new FullCalendar.Calendar(col.querySelector('[data-dispatch-cal]'), {
initialView: 'timeGridDay',
initialDate: ymd(state.date),
headerToolbar: false,
dayHeaders: false,
allDaySlot: true,
allDayText: '',
height: 'auto',
slotMinTime: slots[0],
slotMaxTime: slots[1],
now: zone ? zoneNow : undefined,
slotDuration: '00:30:00',
snapDuration: '00:15:00',
slotEventOverlap: false,
nowIndicator: true,
editable: canEdit,
droppable: canEdit,
eventDurationEditable: canEdit,
// The company's hours mean nothing on another clock - left unshaded there
businessHours: zone ? false : (businessHours || false),
// The times down the side once, on the first column - the others keep a blank the
// label's height, so the rows line up across
slotHeaderContent: function (arg) {
return index === 0 ? arg.text : '\u00a0';
},
eventContent: itemContent,
eventDidMount: function (info) {
const props = info.event.extendedProps || {};
info.el.dataset.kind = props.kind || '';
info.el.setAttribute('title', info.event.title + (props.detail ? '\n' + props.detail : ''));
},
eventClick: function (info) {
info.jsEvent.preventDefault();
const props = info.event.extendedProps || {};
if (props.modal) {
openModal(props.modal);
}
},
// A drag over empty time: New Ticket for this agent, booked for the time dragged over -
// a drag, not a click; saving it comes back here on that day
selectable: canEdit,
selectMirror: true,
selectMinDistance: 5,
selectAllow: function (info) {
return !info.allDay;
},
select: function (info) {
cal.unselect();
const params = new URLSearchParams({
assigned_to: String(agentId),
schedule: ymd(info.start) + 'T' + hm(info.start),
schedule_minutes: String(Math.round((info.end - info.start) / 60000)),
return_to: 'dispatch'
});
openModal('modals/ticket/ticket_add.php?' + params.toString());
},
// From the queue - a booking from another agent's column comes in by eventReceive
drop: function (info) {
if (!queueEl.contains(info.draggedEl)) {
return;
}
const start = new Date(info.date.getTime());
if (info.allDay) {
const parts = businessStart().split(':');
start.setHours(Number(parts[0]), Number(parts[1]), 0, 0);
}
schedule(ticketFromQueue(info.draggedEl), start, agentId);
},
// To another time, the same agent
eventDrop: function (info) {
const props = info.event.extendedProps || {};
if (props.kind === 'event') {
moveEvent(props, info.event.start, info.event.end, info.event.allDay, agentId, agentId);
return;
}
schedule(ticketFromItem(info.event, props), info.event.start, agentId);
},
eventResize: function (info) {
const props = info.event.extendedProps || {};
if (props.kind === 'event') {
moveEvent(props, info.event.start, info.event.end, false, agentId, agentId);
return;
}
const ticket = ticketFromItem(info.event, props);
schedule(ticket, info.event.start, agentId, ticket.minutes);
},
// From another agent's column
eventReceive: function (info) {
const props = info.event.extendedProps || {};
if (props.kind === 'event') {
moveEvent(props, info.event.start, info.event.end, info.event.allDay, Number(props.agent), agentId);
return;
}
schedule(ticketFromItem(info.event, props), info.event.start, agentId);
},
// Back onto the queue
eventDragStart: function () {
queueEl.classList.add('is-drop-target');
},
eventDragStop: function (info) {
queueEl.classList.remove('is-drop-target');
const props = info.event.extendedProps || {};
if (props.kind === 'ticket' && overQueue(info.jsEvent)) {
unbook(ticketFromItem(info.event, props));
}
}
});
cal.dispatchAgent = agentId;
cal.render();
calendars.push(cal);
});
if (canEdit && FullCalendar.Interaction && FullCalendar.Interaction.Draggable) {
queueDraggable = new FullCalendar.Interaction.Draggable(queueEl, {
itemSelector: '.itflow-dispatch-item',
eventData: function (item) {
const minutes = ticketFromQueue(item).minutes || defaultMinutes;
return {title: item.dataset.reference, duration: pad(Math.floor(minutes / 60)) + ':' + pad(minutes % 60), create: false, color: '#6c757d'};
}
});
}
refreshBoard(true);
}
// The hour to open the day at: the working day's start - or, when the board runs around the clock,
// an hour before now today and 8am on other days
function scrollHour() {
if (slotRange()[0] !== '00:00:00') {
return Number(businessStart().split(':')[0]);
}
if (ymd(state.date) === ymd(today())) {
return Math.max(0, (zone ? parseDateTime(zoneNow()) : new Date()).getHours() - 1);
}
return 8;
}
// One scroller for every column - opened at scrollHour(), once the bookings are in
function scrollDay() {
const scroller = board.querySelector('.itflow-dispatch-cols');
const slot = scroller ? scroller.querySelector('.itflow-dispatch-col [data-time="' + pad(scrollHour()) + ':00:00"]') : null;
if (slot) {
const head = scroller.querySelector('.itflow-dispatch-col-head');
scroller.scrollTop += slot.getBoundingClientRect().top - scroller.getBoundingClientRect().top - (head ? head.offsetHeight : 0) - 4;
}
}
function dayTotals(items) {
board.querySelectorAll('.itflow-dispatch-col').forEach(function (col) {
let minutes = 0;
items.forEach(function (item) {
if (Number(item.extendedProps.agent) === Number(col.dataset.agent) && ['ticket', 'helper'].indexOf(item.extendedProps.kind) !== -1 && !item.allDay) {
minutes += minutesBetween(item.start, item.end);
}
});
col.querySelector('[data-dispatch-booked]').textContent = minutes ? lengthText(minutes) + ' booked' : '';
});
}
// Week: a row for each agent, a column for each day
function renderWeek() {
const start = range()[0];
const days = [];
for (let i = 0; i < 7; i++) {
const d = addDays(start, i);
if (state.weekends || (d.getDay() !== 0 && d.getDay() !== 6)) {
days.push(d);
}
}
board.innerHTML = '
Loading...
';
loadItems().then(function (items) {
const now = ymd(today());
let html = '
';
board.querySelectorAll('.itflow-dispatch-chip').forEach(function (chip) {
chip.addEventListener('click', function () {
if (chip.dataset.modal) {
openModal(chip.dataset.modal);
}
});
});
if (!canEdit || typeof Sortable === 'undefined') {
return;
}
board.querySelectorAll('.itflow-dispatch-cell-list').forEach(function (cell) {
sortables.push(Sortable.create(cell, {
group: {name: 'dispatch', pull: true, put: true},
draggable: '.is-movable',
sort: false,
onAdd: function (evt) {
const el = evt.item;
const agentId = Number(cell.dataset.agent);
const day = parseYmd(cell.dataset.date);
const from = evt.from;
el.remove();
if (from === queueEl) {
// From the queue: the start of the working day
const parts = businessStart().split(':');
day.setHours(Number(parts[0]), Number(parts[1]), 0, 0);
schedule(ticketFromQueue(el), day, agentId);
return;
}
const was = parseDateTime(el.dataset.start) || day;
day.setHours(was.getHours(), was.getMinutes(), 0, 0);
const fromAgent = Number(from.dataset.agent);
if (el.dataset.kind === 'event') {
const length = Number(el.dataset.minutes) * 60000;
moveEvent({event_id: Number(el.dataset.event)}, day, length ? new Date(day.getTime() + length) : null, el.dataset.allDay === '1', fromAgent, agentId);
return;
}
schedule({id: Number(el.dataset.ticket), reference: el.dataset.reference, subject: el.title.split('\n')[0], onsite: Number(el.dataset.onsite), agent: fromAgent},
day, agentId, Number(el.dataset.minutes) || defaultMinutes);
}
}));
});
// The queue takes from the board (to take a booking off) and gives to it
sortables.push(Sortable.create(queueEl, {
group: {name: 'dispatch', pull: 'clone', put: true},
draggable: '.itflow-dispatch-item.is-movable, .itflow-dispatch-chip',
sort: false,
onAdd: function (evt) {
const el = evt.item;
el.remove();
if (el.dataset.kind === 'ticket') {
unbook({id: Number(el.dataset.ticket), reference: el.dataset.reference});
} else {
refreshBoard();
}
}
}));
}).catch(function (error) {
board.innerHTML = '
' + esc(error.message) + '
';
});
}
// Workload: each agent's open tickets, SLAs and booked hours - drop a ticket on an agent to give it to them
function bar(minutes, capacity) {
const pct = capacity ? Math.min(100, Math.round(minutes / capacity * 100)) : 0;
const tone = capacity && minutes > capacity ? 'bg-danger' : (pct >= 85 ? 'bg-warning' : 'bg-primary');
return '
Team average: ' + esc(json.team.open) + ' open, ' + esc(lengthText(json.team.booked_week) || '0 min') + ' booked this week. Click an agent for their tickets'
+ (canEdit ? ' - drop a ticket from the queue on one to give it to them.' : '.') + '