Help

Welcome to the Airtable Community! If you're new here, check out our Getting Started area to get the most out of your community experience.

How to determinate dates for any record without repeat day and hour

Topic Labels: Scripting extentions
393 0
cancel
Showing results for 
Search instead for 
Did you mean: 

I Have this code

let settings = input.config({
    title: "Datas aleatórias",
    description: ``,
    items: [
        input.config.table("table", { label: "Table" }),
        input.config.field("field", {
            parentTable: "table",
            label: "Field to randomize",
        }),
    ],
});

let { table, field } = settings;

output.text(`Randomizing ${field.name} field in ${table.name}.`);

let bounds;
switch (field.type) {    
    case "date":
        bounds = await inputBounds(async () => {
            let min = await inputDate("What should the earliest date be?");
            let max = await inputDate("What should the latest date be?");
            return await confirmBounds(min, max);
        });
        await updateField((record) =>  lerpDate(bounds.min, bounds.max, record));
        break;
    case "dateTime":
        bounds = await inputBounds(async () => {
            let min = await inputDate("What should the earliest date time be?");
            let max = await inputDate("What should the latest date time be?");
            return await confirmBounds(min, max);
        });
        
        await updateField((record) => lerpDate(bounds.min, bounds.max, record));
        break;   
    default:
        output.text(
            `'${field.name}' is a '${field.type}' and cannot be randomized. You can customize this script and add an algorithm to randomize this field, or change the settings to randomize a different field.`
        );
        break;
}

output.text("Run again to randomize another field.");


function lerp(i, j, round = Math.round) {
    return round((j - i) * Math.random()) + i;
}

/**
 * @param {Date} i
 * @param {Date} j
 */
async function lerpDate(i, j, record, round = Math.round) {
    let randomDate = new Date(round(lerp(i.getTime(), j.getTime())));   
    let tipo = record.getCellValueAsString("Tipo");
       
    let dayOfWeek = randomDate.getDay();
    if(tipo.includes('Café Da Manhã') && tipo.includes('Janta')){
        var horas = [8, 19];
        var index = Math.floor(Math.random() * horas.length);
        randomDate.setHours(horas[index]);
    } 
    else if (tipo.includes('Café Da Manhã')){             
        randomDate.setHours(8);
    }
    if(tipo.includes('Almoço') && tipo.includes('Janta')){            
        var horas = [12, 19];
        var index = Math.floor(Math.random() * horas.length);
        randomDate.setHours(horas[index]);            
    }
    else if(tipo.includes('Almoço')){         
        randomDate.setHours(12);
    }
    else if (tipo.includes('Janta')){        
        randomDate.setHours(19);
        
    }
    else if( tipo.includes('Sobrmesa')){       
        randomDate.setHours(12);      
        if(dayOfWeek < 5){
            randomDate.setDate(randomDate.getDate() + (5 - dayOfWeek));
        }
        else if (dayOfWeek > 5){
            randomDate.setDate(randomDate.getDate() - 1);
        }       
    }
    else if( tipo.includes('Petisco')){               
        randomDate.setDate(randomDate.getDate() + (6 - dayOfWeek));     
        randomDate.setHours(14);
    }
    if(dayOfWeek < 1 && !(tipo.includes('Vegano') || tipo.includes('Vegetariano'))){
        randomDate.setDate(randomDate.getDate() + 1)

    }
    if (tipo.includes('Vegano') || tipo.includes('Vegetariano')){      
        if(dayOfWeek < 1){
            var dia = [(randomDate.getDate() +1),(randomDate.getDate() +8),(randomDate.getDate() - 6)];
            var index = Math.floor(Math.random() * dia.length);
            randomDate.setDate(dia[index]);
        }
        else if (dayOfWeek > 1){
            randomDate.setDate(randomDate.getDate() - (dayOfWeek - 1));
        }
    }
    for (let record2 of (await table.selectRecordsAsync({ fields: ["Dia de Preparo", "Tipo"] }))
    .records) {
        let diaDePreparo = new Date(record2.getCellValue(field));
        if(diaDePreparo.getDate() == randomDate.getDate() && diaDePreparo.getMonth() == randomDate.getMonth() && diaDePreparo.getHours() == randomDate.getHours()){
            randomDate.setDate(randomDate.getDate() + 1)
            if(randomDate.getDay() == 3){
                randomDate.setDate(randomDate.getDate() + Math.floor(Math.random() * (7 - 1 + 1) + 1))
            }
            if (tipo.includes('Vegano') || tipo.includes('Vegetariano')){
                let dayOfWeek = randomDate.getDay();
                if(dayOfWeek < 1){
                    var dia = [(randomDate.getDate() +1),(randomDate.getDate() +8)];
                    var index = Math.floor(Math.random() * dia.length);
                    randomDate.setDate(dia[index]);
                }else if (dayOfWeek > 1){     
                    randomDate.setDate(randomDate.getDate() + (8 - dayOfWeek));
                } 
            }
            else if( tipo.includes('Petisco')){
                let dayOfWeek = randomDate.getDay();        
                randomDate.setDate(randomDate.getDate() - (3 - dayOfWeek));
            }
            else if( tipo.includes('Sobrmesa')){        
                let dayOfWeek = randomDate.getDay();        
                if(dayOfWeek < 5){
                    randomDate.setDate(randomDate.getDate() + (5 - dayOfWeek));
                }
                else if (dayOfWeek > 5){
                    randomDate.setDate(randomDate.getDate() - 1);
                }                
            }
        }
    }
    if(randomDate.getDay() == 3){
        randomDate.setDate(randomDate.getDate() + 1)
    }
    randomDate.setMinutes(0);
    return randomDate;    
}

async function inputDate(label) {
    return new Date(await input.textAsync(label || ""));
}

async function confirmBounds(min, max) {
    if (
        await input.buttonsAsync(
            `Randomize this field from '${min} to ${max}'?`,
            [
                { label: "Yes", value: true },
                { label: "No", value: false },
            ]
        )
    ) {
        return { min, max };
    }
}

async function inputBounds(fn) {
    let bounds;
    do {
        bounds = fn();
    } while (!bounds);
    return bounds;
}

/**
 * @param {(record: Record) => any} fn
 */
async function updateField(fn) {
    let updates = [];
    for (let record of (await table.selectRecordsAsync({ fields: ["Dia de Preparo", "Tipo"] }))
        .records) {
        output.text(record.id);
        await table.updateRecordAsync( record.id, { [field.id]: await fn(record) } );
        output.text(JSON.stringify(updates[updates.length - 1]));        
    }
    for (let i = 0; i < updates.length; i += 50) {
        output.text(`update ${i} - ${i + 50}`);
        await table.updateRecordsAsync(updates.slice(i, i + 50));
    }
}

but it doesn’t do what i want, i need only one meal per type (almoço, janta, café da manhã), except wednesday and mondays only have vegetarian/vegan options.

Dessert twice a week and snacks on Sunday

0 Replies 0