Last active
October 28, 2019 15:04
-
-
Save faustofjunqueira/f94e5307c2f0fac814f42d2a852c0e89 to your computer and use it in GitHub Desktop.
adicionado ferias
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://pontoweb.nasajon.com.br/radix/colaborador/ajustes/criar | |
// TODO, verificar se esta na tela correta! | |
///////// Util | |
function addHour(originalHour, minutesToAdd) { | |
let [hour, minute] = originalHour.split(':'); | |
minute = Number(minute); | |
hour = Number(hour); | |
const fullyMinutes = hour*60 + minute + minutesToAdd; | |
minute = fullyMinutes % 60; | |
hour = Math.floor(fullyMinutes/60) | |
return [padZero(hour), padZero(minute)].join(':'); | |
} | |
function padZero(number) { | |
if (number < 10) { | |
return '0' + number; | |
} else { | |
return number.toString(); | |
} | |
} | |
function randomNumber(max=1, min=0) { | |
return Math.round(Math.random() * (max-min)) + min; | |
} | |
function randomMinute() { | |
let minute = Math.ceil(Math.random() * 59); | |
return padZero(minute); | |
} | |
///////// Model | |
class HourWorkTime { | |
constructor(hour, justify) { | |
this.hour = hour; | |
this.justify = justify; | |
} | |
toRequestObject() { | |
return { | |
marcacao: { | |
datahora: this.hour | |
}, | |
justificativa: this.justify | |
}; | |
} | |
} | |
class WorkTime { | |
constructor(dateTarget) { | |
this.dateTarget = dateTarget; | |
this.hours = []; | |
} | |
appendHour(hour, justify) { | |
this.hours.push(new HourWorkTime(hour, justify)); | |
} | |
toRequestObject() { | |
const formData = new FormData(); | |
formData.append('datareferencia', this.dateTarget); | |
formData.append('diaponto[]', 'Atual'); | |
formData.append('diaponto[]', 'Atual'); | |
formData.append('diaponto[]', 'Atual'); | |
formData.append('diaponto[]', 'Atual'); | |
formData.append('form[ajustes][0][marcacao][datahora]', this.hours[0].hour); | |
formData.append('form[ajustes][0][justificativa]', this.hours[0].justify); | |
formData.append('form[ajustes][1][marcacao][datahora]', this.hours[1].hour); | |
formData.append('form[ajustes][1][justificativa]', this.hours[1].justify); | |
formData.append('form[ajustes][2][marcacao][datahora]', this.hours[2].hour); | |
formData.append('form[ajustes][2][justificativa]', this.hours[2].justify); | |
formData.append('form[ajustes][3][marcacao][datahora]', this.hours[3].hour); | |
formData.append('form[ajustes][3][justificativa]', this.hours[3].justify); | |
return formData; | |
} | |
toString() { | |
return this.dateTarget; | |
} | |
} | |
///////// API | |
const urlWorkTime = './ajustes/criar'; | |
function doRequest(request) { | |
return fetch(request) | |
.then(response => { | |
const contentType = response.headers.get('content-type'); | |
return contentType === 'application/json' ? response.json() : response.text(); | |
}); | |
} | |
function sendWorkTime(workTime) { | |
const request = new Request(urlWorkTime, { | |
method: 'POST', | |
body: workTime.toRequestObject(), | |
}); | |
return doRequest(request); | |
} | |
///////// Service | |
function createArrayOfRandomEndHours(numberOfDates, array=[]) { | |
if(!numberOfDates) { | |
return array; | |
} else if (numberOfDates <= 1) { | |
return createArrayOfRandomEndHours(numberOfDates-1, [...array, 0]) | |
} else if (numberOfDates === 2) { | |
const minuteRandom = Number(randomMinute()); | |
return createArrayOfRandomEndHours(numberOfDates-2, [...array, minuteRandom, minuteRandom * (-1)]); | |
} else { | |
const minuteRandom1 = Number(randomMinute()) * (Math.random() > 0.5 ? 1 : -1); | |
const minuteRandom2 = Number(randomMinute()) * (Math.random() > 0.5 ? 1 : -1); | |
const minuteRandom3 = 0 - minuteRandom1 - minuteRandom2; | |
return createArrayOfRandomEndHours(numberOfDates-3, [...array, minuteRandom1, minuteRandom2, minuteRandom3]); | |
} | |
} | |
function distributionExtraHour(extraHour, numberOfDays, extraHourArray=[]) { | |
const distributionArray = [34, 55, 89, 144, 180]; | |
if(!extraHour) return extraHourArray; | |
let minPossibleExtraHourInIteration = distributionArray[0]; | |
let maxPossibleExtraHourInIteration = distributionArray[distributionArray.length-1]; | |
if(extraHour < maxPossibleExtraHourInIteration){ | |
return [...extraHourArray, extraHour]; | |
} | |
const numberOfExtraHour = extraHourArray.length; | |
if(extraHour){ | |
const factorOfHealthy = maxPossibleExtraHourInIteration*(numberOfDays - numberOfExtraHour - 1); | |
while( extraHour - minPossibleExtraHourInIteration > factorOfHealthy) { | |
distributionArray.shift(); | |
minPossibleExtraHourInIteration = distributionArray[0]; | |
} | |
} | |
const value = distributionArray[randomNumber(distributionArray.length-1)]; | |
return distributionExtraHour(extraHour-value, numberOfDays, [...extraHourArray, value]); | |
} | |
function applyExtraHour(arrayOfRandomEndHour, extraHour) { | |
const numberOfDays = arrayOfRandomEndHour.length; | |
const extraHourArray = distributionExtraHour(extraHour, numberOfDays); | |
const unusedPosition = arrayOfRandomEndHour.reduce((obj,_,i) => ({...obj, [i]: true}), {}); | |
while(extraHourArray.length) { | |
const value = extraHourArray.pop(); | |
const avalablePosition = Object.keys(unusedPosition); | |
const indexRandom = avalablePosition[randomNumber(avalablePosition.length-1)]; | |
delete unusedPosition[indexRandom]; | |
arrayOfRandomEndHour[indexRandom] += value; | |
} | |
return arrayOfRandomEndHour; | |
} | |
function applyEndRandomHour(hour, arrayOfRandomEndHour) { | |
if(arrayOfRandomEndHour.length){ | |
const minuteToApply = arrayOfRandomEndHour.pop(); | |
return addHour(hour, minuteToApply); | |
} | |
return hour; | |
} | |
function createWorkTime(arrayOfRandomEndHour) { | |
return date => { | |
const workTime = new WorkTime(date); | |
const minutesInOut = randomMinute(); | |
const minutesLunch = randomMinute(); | |
const enterHour = '09:' + minutesInOut; | |
const exitHour = applyEndRandomHour('18:' + minutesInOut, arrayOfRandomEndHour); | |
workTime.appendHour(enterHour, 'Alocado no cliente'); | |
workTime.appendHour('12:' + minutesLunch, 'Almoço saída'); | |
workTime.appendHour('13:' + minutesLunch, 'Almoço retorno'); | |
workTime.appendHour(exitHour, 'Final expediente'); | |
return workTime; | |
} | |
} | |
async function parallelSendDates(workTimeList) { | |
for (let workTime of workTimeList) { | |
try { | |
console.info(`>>> ${workTime.toString()} Enviado com sucesso!`); | |
await sendWorkTime(workTime); | |
} catch (e) { | |
console.error(`>>> ${workTime.toString()} Enviado com erro!`); | |
console.error(e); | |
} | |
} | |
} | |
function sendDates(dateList, arrayOfRandomEndHour) { | |
const workTimeList = dateList.map(createWorkTime(arrayOfRandomEndHour)); | |
const length = dateList.length; | |
if(length > 3) { | |
const factor = Math.floor(length/3); | |
return Promise.all([ | |
parallelSendDates(workTimeList.slice(0, factor)), | |
parallelSendDates(workTimeList.slice(factor, 2*factor)), | |
parallelSendDates(workTimeList.slice(2*factor)) | |
]) | |
} | |
return parallelSendDates(workTimeList) | |
} | |
function checkExtraHour(extraHour, numberOfDays) { | |
return !isNaN(extraHour) | |
&& extraHour < numberOfDays * 3; // vericando se eh menor que 3 horas por dia | |
} | |
function questionAboutExtraHour(arrayOfRandomEndHour) { | |
const numberOfDays = arrayOfRandomEndHour.length; | |
if(confirm('Deseja incluir horas extras?')) { | |
const msgPrompt = `Informe a quantidade de horas extras. Em HORAS! | |
Ex: 2 | |
para duas horas extras`; | |
let extraHour; | |
do{ | |
extraHour = Number(prompt(msgPrompt)); | |
if(!extraHour) break; | |
}while(!checkExtraHour(extraHour, numberOfDays)); | |
extraHour = extraHour || 0; | |
if(extraHour) alert(`Será lançado ${extraHour} horas extras`); | |
extraHour *= 60; // converte em minutos | |
return extraHour; | |
} | |
return 0; | |
} | |
///////// View | |
function getDataFromTable() { | |
const tableRowsHtml = document.querySelectorAll('table#pendencias-table tbody tr'); | |
const dates = Array.from(tableRowsHtml) | |
.filter(rowHtml => rowHtml.getElementsByTagName('td')[1]) | |
.filter(rowHtml => rowHtml.getElementsByTagName('td')[1].innerText == 'Ausência de marcação' && rowHtml.getAttribute("data-date")) | |
.map(rowHtml => rowHtml.getAttribute("data-date")); | |
return dates; | |
} | |
///////// Execution | |
console.warn(`ATENÇÃO | |
A execuçao desse algoritmo, eh de unica e restrita responsabilidade do executor! | |
Não use se não souber o que está fazendo!`); | |
console.info('============= START PROCESS ============='); | |
const _dl = getDataFromTable() | |
let arrayOfRandomEndHour = createArrayOfRandomEndHours(_dl.length); | |
const extraHour = questionAboutExtraHour(arrayOfRandomEndHour); | |
if(extraHour){ | |
arrayOfRandomEndHour = applyExtraHour(arrayOfRandomEndHour, extraHour) | |
} | |
// TODO: Questinoar sobre horas extras | |
// TODOL aplicar as horas extras no array arrayOfRandomEndHour | |
if(confirm('Voce deseja executar o lançamento?')){ | |
sendDates(_dl, arrayOfRandomEndHour) | |
.then(() => console.info('============= END PROCESS =============')) | |
.catch(() => console.error('============= END PROCESS WITH ERROR =============') || console.error(e)) | |
}else{ | |
window.location.reload(); | |
} | |
rennanc
commented
Mar 27, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment