Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <script>
- jQuery(document).on('ready', async function(){
- try {
- document.getElementById("show_request_for").remove()
- } catch {
- console.log('No elements to remove')
- }
- // document.getElementById("add-cc-button").remove()
- console.log('[INIT]')
- if (window.location.pathname === "/support/catalog/items/136" || window.location.pathname === "/support/catalog/items/149") {
- const durationList = {
- "...": false,
- "Full day": true,
- "Half day": true,
- "Short visit (up to 2 hours)": false
- }
- const officeList = {
- "...": false,
- "Toronto": true,
- "Lviv": true,
- "Lab64": true,
- "Lab72": true,
- "Lab72 / 1": false,
- "Rancho 1": false,
- "Rancho 2": false,
- "QA Studio": false,
- "New QA Studio": false,
- "Community": false,
- "Lab62": true
- }
- const officeMeido = {
- "...": false,
- "Toronto": true,
- "Lviv": false,
- "Lab64": true,
- "Lab72": true,
- "Lab72 / 1": false,
- "Rancho 1": false,
- "Rancho 2": false,
- "QA Studio": false,
- "New QA Studio": false,
- "Community": false,
- "Lab62": true
- }
- const officeCapacity = ["Toronto","Lab64","Lab62"]
- const officeAddress = {
- "...": "",
- "Toronto": "м. Київ, вул. Велика Васильківська 100, 8 поверх",
- "Lviv": "м. Львів, вул. Поповича, 9",
- "Lab64": "м. Київ, вул. Велика Васильківська 64",
- "Lab72": "м. Київ, вул. Велика Васильківська 72",
- "Lab72 / 1": "м. Київ, вул. Велика Васильківська 72",
- "Rancho 1": "м. Київ, пров. Малокитаївський, 12",
- "Rancho 2": "м. Київ, вул. Травнева 28",
- "QA Studio": "м. Київ, вул. Північно-Сирецька 1-3",
- "New QA Studio": "м. Київ, просп. Перемоги 53",
- "Community": "м. Київ, вул. Євгена Коновальця 44, 2 поверх",
- "Lab62": "м. Київ, вул. Велика Васильківська 62"
- }
- const accessWeek = {
- "...": false,
- "Current week": true,
- "Next week": true
- }
- const mealTypes = [
- "Non-vegan",
- "Vegan"
- ]
- var fsFields
- if (window.location.pathname === "/support/catalog/items/136") {
- fsFields = {
- duration: "requested_item_values_136_requested_item_value_attributes_cf_visit_duration_270753",
- support_with_lunch: "requested_item_values_136_requested_item_value_attributes_cf_support_with_lunch_270753",
- access_week: "requested_item_values_136_requested_item_value_attributes_cf_access_type_270753",
- lunch_type: "requested_item_values_136_requested_item_value_attributes_cf_select_your_meal_preference_270753",
- office: "requested_item_values_136_requested_item_value_attributes_cf_office_270753",
- dates: [
- "requested_item_values_136_requested_item_value_attributes_cf_day1_270753_date",
- "requested_item_values_136_requested_item_value_attributes_cf_day2_270753_date",
- "requested_item_values_136_requested_item_value_attributes_cf_day3_270753_date",
- "requested_item_values_136_requested_item_value_attributes_cf_day4_270753_date",
- "requested_item_values_136_requested_item_value_attributes_cf_day5_270753_date",
- "requested_item_values_136_requested_item_value_attributes_cf_day6_270753_date",
- "requested_item_values_136_requested_item_value_attributes_cf_day7_270753_date" //ДОБАВИТЬ ДОПОЛНИТЕЛЬНІЕ ДНИ - скопировать айдишники каждого поля_ РЕАЛЬНІЙ РЕКВЕСТ//
- ],
- additional_locations: [
- "requested_item_values_136_requested_item_value_attributes_cf_do_you_plan_to_visit_any_additional_location_during_the_requested_period_nbsp_270753",
- "requested_item_values_136_requested_item_value_attributes_cf_additional_location_2_270753"
- ],
- meido: "requested_item_values_136_requested_item_value_attributes_cf_meido_body_270753",
- document_text: "requested_item_values_136_requested_item_value_attributes_cf__270753",
- document_check: "requested_item_values_136_requested_item_value_attributes_cf_v_270753",
- addloc: "",
- addloc_text: ""
- }
- } else if (window.location.pathname === "/support/catalog/items/149") {
- fsFields = {
- duration: "requested_item_values_149_requested_item_value_attributes_cf_visit_duration_270753",
- support_with_lunch: "requested_item_values_149_requested_item_value_attributes_cf_support_with_lunch_270753",
- access_week: "requested_item_values_149_requested_item_value_attributes_cf_access_type_270753",
- lunch_type: "requested_item_values_149_requested_item_value_attributes_cf_select_your_meal_preference_270753",
- office: "requested_item_values_149_requested_item_value_attributes_cf_office_270753",
- dates: [
- "requested_item_values_149_requested_item_value_attributes_cf_day1_270753_date",
- "requested_item_values_149_requested_item_value_attributes_cf_day2_270753_date",
- "requested_item_values_149_requested_item_value_attributes_cf_day3_270753_date",
- "requested_item_values_149_requested_item_value_attributes_cf_day4_270753_date",
- "requested_item_values_149_requested_item_value_attributes_cf_day5_270753_date" //ДОБАВИТЬ ДОПОЛНИТЕЛЬНІЕ ДНИ - скопировать айдишники каждого поля_ТЕСТОВІЙ РЕКВЕСТ//
- ],
- additional_locations: [
- "requested_item_values_149_requested_item_value_attributes_cf_do_you_plan_to_visit_any_additional_location_during_the_requested_period_nbsp_270753",
- "requested_item_values_149_requested_item_value_attributes_cf_additional_location_2_270753"
- ],
- meido: "requested_item_values_149_requested_item_value_attributes_cf_meido_body_270753",
- document_text: "requested_item_values_149_requested_item_value_attributes_cf__270753",
- document_check: "requested_item_values_149_requested_item_value_attributes_cf_v_270753",
- addloc: "",
- addloc_text: ""
- }
- }
- // -------------------------
- var meidoActive
- if (window.location.pathname === "/support/catalog/items/136") {
- meidoActive = false
- } else if (window.location.pathname === "/support/catalog/items/149") {
- meidoActive = true
- }
- meidoToken = "test"
- // -------------------------
- // -------------------------
- var capacityActive
- if (window.location.pathname === "/support/catalog/items/136") {
- capacityActive = true //замсемнить ФОЛс на ТРУ чтоб включить капасити в боевом. реквесте//
- } else if (window.location.pathname === "/support/catalog/items/149") {
- capacityActive = true
- }
- // -------------------------
- // ====================================================================
- // ====================================================================
- // ====================================================================
- const fsNative = {
- duration: document.getElementById(fsFields.duration),
- support_with_lunch: document.getElementById(fsFields.support_with_lunch).parentNode.childNodes.item(0),
- access_week: document.getElementById(fsFields.access_week),
- lunch_type: document.getElementById(fsFields.lunch_type),
- office: document.getElementById(fsFields.office),
- meido: document.getElementById(fsFields.meido),
- dates: getElemList(fsFields.dates),
- additional_locations: getElemList(fsFields.additional_locations),
- document_text: document.getElementById(fsFields.document_text),
- document_check: document.getElementById(fsFields.document_check).parentNode.childNodes.item(0),
- addloc: document.getElementById(fsFields.addloc),
- addloc_text: document.getElementById(fsFields.addloc_text)
- }
- var activeDateCount = 0
- const today = new Date()
- const todayGlobal = today.toLocaleDateString()
- const weekdayGlobal = today.getDay()
- const currentHoursGlobal = today.getHours()
- const currentMinutesGlobal = today.getMinutes()
- var selectedDatesGlobal = []
- var capacityCheck = true
- var additionalLocationInfo = {}
- var addLocationTable
- var lastSelectedOffice
- const durationSelector = replaceInputWithDropdown(fsFields.duration, durationList, "duration")
- durationSelector.parentNode.hidden = true
- const officeSelector = replaceInputWithDropdown(fsFields.office, officeList, "office")
- const accessWeekSelector = replaceInputWithDropdown(fsFields.access_week, accessWeek, "access-week")
- const lunchTypeSelector = createSimplifiedDropdown(fsFields.lunch_type, mealTypes, "lunch_type")
- const lunchCheckboxLabel = document.createTextNode("Please support me with lunch") // to add text Lunch will be provided in case your visit durayion is more than 2 hours//
- const lunchCheckbox = createCustomCheckbox(document.getElementById(fsFields.support_with_lunch).parentNode, "show-lunch", lunchCheckboxLabel)
- const dateList = createCustomDates(fsNative.dates)
- const additionalOfficesList = createAdditionalOfficeSelectors(fsFields.additional_locations, officeList)
- const capacityDisplay = createCapacityDisplay(fsNative.dates[0].parentNode.parentNode)
- //--- capacity ---
- if (capacityActive) {
- fsNative.addloc.parentNode.hidden = true
- fsNative.addloc_text.parentNode.hidden = true
- fsNative.additional_locations.forEach(elem => { elem.parentNode.hidden = true })
- }
- //add hotDeskCheckbox
- const hotdeskCheckboxLabel = document.createTextNode("I don`t have a permanent seat and would like to book a hot desk.");
- const hotdeskCheckboxContainer = document.createElement('div');
- document.getElementById(fsFields.office).parentNode.appendChild(hotdeskCheckboxContainer);
- const hotdeskCheckbox = createCustomCheckbox(hotdeskCheckboxContainer, "show-hotdesk", hotdeskCheckboxLabel);
- hotdeskCheckbox.checked = false;
- const hotdeskText = document.createElement("p");
- hotdeskText.innerHTML = "Please, follow the <a href='https://ringukraine.officespacesoftware.com/visual-directory/floors/139' style='color:blue;cursor:pointer;' target='_blank'>link</a> for hot desks booking system (applicable only for Full/half-day visit). Here`re <a href='https://docs.google.com/document/d/1llpCz3RbK0cBew7kSJhZPQwD5Om8Kgj0tTq-1kgONx4/edit' style='color:blue;cursor:pointer;' target='_blank'>instructions</a> on how to make a booking.";
- hotdeskCheckboxContainer.appendChild(hotdeskText);
- const documentCheckboxLabel = document.createElement("span")
- documentCheckboxLabel.innerHTML = "Я, {{ current_user.phone }}, ознайомився з документом та підтверджую що мій стан відповідає нормам відвідування офісу згідно з заявою.<br>*[✓] <i>означає, що дана відмітка прирівнюється до власноручного/факсимільного відтворення підпису особи.</i>"
- const documentCheckbox = createCustomCheckbox(fsNative.document_check.parentNode, "document-check", documentCheckboxLabel)
- const documentText = createDocumentSection(fsNative.document_text, todayGlobal)
- const dateControlAdd = document.createElement("button")
- dateControlAdd.innerHTML = "+"
- const dateControlRemove = document.createElement("button")
- dateControlRemove.innerHTML = "-"
- lunchCheckbox.parentNode.hidden = true;
- lunchTypeSelector.parentNode.hidden = true;
- hotdeskCheckboxContainer.hidden = true;
- hotdeskText.hidden = true;
- //durationSelector.addEventListener("change", function(){ renderController() })
- officeSelector.addEventListener("change", function(){ renderController() })
- accessWeekSelector.addEventListener("change", function(){ renderController() })
- lunchCheckbox.addEventListener("change", function(){ renderController() })
- hotdeskCheckbox.addEventListener("change", function(){ renderController() })
- lunchTypeSelector.addEventListener("change", function(){ renderController() })
- dateList.forEach(dateElem => {
- jQuery(dateElem).datepicker("option", {
- onSelect: function() {
- renderController()
- }
- })
- })
- dateControlAdd.addEventListener("click", function(e){
- e.preventDefault()
- activeDateCount += 1
- renderController()
- })
- dateControlRemove.addEventListener("click", function(e){
- e.preventDefault()
- activeDateCount -= 1
- renderController()
- })
- additionalOfficesList.forEach(elem => {
- elem.addEventListener("change", function(){ renderController() })
- })
- documentCheckbox.addEventListener("change", function(){ renderController() })
- var meidoMenu
- document.getElementById(fsFields.meido).parentNode.style.display = "none"
- if (meidoActive) {
- const elems = document.getElementsByClassName("main pull-left")
- meidoMenu = await meidoInit(elems[0], dateList, fsFields.meido, 125, false) // change 125 to required limit
- meidoMenu.hidden = true
- renderController()
- } else {
- renderController()
- }
- jQuery("input[type=\"submit\"]").each((index, elem) => {
- elem.onclick = function(e){
- if (!capacityCheck) {
- e.stopImmediatePropagation()
- e.preventDefault()
- alert("Please check the capactiy for selected dates") //поменять нотифай если нужно!//
- }
- }
- })
- function renderController(){
- var values = {
- duration: "Full day",
- office: officeSelector.value,
- access_week: accessWeekSelector.value
- }
- fsNative.duration.value = values.duration === "..." ? "" : values.duration
- fsNative.office.value = values.office === "..." ? "" : values.office
- if (capacityActive) {
- if (values.office === "...") {
- lastSelectedOffice = values.office
- for (let elem of document.getElementsByClassName("addtable-container")) {
- elem.innerHTML = ""
- }
- additionalLocationInfo = {}
- populateAddLocation()
- }
- if (values.office !== "..." && values.office !== lastSelectedOffice) {
- lastSelectedOffice = values.office
- addLocationTable = buildAddLocationTable(values.office)
- const addTableContainers = document.getElementsByClassName("addtable-container")
- var index = 1
- for (let elem of addTableContainers) {
- elem.innerHTML = ""
- const table = addLocationTable.cloneNode(true)
- console.log(table.querySelectorAll('.add-office-label'))
- for (let elem of table.querySelectorAll('.add-office-label')) {
- elem.htmlFor = elem.htmlFor + "_" + index
- }
- for (let elem of table.querySelectorAll('.add-office-checkbox')) {
- elem.id = elem.id + "_" + index
- elem.onclick = function(){ handleAddLocation(this) }
- }
- ++index
- elem.appendChild(table)
- }
- additionalLocationInfo = {}
- populateAddLocation()
- }
- }
- if (fsNative.office.value === 'Toronto') {
- hotdeskCheckboxContainer.hidden = false;
- } else {
- hotdeskCheckbox.checked = false;
- hotdeskCheckboxContainer.hidden = true;
- }
- if (!hotdeskCheckbox.checked) {
- hotdeskText.hidden = true;
- } else {
- hotdeskText.hidden = false;
- }
- const accessWeekChanged = fsNative.access_week.value === values.access_week ? false : true
- fsNative.access_week.value = values.access_week === "..." ? "" : values.access_week
- var datesInRequest = dateList.map(x => x.value).filter(x => !!x)
- if (activeDateCount === 0) datesInRequest = datesInRequest[0] ? [datesInRequest[0]] : []
- const today = new Date().toISOString().split("T")[0]
- if (durationList[values.duration] && officeList[values.office] && accessWeek[values.access_week] && datesInRequest.length && !(datesInRequest.length === 1 && datesInRequest[0] === today) && !accessWeekChanged) {
- lunchCheckbox.parentNode.hidden = false
- } else {
- lunchCheckbox.parentNode.hidden = true
- lunchCheckbox.checked = false
- }
- values.support_with_lunch = lunchCheckbox.checked
- fsNative.support_with_lunch.value = lunchCheckbox.checked ? "1" : "0"
- if (values.support_with_lunch) {
- if (meidoActive) {
- if (weekdayGlobal === 6 || weekdayGlobal === 0 || (weekdayGlobal === 5 && currentHoursGlobal >= 19 && currentMinutesGlobal >= 30) || values.access_week === "Current week" || !officeMeido[values.office]) {
- lunchTypeSelector.parentNode.hidden = false
- lunchTypeSelector.value = lunchTypeSelector.value ? lunchTypeSelector.value : mealTypes[0]
- meidoMenu.hidden = true
- } else {
- lunchTypeSelector.parentNode.hidden = true
- lunchTypeSelector.value = null
- meidoMenu.hidden = false
- }
- } else {
- lunchTypeSelector.parentNode.hidden = false
- lunchTypeSelector.value = lunchTypeSelector.value ? lunchTypeSelector.value : mealTypes[0]
- }
- } else {
- lunchTypeSelector.parentNode.hidden = true
- lunchTypeSelector.value = null
- if (meidoActive) meidoMenu.hidden = true
- }
- values.lunch_type = lunchTypeSelector.value
- fsNative.lunch_type.value = values.lunch_type ? values.lunch_type : ""
- const dateLimits = (values.access_week === "...") ? null : calcDateLimits(values.access_week === "Current week" ? true : false)
- const dateLimitsRaw = dateLimits ? dateLimits.map(x => new Date(x).valueOf()) : null
- var existingDates = []
- var lastUsedFound = false;
- if (accessWeekChanged) activeDateCount = 0
- dateList.forEach((dateElem, index) => {
- const dateNativeElem = fsNative.dates[index]
- const timeNativeElem = document.getElementById(fsFields.dates[index].substring(0, fsFields.dates[index].length - 4) + "time")
- const errorElem = document.getElementById("date_custom_" + (index+1) + "-error")
- if (errorElem) errorElem.style.display = "none"
- if (accessWeekChanged && index === 0) dateElem.value = null
- const dateRawValue = new Date(dateElem.value).valueOf()
- if (existingDates.includes(dateRawValue)) dateElem.value = null
- if (dateLimits) {
- jQuery("#date_custom_"+(index+1)).datepicker("option", {
- minDate: new Date(dateLimits[0]),
- maxDate: new Date(dateLimits[1])
- })
- dateElem.disabled = false
- if (dateRawValue < dateLimitsRaw[0] || dateRawValue > dateLimitsRaw[1]) dateElem.value = null
- } else {
- dateElem.disabled = true
- }
- existingDates.push(dateRawValue)
- const controlWrapper = document.getElementById("controls_" + index)
- controlWrapper.innerHTML = ""
- const addLocations = document.getElementById("addtable_" + (index+1)).querySelectorAll('.add-office-checkbox')
- if (dateElem.value && dateElem.value !== "") {
- dateNativeElem.value = reverseForFS(dateElem.value)
- timeNativeElem.value = "00:00"
- if (capacityActive) document.getElementById("addtable_wrapper_" + (index+1)).style.display = "block"
- } else {
- dateNativeElem.value = null
- timeNativeElem.value = null
- if (capacityActive) {
- document.getElementById("addtable_wrapper_" + (index+1)).style.display = "none"
- for (let checkbox of addLocations) {
- checkbox.checked = false
- }
- }
- }
- controlWrapper.style.display = "inline-block"
- if (index < activeDateCount) {
- dateElem.disabled = true
- dateElem.parentNode.style.display = "block"
- } else if (index === activeDateCount) {
- if (dateLimits) dateElem.disabled = false
- if (index > 0 && dateList[index-1].value) {
- const nextDate = new Date(dateList[index-1].value)
- nextDate.setDate(nextDate.getDate() + 1)
- jQuery("#date_custom_"+(index+1)).datepicker("option", {
- minDate: nextDate
- })
- }
- dateElem.parentNode.style.display = "block"
- if (activeDateCount > 0) controlWrapper.appendChild(dateControlRemove)
- if (activeDateCount < dateList.length-1) {
- controlWrapper.appendChild(dateControlAdd)
- dateControlAdd.disabled = !dateElem.value
- }
- } else {
- dateElem.parentNode.style.display = "none"
- dateElem.value = null
- dateNativeElem.value = null
- timeNativeElem.value = null
- }
- })
- if (capacityActive === true) {
- const selectedDates = dateList.map(x => x.value).filter(x => !!x)
- for (let date in additionalLocationInfo) {
- if (!selectedDates.includes(date)) delete additionalLocationInfo[date]
- }
- populateAddLocation()
- if (selectedDates.length && JSON.stringify(selectedDates) !== selectedDatesGlobal) {
- fetch(`https://freshservicecounter.ringteam.com/v2/getcapacity?office=${JSON.stringify(officeCapacity)}&dates=${JSON.stringify(selectedDates)}`)
- .then(res => {
- return res.json()
- })
- .then(res => {
- // main capacity
- for (let officeName in res) {
- if (values.office === officeName) {
- capacityDisplay.innerHTML = ""
- const office = document.createElement("div")
- office.innerHTML = `<b>Office:</b> ${officeName}`
- const limit = document.createElement("div")
- limit.innerHTML = `<b>Limit:</b> ${res[officeName].limit} visitors per day`
- limit.style.borderBottom = "1px dotted grey"
- capacityDisplay.appendChild(office)
- capacityDisplay.appendChild(limit)
- var capacityDataArray = []
- for (let date in res[officeName].capacity) {
- capacityDataArray.push({ date: date, capacity: res[officeName].capacity[date] })
- }
- capacityDataArray.sort((x,y) => { return x.date > y.date ? 1 : -1 })
- capacityCheck = true
- capacityDataArray.forEach(obj => {
- const dateElem = document.createElement("div")
- dateElem.innerHTML = `<b>${obj.date}:</b> ${obj.capacity} visitors confirmed`
- //console.log(obj.capacity, res.limit)
- if (obj.capacity / res[officeName].limit >= 0.7) dateElem.style.color = "orange"
- if (obj.capacity >= res[officeName].limit) {
- dateElem.style.color = "red"
- capacityCheck = false
- }
- capacityDisplay.appendChild(dateElem)
- })
- capacityDisplay.hidden = false
- } else {
- //additional capacity
- dateList.forEach(dateElem => {
- var elem = dateElem.parentNode.getElementsByClassName("capacity_" + officeName)[0]
- elem.innerHTML = `${res[officeName].capacity[dateElem.value]}/${res[officeName].limit} confirmed`
- })
- }
- }
- })
- } else {
- capacityDisplay.hidden = true
- capacityCheck = capacityDisplay.hidden
- }
- selectedDatesGlobal = JSON.stringify(selectedDates)
- }
- if (meidoActive && values.access_week === "Next week") {
- meidoCart.calcDateCollection()
- } else {
- fsNative.meido.innerHTML = null
- }
- values.additional_offices = []
- additionalOfficesList.forEach((elem, index) => {
- values.additional_offices.push(elem.value)
- if ((index === 0 && values.office !== "...") || (index > 0 && values.additional_offices[index-1] !== "...")) {
- elem.parentNode.style.display = "block"
- } else {
- elem.parentNode.style.display = "none"
- elem.value = "..."
- }
- fsNative.additional_locations[index].value = elem.value === "..." ? null : elem.value
- })
- values.document_check = documentCheckbox.checked
- fsNative.document_check.value = documentCheckbox.checked ? "1" : "0"
- fsNative.document_check.checked = documentCheckbox.checked
- const documentLocations = [values.office, values.additional_offices].flat().map(x => officeAddress[x]).filter(x => !!x).join(", ")
- document.getElementById("doc-address").innerHTML = documentLocations
- // =================================================
- var text = `Заява на допуск до користування Простором Товариства з обмеженою відповідальністю «ТекХостинг» (далі – ТОВ «ТекХостинг»)
- Я, фізична особа-підприємець ${"{{ current_user.phone }}"}, прошу допустити мене до користування офісним простором ТОВ «ТекХостинг» (далі – Простір), що знаходиться за адресою: ${documentLocations}.
- Я підтверджую, що на момент надання мені доступу до користування Простором:
- • у мене відсутні будь-які ознаки ГРВІ, а саме: підвищена температура тіла (більше 37,2 С), кашель, утруднене дихання тощо;
- • я ознайомлений(а) з рекомендаціями МОЗ та ВООЗ щодо попередження зараження COVID-19 та їх дотримуюсь;
- • протягом останніх 14 днів я не перебував(ла) за межами України та не контактував(ла) з особами, щодо яких наявна підозра/хворими на COVID-19.
- Я зобов’язуюсь під час користування Простором дотримуватися посилених санітарно-гігієнічних норм, а також рекомендацій МОЗ та ВООЗ щодо запобігання поширенню COVID-19, а саме:
- • носити медичну маску/респіратор;
- • ретельно мити руки з милом протягом 20-40 сек. та регулярно обробляти їх антисептичним засобом під час перебування в Просторі;
- • дотримуватися дистанції min 1,5 (півтора) метри від інших відвідувачів Простору.
- Дата: ${todayGlobal}`
- // =================================================
- fsNative.document_text.value = text
- }
- function buildAddLocationTable(excluded){
- const table = document.createElement('table')
- table.style.margin = "10px"
- const row = document.createElement('tr')
- row.style.width = "800px"
- row.style.display = "block"
- table.appendChild(row)
- var cellCount = 0
- for (let office in officeList) {
- if (office !== "..." && office !== excluded) {
- var currentRow
- if (cellCount <= 2) {
- currentRow = table.childNodes[table.childNodes.length - 1]
- ++cellCount
- } else {
- currentRow = document.createElement('tr')
- table.appendChild(currentRow)
- cellCount = 1
- }
- const cell = document.createElement('td')
- cell.style.display = "inline-flex"
- const label = document.createElement('label')
- label.htmlFor = office
- label.className += "add-office-label"
- label.innerHTML = office
- const checkbox = document.createElement('input')
- checkbox.type = "checkbox"
- checkbox.id = office
- checkbox.className += "add-office-checkbox"
- //checkbox.style.display = "inline-block"
- checkbox.style.marginRight = "5px"
- const capacity = document.createElement('span')
- capacity.className += "capacity_" + office
- //capacity.style.display = "inline-block"
- capacity.style.marginLeft = "10px"
- cell.appendChild(checkbox)
- cell.appendChild(label)
- cell.appendChild(capacity)
- cell.style.width = "33%"
- currentRow.appendChild(cell)
- }
- }
- return table
- }
- function handleAddLocation(elem){
- console.log('called')
- console.log(elem)
- const dateId = elem.id[elem.id.length - 1]
- console.log(dateId)
- const locationName = elem.id.substring(0, elem.id.length - 2)
- console.log(locationName)
- const dateElem = document.getElementById("date_custom_" + dateId)
- console.log(dateElem.value)
- if (elem.checked) {
- if (!additionalLocationInfo[dateElem.value]) additionalLocationInfo[dateElem.value] = []
- additionalLocationInfo[dateElem.value].push(locationName)
- } else {
- const removed = additionalLocationInfo[dateElem.value].splice(additionalLocationInfo[dateElem.value].indexOf(locationName), 1)
- console.log(removed)
- console.log(additionalLocationInfo[dateElem.value])
- if (!additionalLocationInfo[dateElem.value].length) delete additionalLocationInfo[dateElem.value]
- }
- console.log(additionalLocationInfo)
- populateAddLocation()
- }
- function populateAddLocation(){
- fsNative.addloc.innerHTML = JSON.stringify(additionalLocationInfo)
- var text = []
- for (let date in additionalLocationInfo) {
- text.push(`${date}: ${additionalLocationInfo[date].join(", ")}`)
- }
- fsNative.addloc_text.innerHTML = text.join("; \n")
- }
- }
- // ========== END OF WFO ==========
- if (window.location.pathname === "/support/catalog/items/139") {
- const fsFields = {
- from: "requested_item_values_139_requested_item_value_attributes_cf_from_270753",
- to: "requested_item_values_139_requested_item_value_attributes_cf_to_270753",
- country: "requested_item_values_139_requested_item_value_attributes_cf_country_270753"
- }
- const countryBlacklist = [
- "Afghanistan",
- "Belarus",
- "Burundi",
- "Central African Republic",
- "China",
- "Côte d'Ivoire",
- "Lebanon"
- ]
- // =====================================================
- const fsNative = {
- dates: [
- {
- date: document.getElementById(fsFields.from + "_date"),
- time: document.getElementById(fsFields.from + "_time")
- },
- {
- date: document.getElementById(fsFields.to + "_date"),
- time: document.getElementById(fsFields.to + "_time")
- }
- ],
- country: document.getElementById(fsFields.country)
- }
- const countryDropdown = createSimplifiedDropdown(fsFields.country, [], "country")
- countryDropdown.addEventListener("change", function(){ renderController() })
- countriesGlobal.forEach(country => {
- if (!countryBlacklist.includes(country)) {
- const option = document.createElement("option")
- option.innerHTML = country
- option.value = country
- countryDropdown.appendChild(option)
- }
- })
- const dateList = createCustomDates(fsNative.dates.map(x => x.date))
- const minDate = new Date()
- minDate.setDate(minDate.getDate() + 14)
- dateList.forEach(dateElem => {
- dateElem.parentNode.style.display = "block"
- jQuery(dateElem).datepicker("option", {
- onSelect: function() {
- renderController()
- },
- minDate: minDate
- })
- })
- renderController()
- function renderController(){
- dateList.forEach((dateElem, index) => {
- if (dateElem.value) {
- fsNative.dates[index].date.value = reverseForFS(dateElem.value)
- fsNative.dates[index].time.value = "00:00"
- } else {
- fsNative.dates[index].date.value = null
- fsNative.dates[index].time.value = null
- }
- })
- fsNative.country.value = countryDropdown.value
- }
- }
- if (window.location.pathname === "/support/catalog/items/148") {
- console.log("dates init")
- const fsFields = {
- dates: [
- "requested_item_values_148_requested_item_value_attributes_cf_day1_270753",
- "requested_item_values_148_requested_item_value_attributes_cf_day2_270753",
- "requested_item_values_148_requested_item_value_attributes_cf_day3_270753",
- "requested_item_values_148_requested_item_value_attributes_cf_day4_270753",
- "requested_item_values_148_requested_item_value_attributes_cf_day5_270753"
- ]
- }
- //==============================================================================
- const fsNative = {
- dates: getElemList(fsFields.dates)
- }
- var activeDateCount = 0
- const dateList = createCustomDates(fsFields.dates.map(x => document.getElementById(x+"_date")))
- const today = new Date()
- const max = new Date()
- max.setDate(max.getDate() + 7 + (today.getDay() === 0 ? 0 : 7 - today.getDay()))
- dateList.forEach(dateElem => {
- jQuery(dateElem).datepicker("option", {
- onSelect: function() {
- renderController()
- },
- minDate: today,
- maxDate: max
- })
- })
- const dateControlAdd = document.createElement("button")
- dateControlAdd.innerHTML = "+"
- const dateControlRemove = document.createElement("button")
- dateControlRemove.innerHTML = "-"
- dateControlAdd.addEventListener("click", function(e){
- e.preventDefault()
- activeDateCount += 1
- renderController()
- })
- dateControlRemove.addEventListener("click", function(e){
- e.preventDefault()
- activeDateCount -= 1
- renderController()
- })
- renderController()
- function renderController(){
- dateList.forEach((dateElem, index) => {
- const date = document.getElementById(fsFields.dates[index] + "_date")
- const time = document.getElementById(fsFields.dates[index] + "_time")
- const errorElem = document.getElementById("date_custom_" + (index+1) + "-error")
- if (errorElem) errorElem.style.display = "none"
- if (dateElem.value) {
- date.value = reverseForFS(dateElem.value)
- time.value = "00:00"
- } else {
- date.value = null
- time.value = null
- }
- const controlWrapper = document.getElementById("controls_" + index)
- controlWrapper.innerHTML = ""
- controlWrapper.style.display = "inline"
- if (index < activeDateCount) {
- dateElem.disabled = true
- dateElem.parentNode.style.display = "block"
- } else if (index === activeDateCount) {
- dateElem.disabled = false
- if (index > 0 && dateList[index-1].value) {
- const nextDate = new Date(dateList[index-1].value)
- nextDate.setDate(nextDate.getDate() + 1)
- jQuery("#date_custom_"+(index+1)).datepicker("option", {
- minDate: nextDate
- })
- }
- dateElem.parentNode.style.display = "block"
- if (activeDateCount > 0) controlWrapper.appendChild(dateControlRemove)
- if (activeDateCount < dateList.length-1) {
- controlWrapper.appendChild(dateControlAdd)
- dateControlAdd.disabled = !dateElem.value
- }
- } else {
- dateElem.parentNode.style.display = "none"
- dateElem.value = null
- date.value = null
- time.value = null
- }
- })
- }
- }
- // hoodie//
- if (window.location.pathname === "/support/catalog/items/174") {
- const fsFields = {
- item: "requested_item_values_174_requested_item_value_attributes_cf_hoodie_options_270753"
- }
- const itemList = {
- "Hoodie black: front logo": "https://squad-photo.s3.eu-north-1.amazonaws.com/hoodie/hoodie-black-with-front-logo.png",
- "Hoodie black: front+arm logo": "https://squad-photo.s3.eu-north-1.amazonaws.com/hoodie/hoodie-black-with-front-arm-logo.png",
- "Hoodie black: front+back logo": "https://squad-photo.s3.eu-north-1.amazonaws.com/hoodie/hoodie-black-with-front-and-back-logo.png",
- "Hoodie khaki": "https://squad-photo.s3.eu-north-1.amazonaws.com/hoodie/hoodie-khaki.png"
- }
- // ===============================================
- const fsNative = {
- item: document.getElementById(fsFields.item)
- }
- fsNative.item.style.display = "none"
- const itemContainer = document.createElement("div")
- itemContainer.style.width = "100%"
- for (let itemName in itemList) {
- const container = document.createElement("div")
- const radio = document.createElement("input")
- radio.type = "radio"
- radio.name = "item"
- radio.value = itemName
- radio.id = itemName
- const label = document.createElement("label")
- label.htmlFor = itemName
- label.style.display = "inline"
- const img = document.createElement("img")
- img.src = itemList[itemName]
- img.style.width = "400px"
- img.style.border = "1px solid lightgrey"
- img.style.margin = "5px"
- label.appendChild(img)
- container.appendChild(radio)
- container.appendChild(label)
- itemContainer.appendChild(container)
- radio.onchange = function(){ renderController(this) }
- }
- fsNative.item.parentNode.appendChild(itemContainer)
- function renderController(context){
- fsNative.item.value = context.value
- }
- }
- const poshtaRequestList = [32]
- const currentRequestId = window.location.pathname.split("/").slice(-1)[0]
- const langPattern = /[а-яА-ЯЬьЮюЯяЇїІіЄєҐґ.,-\/0-9 \b\+\)\(]/
- if (poshtaRequestList.includes(parseInt(currentRequestId))) {
- const fsFields = {
- 32: {
- dropdown: "requested_item_values_120_requested_item_value_attributes_cf_delivery_type_270753",
- address: {
- region: "requested_item_values_120_requested_item_value_attributes_cf_region_270753",
- city: "requested_item_values_120_requested_item_value_attributes_cf_city_270753",
- district: "requested_item_values_120_requested_item_value_attributes_cf_district_270753",
- street: "requested_item_values_120_requested_item_value_attributes_cf_street_name_270753",
- building: "requested_item_values_120_requested_item_value_attributes_cf_building_270753",
- apartment: "requested_item_values_120_requested_item_value_attributes_cf_apartment_270753",
- receiver: 'requested_item_values_120_requested_item_value_attributes_cf_receiver_270753',
- phone: 'requested_item_values_120_requested_item_value_attributes_cf_phone_number_270753'
- },
- pickup: {
- receiver: "requested_item_values_120_requested_item_value_attributes_cf_receiver_1_270753",
- phone: "requested_item_values_120_requested_item_value_attributes_cf_phone_number_1_380501234567_270753",
- city: "requested_item_values_120_requested_item_value_attributes_cf_city_1_270753",
- location: "requested_item_values_120_requested_item_value_attributes_cf_novaposhta_office_1_270753"
- },
- dropdown_options: [
- "...",
- "Address delivery",
- "Delivery to NovaPoshta office",
- "Pick up at the Toronto office",
- "Pick up at the Community office",
- "Pick up at the Lviv office",
- "Courier delivery to the Lab 72/1",
- "Courier delivery to the Lab 72",
- "Courier delivery to the Lab 64"
- ]
- }
- }
- // =============================================================================================================
- // =============================================================================================================
- // =============================================================================================================
- var fsNative = {
- dropdown: document.getElementById(fsFields[currentRequestId].dropdown),
- address: {},
- pickup: {}
- }
- var fsCustom = {
- dropdown: createSimplifiedDropdown(fsFields[currentRequestId].dropdown, fsFields[currentRequestId].dropdown_options),
- address: {},
- pickup: {}
- }
- fsCustom.dropdown.onchange = function(){ renderController() }
- for (let key in fsFields[currentRequestId].address) {
- fsNative.address[key] = document.getElementById(fsFields[currentRequestId].address[key])
- fsCustom.address[key] = createInputWithRestrictions(fsNative.address[key], langPattern)
- fsCustom.address[key].onkeydown = function(e){
- if (langPattern.test(e.key) || e.key === "Backspace") {
- renderController(fsNative.address[key], e.key)
- } else {
- return false
- }
- }
- }
- for (let key in fsFields[currentRequestId].pickup) {
- fsNative.pickup[key] = document.getElementById(fsFields[currentRequestId].pickup[key])
- fsCustom.pickup[key] = createInputWithRestrictions(fsNative.pickup[key], langPattern)
- fsCustom.pickup[key].onkeydown = function(e){
- if (langPattern.test(e.key)) {
- renderController(fsNative.pickup[key], e.key)
- } else {
- return false
- }
- }
- }
- renderController()
- function renderController(elem, key){
- //console.log(elem, key)
- //console.log('test')
- fsNative.dropdown.value = fsCustom.dropdown.value === "..." ? "" : fsCustom.dropdown.value
- if (fsCustom.dropdown.value === 'Address delivery') {
- for (let key in fsCustom.address) {
- fsCustom.address[key].parentNode.hidden = false
- fsNative.address[key].value = fsCustom.address[key].value
- }
- for (let key in fsCustom.pickup) {
- fsCustom.pickup[key].value = ""
- fsNative.pickup[key].value = ""
- fsCustom.pickup[key].parentNode.hidden = true
- }
- } else if (fsCustom.dropdown.value === 'Delivery to NovaPoshta office') {
- for (let key in fsCustom.pickup) {
- fsCustom.pickup[key].parentNode.hidden = false
- fsNative.pickup[key].value = fsCustom.pickup[key].value
- }
- for (let key in fsCustom.address) {
- fsCustom.address[key].value = ""
- fsNative.address[key].value = ""
- fsCustom.address[key].parentNode.hidden = true
- }
- } else {
- for (let key in fsCustom.address) {
- fsCustom.address[key].value = ""
- fsNative.address[key].value = ""
- fsCustom.address[key].parentNode.hidden = true
- }
- for (let key in fsCustom.pickup) {
- fsCustom.pickup[key].value = ""
- fsNative.pickup[key].value = ""
- fsCustom.pickup[key].parentNode.hidden = true
- }
- }
- if (elem && key) {
- console.log(key)
- if (key === "Backspace") {
- console.log(elem.value.slice(0, -1))
- elem.value = elem.value.slice(0, -1)
- } else {
- if (langPattern.test(key)) elem.value += key
- }
- }
- }
- }
- if (/\/support\/tickets\/\d*/.test(window.location.pathname)) { // INVENTORY//
- console.log(jQuery('.item-name').text())
- const itemName = "Annual Asset check" // if need to rename//
- const rawDataFieldName = "Raw_data"
- console.log(jQuery('.item-name').text() === itemName, itemName, jQuery('.item-name').text())
- if (jQuery('.item-name').text() === itemName) {
- console.log('start')
- jQuery('.redactor_box').hide()
- jQuery('.control-group').hide()
- const commentNative = jQuery('.redactor_editor p')
- console.log('ELEM PROBING')
- const rawDataElem = jQuery(`[for=${rawDataFieldName}]`).parent()
- const rawDataText = rawDataElem.find("pre").text()
- const rawData = JSON.parse(rawDataText)
- console.log(rawData)
- console.log('rendering items for requester')
- renderItemList(rawData)
- const replyTable = createReplyTable(rawData)
- jQuery('.redactor_box').parent().append(replyTable)
- const replies = jQuery('.p-desc')
- replies.each((i,x) => {
- if (i !== 0) {
- try {
- const child = jQuery(x).children('div')
- JSON.parse(child.text())
- child.css({
- "font-size": "14px",
- "font-family": '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'
- })
- child.html('Thank you! Your reply has been submitted.')
- } catch(e) { null }
- }
- })
- function createReplyTable(data){
- const table = document.createElement("table")
- rawData.forEach(item => {
- const row = document.createElement("tr")
- row.id = item.asset_tag
- const itemName = document.createElement("td")
- itemName.innerHTML = item.display_name
- itemName.style.fontWeight = "bold"
- itemName.style.margin = "5px"
- itemName.style.textAlign = "right"
- const isConfirmed = document.createElement("td")
- const checkbox = document.createElement("input")
- checkbox.type = "checkbox"
- checkbox.id = "check_" + item.asset_tag
- checkbox.onchange = function(){ renderController() }
- const label = document.createElement("label")
- label.htmlFor = "check_" + item.asset_tag
- label.innerHTML = "Confirm"
- label.style.margin = "5px"
- label.style.display = "inline"
- isConfirmed.appendChild(label)
- isConfirmed.appendChild(checkbox)
- const comment = document.createElement("td")
- const commentInput = document.createElement("textarea")
- commentInput.id = "comment_" + item.asset_tag
- commentInput.style.marginLeft = "10px"
- commentInput.onkeyup = function(){ renderController() }
- comment.appendChild(commentInput)
- row.appendChild(itemName)
- row.appendChild(isConfirmed)
- row.appendChild(comment)
- table.appendChild(row)
- })
- return table
- }
- function renderItemList(itemList){
- var parsedItems = []
- itemList.forEach(item => {
- var text = `<b>Display name:</b> ${item.display_name}<br>
- <b>Asset type:</b> ${item.asset_type}<br>
- <b>Asset tag:</b> ${item.asset_tag}<br>
- <b>Serial number:</b> ${item.serial_number}<br>
- <b>Finance name:</b> ${item.finance_name}<br>`
- parsedItems.push(text)
- })
- rawDataElem.html(parsedItems.join("<br>"))
- }
- function renderController(){
- var replyData = []
- rawData.forEach(item => {
- var replyItem = item
- replyItem.is_confirmed = document.getElementById("check_" + item.asset_tag).checked
- replyItem.comment = document.getElementById("comment_" + item.asset_tag).value
- replyData.push(replyItem)
- })
- commentNative.html(JSON.stringify(replyData))
- }
- }
- }
- })
- function replaceInputWithDropdown(targetId, dataset, facsId = null){
- const nativeContainer = document.getElementById(targetId).parentNode
- document.getElementById(targetId).style.display = "none"
- const selector = document.createElement("select")
- selector.id = facsId
- for (let optionName in dataset) {
- const option = document.createElement("option")
- option.innerHTML = optionName
- option.value = optionName
- selector.appendChild(option)
- }
- nativeContainer.appendChild(selector)
- return selector
- }
- function createSimplifiedDropdown(targetId, dataset, facsId = null){
- const nativeContainer = document.getElementById(targetId).parentNode
- document.getElementById(targetId).style.display = "none"
- const selector = document.createElement("select")
- selector.id = facsId
- dataset.forEach(optionName => {
- const option = document.createElement("option")
- option.innerHTML = optionName
- option.value = optionName
- selector.appendChild(option)
- })
- nativeContainer.appendChild(selector)
- return selector
- }
- function createCustomCheckbox(container, id, labelText){
- container.childNodes.forEach(elem => {
- elem.style.display = "none"
- })
- const checkboxWrapper = document.createElement("div")
- const checkbox = document.createElement("input")
- checkbox.type = "checkbox"
- checkbox.id = id
- const checkboxLabel = document.createElement("label")
- checkboxLabel.htmlFor = id
- checkboxLabel.style.display = "inline"
- checkboxLabel.style.marginLeft = "5px"
- checkboxLabel.appendChild(labelText)
- checkboxWrapper.appendChild(checkbox)
- checkboxWrapper.appendChild(checkboxLabel)
- container.appendChild(checkboxWrapper)
- return checkbox
- }
- function createCustomDates(nativeList){
- var customDateCollection = []
- nativeList.forEach((dateNativeField, index) => {
- dateNativeField.parentNode.style.display = "none"
- const dateField = document.createElement("input")
- const elemId = "date_custom_" + (index + 1)
- dateField.id = elemId
- const controlWrapper = document.createElement("span")
- controlWrapper.id = "controls_" + index
- controlWrapper.style.marginLeft = "5px"
- controlWrapper.style.minWidth = "50px"
- controlWrapper.style.display = "inline-block"
- const addLocationWrapper = document.createElement("div")
- addLocationWrapper.id = "addtable_wrapper_" + (index+1)
- const addLocationHeader = document.createElement("div")
- addLocationHeader.style.textColor = "lightgrey"
- addLocationHeader.style.fontSize = "16px"
- const addLocationArrow = document.createElement("span")
- addLocationHeader.appendChild(addLocationArrow)
- addLocationArrow.innerHTML = "►"
- addLocationHeader.innerHTML += "Select additional locations"
- const addLocationTableContainer = document.createElement("div")
- addLocationTableContainer.id = "addtable_" + (index+1)
- addLocationTableContainer.className += "addtable-container"
- jQuery(addLocationTableContainer).hide()
- addLocationHeader.onclick = function(){
- console.log(addLocationArrow.innerHTML, addLocationArrow.innerHTML === "►")
- addLocationArrow.innerHTML = (addLocationArrow.innerHTML === "►") ? "▼" : "►"
- jQuery(addLocationTableContainer).toggle(200)
- }
- addLocationWrapper.appendChild(addLocationHeader)
- addLocationWrapper.appendChild(addLocationTableContainer)
- dateNativeField.parentNode.parentNode.append(dateField)
- dateNativeField.parentNode.parentNode.append(controlWrapper)
- dateNativeField.parentNode.parentNode.append(addLocationWrapper)
- if (index > 0) dateNativeField.parentNode.parentNode.style.display = "none"
- customDateCollection.push(dateField)
- jQuery("#"+elemId).datepicker({
- dateFormat: "yy-mm-dd",
- firstDay: 1
- })
- })
- return customDateCollection
- }
- function createInputWithRestrictions(elem, pattern){
- const parent = elem.parentNode
- const input = document.createElement("input")
- if (pattern) input.pattern = pattern
- elem.style.display = "none"
- parent.appendChild(input)
- return input
- }
- function createDocumentSection(target, todayGlobal){
- target.parentNode.childNodes.forEach(node => {
- node.style.display = "none"
- })
- const documentTextWrapper = document.createElement("div")
- const documentTextHeader = document.createElement("div")
- documentTextHeader.style.fontSize = "16px"
- const headerArrow = document.createElement("span")
- headerArrow.innerHTML = "▼"
- const headerTitle = document.createElement("span")
- headerTitle.innerHTML = "Текст документа (click to view)"
- documentTextHeader.appendChild(headerArrow)
- documentTextHeader.appendChild(headerTitle)
- const documentTextContent = document.createElement("div")
- documentTextHeader.onclick = function(){
- documentTextContent.hidden = !documentTextContent.hidden
- headerArrow.innerHTML = (headerArrow.innerHTML === "►" ? "▼" : "►")
- }
- documentTextContent.style.width = "600px"
- documentTextContent.style.margin = "15px"
- documentTextContent.insertAdjacentHTML('beforeend', '<div style="text-align: center"> <b>Заява на допуск до користування Простором Товариства з обмеженою відповідальністю «ТекХостинг» (далі – ТОВ «ТекХостинг»)</b> </div> <br> <div style="text-align: justify"> <p> Я, <b>фізична особа-підприємець</b> {{ current_user.phone }}, прошу допустити мене до користування офісним простором ТОВ «ТекХостинг» (далі – Простір), що знаходиться за адресою: <span id="doc-address"></span>. </p> <br> <p> <b>Я підтверджую</b>, що на момент надання мені доступу до користування Простором: <ul> <li>у мене відсутні будь-які ознаки ГРВІ, а саме: підвищена температура тіла (більше 37,2 С), кашель, утруднене дихання тощо;</li> <li>я ознайомлений(а) з рекомендаціями МОЗ та ВООЗ щодо попередження зараження COVID-19 та їх дотримуюсь;</li> <li>протягом останніх 14 днів я не перебував(ла) за межами України та не контактував(ла) з особами, щодо яких наявна підозра/хворими на COVID-19.</li> </ul> </p> <br> <p> <b>Я зобов’язуюсь</b> під час користування Простором дотримуватися посилених санітарно-гігієнічних норм, а також рекомендацій МОЗ та ВООЗ щодо запобігання поширенню COVID-19, а саме: <ul> <li>носити медичну маску/респіратор;</li> <li>ретельно мити руки з милом протягом 20-40 сек. та регулярно обробляти їх антисептичним засобом під час перебування в Просторі;</li> <li>дотримуватися дистанції min 1,5 (півтора) метри від інших відвідувачів Простору.</li> </ul> </p> </div><br> <div> <b>Дата</b>: ' + todayGlobal + ' </div>')
- documentTextContent.hidden = true
- documentTextWrapper.appendChild(documentTextHeader)
- documentTextWrapper.appendChild(documentTextContent)
- target.parentNode.appendChild(documentTextWrapper)
- return documentTextContent
- }
- function createAdditionalOfficeSelectors(ids, datalist){
- var list = []
- ids.forEach((id, index) => {
- const newID = "additional_office_" + (index+1)
- const selector = replaceInputWithDropdown(id, datalist, newID)
- selector.parentNode.style.display = "none"
- if (index > 0) selector.parentNode.childNodes.item("LABEL").style.display = "none"
- list.push(selector)
- })
- return list
- }
- function calcDateLimits(thisWeek){
- const nowDate = new Date()
- var limits = []
- if (thisWeek) {
- const dateMin = nowDate.toISOString().split("T")[0]
- const nowWeekDay = nowDate.getDay()
- const daysToAdd = !nowWeekDay ? 0 : 7 - nowWeekDay
- nowDate.setDate(nowDate.getDate() + daysToAdd)
- const dateMax = nowDate.toISOString().split("T")[0]
- limits.push(dateMin)
- limits.push(dateMax)
- } else {
- const nowWeekDay = nowDate.getDay()
- const daysToAdd = !nowWeekDay ? 1 : 7 - nowWeekDay + 1
- nowDate.setDate(nowDate.getDate() + daysToAdd)
- const dateMin = nowDate.toISOString().split("T")[0]
- nowDate.setDate(nowDate.getDate() + 6)
- const dateMax = nowDate.toISOString().split("T")[0]
- limits.push(dateMin)
- limits.push(dateMax)
- }
- return limits
- }
- function reverseForFS(date){
- if (!date) return null
- const vals = date.split("-")
- //return `${vals[2]}-${vals[1]}-${vals[0]}`
- return vals[2]+"-"+vals[1]+"-"+vals[0]
- }
- function getElemList(idList){
- var collection = []
- idList.forEach(id => {
- collection.push(document.getElementById(id))
- })
- return collection
- }
- function createCapacityDisplay(nextElement){
- const wrapper = document.createElement("div")
- wrapper.style.border = "3px solid #70c9e9"
- wrapper.style.minHeight = "100px"
- wrapper.style.width = "250px"
- wrapper.style.margin = "5px 0px 5px 0px"
- wrapper.style.padding = "5px"
- const mainWrapper = nextElement.parentNode
- mainWrapper.insertBefore(wrapper, nextElement)
- wrapper.hidden = true
- return wrapper
- }
- // ==================== MEIDO ====================
- class MeidoCart{
- constructor(itemList, limit, cartElem, dateElemsCollection, fsMeidoField, reverseDate){
- console.log('constructing')
- this.itemList = itemList
- this.dailyLimit = limit
- //this.renderElementId = elemId
- this.renderTarget = cartElem
- this.reverseDate = reverseDate
- this.targetField = fsMeidoField
- this.dateElemsCollection = dateElemsCollection
- console.log(this.dateElemsCollection)
- this.dateCollection = null
- this.selectedRadio = null
- this.dateElemsCollection.forEach(dateElem => {
- dateElem.onchange = function(){
- this.calcDateCollection()
- this.render()
- }
- })
- }
- init(){
- this.calcDateCollection()
- }
- reverse(date){
- const vals = date.split("-")
- //return `${vals[2]}-${vals[1]}-${vals[0]}`
- return vals[2]+"-"+vals[1]+"-"+vals[0]
- }
- calcDateCollection(){
- if (!this.dateCollection) this.dateCollection = {}
- var flag = false
- var collection = []
- var dateObj = {}
- this.dateElemsCollection.forEach(dateElem => {
- if (dateElem.value) {
- flag = true
- collection.push(dateElem.value)
- }
- const weekday = new Date(dateElem.value).getDay()
- if (dateElem.value && weekday !== 6 && weekday !== 0){
- if (!this.dateCollection[dateElem.value]){
- dateObj[dateElem.value] = {
- limit: this.dailyLimit,
- items: {}
- }
- } else {
- dateObj[dateElem.value] = this.dateCollection[dateElem.value]
- }
- }
- })
- if (!this.selectedRadio || !collection.includes(this.selectedRadio)) this.selectedRadio = this.dateElemsCollection[0].value
- if (!flag) dateObj = null
- this.dateCollection = dateObj
- this.render()
- }
- get cartState(){
- return JSON.stringify(this.dateCollection)
- }
- render(){
- const wrapper = document.createElement("div")
- if (!this.dateCollection) {
- wrapper.innerHTML = "Диапазон дат указан неверно!"
- } else {
- for(let date in this.dateCollection){
- const dateWrapper = document.createElement("div")
- dateWrapper.className += "meido-cart-date-wrapper"
- const header = document.createElement("div")
- header.className += "meido-cart-date-header"
- const radio = document.createElement("input")
- radio.type = "radio"
- radio.id = date
- radio.value = date
- radio.name = "date-radio"
- radio.addEventListener('change', function(e){
- this.selectedRadio = e.target.value
- }.bind(this))
- if (date === this.selectedRadio) radio.checked = true
- header.appendChild(radio)
- const label = document.createElement("label")
- label.htmlFor = date
- //label.innerHTML += `${date} (остаток: ${this.dateCollection[date].limit} грн.)`
- label.innerHTML += date+" (остаток: "+this.dateCollection[date].limit+" грн.)"
- header.appendChild(label)
- dateWrapper.appendChild(header)
- var flag = false
- for(let item in this.dateCollection[date].items){
- flag = true
- const itemElem = document.createElement("div")
- itemElem.className += "meido-cart-item"
- const itemText = document.createElement("span")
- //itemText.innerHTML = `${this.dateCollection[date].items[item]} x ${this.itemList[item].name}`
- itemText.innerHTML = this.dateCollection[date].items[item]+" x "+this.itemList[item].name
- itemText.style.width = "90%"
- itemElem.appendChild(itemText)
- const itemRemove = document.createElement("button")
- itemRemove.innerHTML = "X"
- itemRemove.className += "meido-cart-item-remove"
- itemRemove.onclick = function(){ this.removeMeidoItem(item, date) }.bind(this)
- itemElem.appendChild(itemRemove)
- dateWrapper.appendChild(itemElem)
- }
- if (!flag) {
- const itemEmpty = document.createElement("div")
- itemEmpty.className += "meido-cart-item"
- itemEmpty.style.color = "grey"
- itemEmpty.innerHTML = "<i>Ничего не добавлено</i>"
- dateWrapper.appendChild(itemEmpty)
- }
- wrapper.appendChild(dateWrapper)
- }
- }
- this.renderTarget.innerHTML = ""
- this.renderTarget.appendChild(wrapper)
- document.getElementById(this.targetField).innerHTML = this.cartState
- }
- addMeidoItem(itemId){
- if (this.dateCollection[this.selectedRadio].limit - this.itemList[itemId].price >= 0) {
- if (!this.dateCollection[this.selectedRadio].items[itemId]) {
- this.dateCollection[this.selectedRadio].items[itemId] = 1
- } else {
- this.dateCollection[this.selectedRadio].items[itemId] += 1
- }
- this.dateCollection[this.selectedRadio].limit -= this.itemList[itemId].price
- } else {
- console.error('Insufficient funds!')
- }
- this.render()
- }
- removeMeidoItem(itemId, date){
- this.dateCollection[date].items[itemId] -= 1
- if (this.dateCollection[date].items[itemId] === 0) delete this.dateCollection[date].items[itemId]
- this.dateCollection[date].limit += this.itemList[itemId].price
- this.render()
- }
- }
- function meidoInit(container, dateElemsCollection, fsMeidoField, limit, reverseDate = false){
- const innerContainer = document.createElement("div")
- return fetch("https://analytics.getmeido.com/api/fs/product-list?token="+meidoToken)
- .then(res => {return res.json()})
- .then(data => {
- const title = document.createElement("h4")
- title.innerHTML = "Заказ еды Meido"
- innerContainer.appendChild(title)
- const mainWindow = buildMeidoWindow(data, dateElemsCollection, fsMeidoField, limit, reverseDate)
- innerContainer.appendChild(mainWindow)
- meidoCart.init()
- container.appendChild(innerContainer)
- return innerContainer
- }).catch(err => {
- console.error("[MEIDO] Cannot get Meido menu!")
- console.error(err)
- })
- }
- function buildMeidoWindow(apiData, dateElemsCollection, fsMeidoField, limit, reverseDate){
- const wrapper = document.createElement("div")
- wrapper.className += "meido-main-window"
- const menuElem = document.createElement("div")
- menuElem.id = "meido-menu"
- const cartElem = document.createElement("div")
- cartElem.id = "meido-cart"
- var categorized = {}
- var flat = {}
- apiData.forEach(item => {
- if (!categorized[item.product_contractor_title]) categorized[item.product_contractor_title] = {}
- if (!categorized[item.product_contractor_title][item.category_title]) categorized[item.product_contractor_title][item.category_title] = {}
- categorized[item.product_contractor_title][item.category_title][item.id] = item
- flat[item.id] = {
- name: item.product_title,
- price: parseFloat(item.product_price),
- bzhu: item.bzhu,
- weight: item.weight,
- cal: item.cal
- }
- })
- menuElem.appendChild(buildMenu(categorized))
- console.log(limit, dateElemsCollection, reverseDate)
- window.meidoCart = new MeidoCart(flat, limit, cartElem, dateElemsCollection, fsMeidoField, reverseDate)
- cartElem.className += "meido-cart-wrapper"
- wrapper.appendChild(menuElem)
- wrapper.appendChild(cartElem)
- return wrapper
- }
- function buildMenu(data){
- const wrapper = document.createElement("div")
- wrapper.className += "meido-menu-wrapper"
- for(let category in data){
- const categoryWrapper = document.createElement("div")
- const categoryHeader = document.createElement("div")
- categoryHeader.className += "meido-category-title"
- const categoryArrow = document.createElement("span")
- categoryArrow.className += "arrow"
- categoryArrow.innerHTML = "►"
- const categoryTitle = document.createElement("span")
- categoryTitle.innerHTML = category
- categoryHeader.appendChild(categoryArrow)
- categoryHeader.appendChild(categoryTitle)
- const categoryContent = document.createElement("div")
- categoryContent.className += "meido-category-content"
- categoryHeader.onclick = function(){
- categoryContent.hidden = !categoryContent.hidden
- categoryArrow.innerHTML = (categoryArrow.innerHTML === "►" ? "▼" : "►")
- }
- categoryContent.hidden = true
- categoryWrapper.appendChild(categoryHeader)
- for(let contractor in data[category]){
- const contractorWrapper = document.createElement("div")
- const contractorHeader = document.createElement("div")
- contractorHeader.className += "meido-contractor-title"
- const contractorArrow = document.createElement("span")
- contractorArrow.className += "arrow"
- contractorArrow.innerHTML = "►"
- const contractorTitle = document.createElement("span")
- contractorTitle.innerHTML = contractor
- contractorHeader.appendChild(contractorArrow)
- contractorHeader.appendChild(contractorTitle)
- const contractorContent = document.createElement("div")
- contractorContent.className += "meido-contractor-content"
- contractorHeader.onclick = function(){
- contractorContent.hidden = !contractorContent.hidden
- contractorArrow.innerHTML = (contractorArrow.innerHTML === "►" ? "▼" : "►")
- }
- contractorContent.hidden = true
- contractorWrapper.appendChild(contractorHeader)
- for(let item in data[category][contractor]){
- contractorContent.appendChild(buildMenuItem(data[category][contractor][item]))
- }
- contractorWrapper.appendChild(contractorContent)
- categoryContent.appendChild(contractorWrapper)
- }
- categoryWrapper.appendChild(categoryContent)
- wrapper.appendChild(categoryWrapper)
- }
- return wrapper
- }
- function buildMenuItem(item){
- const wrapper = document.createElement("div")
- wrapper.className += "meido-item"
- const itemTitle = document.createElement("div")
- itemTitle.innerHTML = item.product_title
- itemTitle.className += "meido-item-title"
- const descWrapper = document.createElement("div")
- descWrapper.className += "meido-desc-wrapper"
- const itemPic = document.createElement("img")
- itemPic.src = item.photo_url
- itemPic.className += "meido-pic"
- const innerWrapper = document.createElement("div")
- const itemDesc = document.createElement("div")
- itemDesc.innerHTML = item.product_description
- itemDesc.className += "meido-desc-text"
- const itemInfo = document.createElement("div")
- itemInfo.innerHTML = item.weight + " gr. " + item.cal
- itemInfo.className += "meido-item-bzhu"
- const itemBzhu = document.createElement("div")
- itemBzhu.innerHTML = item.bzhu
- itemBzhu.className += "meido-item-bzhu"
- descWrapper.appendChild(itemPic)
- innerWrapper.appendChild(itemDesc)
- innerWrapper.appendChild(itemInfo)
- innerWrapper.appendChild(itemBzhu)
- descWrapper.appendChild(innerWrapper)
- const price = document.createElement("span")
- //price.innerHTML = `<i>Цена: ${item.product_price} грн.</i>`
- price.innerHTML = "Цена: "+item.product_price+" грн."
- price.className += "meido-price"
- const add = document.createElement("button")
- add.innerHTML = "Buy"
- add.className += "meido-add-button"
- add.onclick = null
- add.onclick = function(e){
- e.preventDefault()
- meidoCart.addMeidoItem(item.id)
- }
- wrapper.appendChild(itemTitle)
- wrapper.appendChild(descWrapper)
- wrapper.appendChild(add)
- wrapper.appendChild(price)
- return wrapper
- }
- const countriesGlobal = ["Afghanistan","Åland Islands","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua and Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia (Plurinational State of)","Bonaire, Sint Eustatius and Saba","Bosnia and Herzegovina","Botswana","Bouvet Island","Brazil","British Indian Ocean Territory","United States Minor Outlying Islands","Virgin Islands (British)","Virgin Islands (U.S.)","Brunei Darussalam","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cabo Verde","Cayman Islands","Central African Republic","Chad","Chile","China","Christmas Island","Cocos (Keeling) Islands","Colombia","Comoros","Congo","Congo (Democratic Republic of the)","Cook Islands","Costa Rica","Croatia","Cuba","Curaçao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands (Malvinas)","Faroe Islands","Fiji","Finland","France","French Guiana","French Polynesia","French Southern Territories","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guadeloupe","Guam","Guatemala","Guernsey","Guinea","Guinea-Bissau","Guyana","Haiti","Heard Island and McDonald Islands","Holy See","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Côte d'Ivoire","Iran (Islamic Republic of)","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kuwait","Kyrgyzstan","Lao People's Democratic Republic","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macao","Macedonia (the former Yugoslav Republic of)","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Martinique","Mauritania","Mauritius","Mayotte","Mexico","Micronesia (Federated States of)","Moldova (Republic of)","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Niue","Norfolk Island","Korea (Democratic People's Republic of)","Northern Mariana Islands","Norway","Oman","Pakistan","Palau","Palestine, State of","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Pitcairn","Poland","Portugal","Puerto Rico","Qatar","Republic of Kosovo","Réunion","Romania","Russian Federation","Rwanda","Saint Barthélemy","Saint Helena, Ascension and Tristan da Cunha","Saint Kitts and Nevis","Saint Lucia","Saint Martin (French part)","Saint Pierre and Miquelon","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Sint Maarten (Dutch part)","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Georgia and the South Sandwich Islands","Korea (Republic of)","South Sudan","Spain","Sri Lanka","Sudan","Suriname","Svalbard and Jan Mayen","Swaziland","Sweden","Switzerland","Syrian Arab Republic","Taiwan","Tajikistan","Tanzania, United Republic of","Thailand","Timor-Leste","Togo","Tokelau","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Turks and Caicos Islands","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom of Great Britain and Northern Ireland","United States of America","Uruguay","Uzbekistan","Vanuatu","Venezuela (Bolivarian Republic of)","Viet Nam","Wallis and Futuna","Western Sahara","Yemen","Zambia","Zimbabwe"]
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement