I went looking for a function to pass in a start date and duration and get an end date based on working days from a production calendar. I found some good posts that described the right method, but not necessarily in the current Function format. So I took to ChatGPT and made a working one that I wanted to share.
References: ERP:BO:ProdCal
Signature:
Function Code:
// Step 1: Validate input
if (!StartDate.HasValue)
throw new ArgumentException("StartDate cannot be null.");
DateTime startDate = StartDate.Value;
string calendar = string.IsNullOrWhiteSpace(CalendarID) ? "Office" : CalendarID;
DateTime currentDate = startDate;
int workDayCount = 0;
EndDate = startDate;
// Step 2: Load all modified (exception) calendar days using GetRows
HashSet<DateTime> modifiedDays = new HashSet<DateTime>();
this.CallService<Erp.Contracts.ProdCalSvcContract>(svc =>
{
var ts = new Erp.Tablesets.ProdCalTableset();
bool morePages;
svc.GetRows(
$"CalendarID = '{calendar}'", // whereClause
"", // orderByClause
"", // tableName
"", // fieldList
"", // keyFields
0, // pageSize
1, // absolutePage
out morePages
);
foreach (var row in ts.ProdCalDay)
{
if (row.ModifiedDay.HasValue)
{
modifiedDays.Add(row.ModifiedDay.Value.Date);
}
}
});
// Step 3: Loop forward until the required number of working days is counted
while (workDayCount < Duration)
{
currentDate = currentDate.AddDays(1);
bool isWorkDay = false;
this.CallService<Erp.Contracts.ProdCalSvcContract>(svc =>
{
svc.IsWorkDay(calendar, currentDate, out isWorkDay);
});
// Count if it's a regular workday and not in the modified day list
if (isWorkDay && !modifiedDays.Contains(currentDate.Date))
{
workDayCount++;
}
}
// Step 4: Set result
EndDate = currentDate;
Hope this helps someone else out in the future!
