
DECLARE @Store	VARCHAR(15) = '00048' 
DECLARE @Month			INT = 5
DECLARE @Year			INT = 2019

DECLARE @ReopenMonth	BIT = 1 -- 1 = reopen the month if it was closed
DECLARE @ResendToCFA	BIT = 0 -- 1 = resend data to CFA Endpoints (may require configuration on CFA's side)
DECLARE @Status			INT = 1 -- 0 for Open, 1 for Done

DECLARE @EntityId BIGINT = (select top 1 EntityId from tbEntity where StoreNumber like @Store)
DECLARE @ApplicablePeriod DATETIME = DATETIMEFROMPARTS ( @Year, @Month, 1, 0, 0, 0, 0)

IF @ReopenMonth = 1
BEGIN
	DELETE FROM tbPeriodClose WHERE EntityId = @EntityId AND CalendarDay = @ApplicablePeriod
	UPDATE tbEndOfMonthStatusCheck SET MarkMonthEndSentToCfa = 0 WHERE EntityId = @EntityId and ApplicablePeriod = @ApplicablePeriod
END

UPDATE dbo.tbEndOfMonthStatusCheck SET
	StockCountApplyStatus = @Status,
	DayFinalizeStatus = @Status,
	GiveawaysStatus = @Status,
	SupplierInvoiceStatus = @Status,
	WageAccrualStatus = @Status,
	UtilityThresholdStatus = @Status,
	ExpenseTransferStatus = @Status,
	ExpenseUnpaidStatus = @Status,
	ReportsStatus = @Status,
	CommentsStatus = @Status,
	RefillsStatus = @Status,
	AccrualsAndReversalsStatus = @Status,
	InventoryCostSummarySentToCfa = @Status,
	InventoryCostDetailSentToCfa = @Status
WHERE EntityId = @EntityId and ApplicablePeriod = @ApplicablePeriod

IF @ResendToCFA = 1
BEGIN
	UPDATE dbo.tbEndOfMonthStatusCheck SET	
		UtilityThresholdSentToCfa = @Status,
		AccrualsAndReversalsSentToCfa = @Status,
		ExpenseTransferSentToCfa = @Status,
		ExpenseUnpaidSentToCfa = @Status,
		WageAccrualSentToCfa = @Status,
		CommentsSentToCfa = @Status,
		RefillsSentToCfa = @Status,
		MarkMonthEndSentToCfa = @Status,
		InventoryCostSummarySentToCfa = @Status,
		InventoryCostDetailSentToCfa = @Status	
	WHERE EntityId = @EntityId and ApplicablePeriod = @ApplicablePeriod
END

EXEC [dbo].[MXC_GetOrInsertEOMStatusCheckByEntityIdMonth] @EntityId, @ApplicablePeriod