Change client script to lock timesheet on last Saturday

I want my Timesheet to be locked on every Saturday. Before that Saturday no one should be able to fill the timesheet. I tried changing the script, but it locks all weeks. Can someone help with the updated script.

This is the original script from Frappe Documentation

frappe.ui.form.on("Timesheet", "validate", function(frm) {
    if (frappe.user_roles.indexOf("Projects Manager") == -1) {
        const t = new Date().getDate() + (6 - new Date().getDay() - 1) - 7;
        const lastFriday = new Date();
        lastFriday.setDate(t);

        let dd = lastFriday.getDate();
        let mm = lastFriday.getMonth() + 1;
        let yyyy = lastFriday.getFullYear();

        frm.doc.time_logs.forEach(log => {
            if (new Date(log.from_time) <= lastFriday) {
                frappe.throw("You cannot add timesheet for dates before last Friday " + dd + "/" + mm + "/" + yyyy + ". Please contact your Project Manager.");
            }
        })
    }
})

This is the script I created

frappe.ui.form.on("Timesheet", "validate", function(frm) {
    if (frappe.user_roles.indexOf("Projects Manager") == -1) {
        const t = new Date().getDate() + (6 - new Date().getDay());
        const lastSaturday = new Date();
        lastSaturday.setDate(t);

        let dd = lastSaturday.getDate();
        let mm = lastSaturday.getMonth() + 1;
        let yyyy = lastSaturday.getFullYear();

        frm.doc.time_logs.forEach(log => {
            if (new Date(log.from_time) <= lastSaturday) {
                frappe.throw("You cannot add timesheet for dates before last Saturday " + dd + "/" + mm + "/" + yyyy + ".");
            }
        });
    }
});

Please apply it.

frappe.ui.form.on("Timesheet", {
    validate: function(frm) {
        if (frappe.user_roles.indexOf("Projects Manager") == -1) {
            var today = new Date();
            var todayDay = today.getDay();
            var daysUntilNextSaturday = 6 - todayDay;
    
            var nextSaturday = new Date();
            nextSaturday.setDate(today.getDate() + daysUntilNextSaturday);
    
            let dd = nextSaturday.getDate();
            let mm = nextSaturday.getMonth() + 1;
            let yyyy = nextSaturday.getFullYear();
    
            frm.doc.time_logs.forEach(log => {
                if (new Date(log.from_time) < nextSaturday) {
                    frappe.throw("You cannot add timesheet entries for dates before the upcoming Saturday " + dd + "/" + mm + "/" + yyyy + ".");
                }
            });
        }
    }
});

Then reload and check.

1 Like