Files
advertising-profit-control/AdvertsingProfitControl/FrmMain.cs
T

1172 lines
55 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace AdvertsingProfitControl
{
public partial class FrmMain : Form
{
private double _salesProducedByAdItems;
private double _totalProfitReturnFromAdItems;
private double _totalInvoicePurchases; //Total Purchases
private double _departmentSales; //weekly sales total
readonly FrmLogConsole _console = FrmLogConsole.GetStaticInstance;
private int _LazyPageCounter = 0;
public FrmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
var databaseTracker = new DatabaseTracker();
var databaseReader = new DatabaseReader();
RowParsing.AdSpecialGroups.AddRange(databaseReader.ReturnGroupNameList(databaseTracker.DatabaseConnectionString));
ConstructApcDataGridViews();
ConstructInvoicesDataGridView();
var date = databaseReader.RetrieveMostRecentDate(databaseTracker.DatabaseConnectionString);
monthCalendar.SelectionStart = date;
LoadDate(date);
CalculateProfitAnalysis();
CalculateGrossProfit();
//projectionsDataGridView.KeyDown += FrmMain_KeyDown;
//var margin = new Margins(50, 50, 0, 0);
//_printDoc.DefaultPageSettings.Margins = margin;
}
private void CalculateProfitAnalysis(double shrink = 0.30)
{
var incompleteData = false;
//First grab the total sales and the total profit return generated by the actual sales of product.
if (
double.TryParse(
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[3].EditedFormattedValue
.ToString(), out _salesProducedByAdItems))
{
//The sales parsed properly so there is data in the cell. Next try to grab the total profit return.
if (double.TryParse(
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[6].EditedFormattedValue
.ToString(), out _totalProfitReturnFromAdItems))
{
}
}
if (Math.Abs(_salesProducedByAdItems) < 1)
{
salesProducedLabel.Text = @"Sales Produced By Ad Items (A): No Data";
incompleteData = true;
}
if (Math.Abs(_totalProfitReturnFromAdItems) < 1)
{
totalProfitFromAdItemsLabel.Text = @"Total Profit Return From Ad Items (B): No Data";
incompleteData = true;
}
if (Math.Abs(_departmentSales) < 1)
{
departmentSalesLabel.Text = @"Department Sales: No Data";
incompleteData = true;
}
if (incompleteData)
{
return;
}
departmentSalesLabel.Text = @"Department Sales: " + _departmentSales.ToString("C");
salesProducedLabel.Text = @"Sales Produced By Ad Items (A): " + _salesProducedByAdItems.ToString("C");
//Calculate the remaining sales.
var remainingSales = _departmentSales - _salesProducedByAdItems;
remainingSalesLabel.Text = @"Remaining Sales: " + remainingSales.ToString("C");
//Again assume the total profit return is larger then zero (0).
totalProfitFromAdItemsLabel.Text = @"Total Profit Return From Ad Items (B): " + _totalProfitReturnFromAdItems.ToString("C");
//Shrink is being used as a place holder for Cross Profit % which is obtained by dividing the total profit return from the department weekly retail sales.
var totalProfitReturnFromRemainingSales = shrink*remainingSales;
//
totalProfitReturnFromRemaingLabel.Text = @"Total Profit Return From Remaining Sales: " + totalProfitReturnFromRemainingSales.ToString("C");
var totalProfitReturn = _totalProfitReturnFromAdItems + totalProfitReturnFromRemainingSales;
totalProfitReturnLabel.Text = @"Total Profit Return: " + totalProfitReturn.ToString("C");
}
private void CalculateGrossProfit()
{
if (Math.Abs(_totalInvoicePurchases) < 1)
{
//IF Cost of Sales hasn't been calculated, then clear labels and return.
if (Math.Abs(_departmentSales) < 1)
{
grossProfitTotalSales.Text = @"Total Sales: No Data";
}
grossProfitLessCostOfSales.Text = @"Less Cost of Sales: No Data";
return;
}
grossProfitTotalSales.Text = @"Total Sales: " + _departmentSales.ToString("C");
grossProfitLessCostOfSales.Text = @"Less Cost of Sales: " + _totalInvoicePurchases.ToString("C");
var dollarGrossProfit = _departmentSales - _totalInvoicePurchases;
grossProfitDollarGrossProfitLabel.Text = @"Dollar Gross Profit: " + dollarGrossProfit.ToString("C");
var grossProfitPercent = dollarGrossProfit/_departmentSales;
perfectGrossProfitLabel.Text = @"Percent Gross Profit: " + grossProfitPercent.ToString("P");
}
private void addRecordToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = new NewAddRecord();
form.ShowDialog();
}
private void showHideConsoleHelpMainMenu_Click(object sender, EventArgs e)
{
if (_console.IsVisable)
{
_console.Hide();
}
else
{
_console.Show();
}
}
private void deleteRecordsMainMenu_Click(object sender, EventArgs e)
{
var frmDeleteRecord = new FrmDeleteRecord();
frmDeleteRecord.ShowDialog();
CalculateProfitAnalysis();
CalculateGrossProfit();
}
private void modifyRecordMainMenu_Click(object sender, EventArgs e)
{
var form = new NewModifyRecord(monthCalendar.SelectionStart);
form.ShowDialog();
}
private void manageItemsToolsMainMenu_Click(object sender, EventArgs e)
{
var adItemManager = new FrmManageAdItems();
adItemManager.ShowDialog();
}
private void dbVersionHelpMainMenu_Click(object sender, EventArgs e)
{
var databaseTracker = new DatabaseTracker();
var databaseReader = new DatabaseReader();
var version = databaseReader.GetDatabaseVersion(databaseTracker.DatabaseConnectionString);
if (version != "0.0.0.0")
{
MessageBox.Show("The current database's version is " + version + ".", "Database Version Number");
}
}
private void PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bitMap;
if (_LazyPageCounter == 0)
{
bitMap = new Bitmap(Application.StartupPath + "\\FrontPage.png");
}
else
{
bitMap = new Bitmap(Application.StartupPath + "\\BackPage.png");
}
var rect = e.MarginBounds;
if ((double) bitMap.Width/(double) bitMap.Height > (double) rect.Width/(double) rect.Height)
// image is wider
{
rect.Height = (int) ((double) bitMap.Height/(double) bitMap.Width*(double) rect.Width);
}
else
{
rect.Width = (int) ((double) bitMap.Width/(double) bitMap.Height*(double) rect.Height);
}
if (_LazyPageCounter == 0)
{
e.Graphics.DrawImage(bitMap, new Rectangle(0, 25, 850, 1050));
_LazyPageCounter++;
e.HasMorePages = true;
}
else
{
e.Graphics.DrawImage(bitMap, new Rectangle(0, 0, 850, 1100));
_LazyPageCounter = 0;
e.HasMorePages = false;
}
}
private void DisplayPrintPreview(object sender, EventArgs e)
{
//Build and render the front and back forms of the document.
var test = new FrontPageGenerator();
var backPageTest = new BackPageGenerator();
var printTestPage = new PrintDocument();
var printDialog = new PrintPreviewDialog();
if (!usePreRenderedFilesCheckbox.Checked)
{
var databaseTracker = new DatabaseTracker();
var databaseReader = new DatabaseReader();
var dateId =
databaseReader.RetrieveDateIdByDateString(monthCalendar.SelectionStart.ToShortDateString(),
databaseTracker.DatabaseConnectionString);
double remaingingSales = _departmentSales - _salesProducedByAdItems;
double totalProfitReturnFromReminaingSales = remaingingSales*.3;
double totalProfitReturn = _totalProfitReturnFromAdItems + totalProfitReturnFromReminaingSales;
test.BuildFormFrontCompressedLayout(dateId, _departmentSales, _salesProducedByAdItems, remaingingSales,
_totalProfitReturnFromAdItems, totalProfitReturnFromReminaingSales, totalProfitReturn,
commentsTextBox.Text);
test.RenderHtmlToImage();
backPageTest.GenerateWeeklyInventoryControlPage(dateId);
backPageTest.RenderHtmlToImage();
}
else
{
if (File.Exists(Application.StartupPath + "\\" + "FrontPage.html") &&
File.Exists(Application.StartupPath + "\\" + "Backpage.html"))
{
test.RenderHtmlToImage();
backPageTest.RenderHtmlToImage();
}
}
//var margin = new Margins(50, 50, 0, 0);
//printDoc.DefaultPageSettings.Margins = margin;
printTestPage.PrintPage += PrintPage;
printDialog.Document = printTestPage;
printDialog.ShowDialog();
printDialog.Document = new PrintDocument();
}
private void newFormTestToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = new NewAddRecord();
form.ShowDialog();
}
private void newModifyRecordToolStripMenuItem_Click(object sender, EventArgs e)
{
var date = monthCalendar.SelectionStart;
var form = new NewModifyRecord(date);
form.ShowDialog();
}
public enum FormRoll
{
AddRecords = 0,
ModifyRecords = 1,
DeleteRecords = 2
}
/// <summary>
/// Fills the APC DataGridViews with the appropriate columns and starting row for the user to start
/// entering data.
/// </summary>
private void ConstructApcDataGridViews()
{
//Construct a list of column names for the inventory/actual sales DataGridViews and the inventory DataGirdView.
string[] saleColumnNames =
{
"AdItem", "Sold", "SalePrice", "TotalSales", "Cost", "ProfitReturn",
"TotalProfitReturn"
};
string[] inventoryColumnNames =
{
"AdItem", "BeginningInventory", "Received", "Total", "EndingInventory"
};
foreach (var name in saleColumnNames)
{
var column = new DataGridViewTextBoxColumn
{
Name = name,
HeaderText = TextFormat.AddSpacesToSentence(name, false),
ValueType = typeof(string),
SortMode = DataGridViewColumnSortMode.NotSortable,
MaxInputLength = 20
};
projectionsDataGridView.Columns.Add(column);
}
//Add the columns into the inventory DataGridView after setting their types.
foreach (var name in inventoryColumnNames)
{
var column = new DataGridViewTextBoxColumn
{
Name = name,
HeaderText = TextFormat.AddSpacesToSentence(name, false),
ValueType = typeof(string),
SortMode = DataGridViewColumnSortMode.NotSortable,
MaxInputLength = 20
};
inventoryDataGridView.Columns.Add(column);
}
//
foreach (var name in saleColumnNames)
{
var column = new DataGridViewTextBoxColumn
{
Name = name,
HeaderText = TextFormat.AddSpacesToSentence(name, false),
ValueType = typeof(string),
SortMode = DataGridViewColumnSortMode.NotSortable,
MaxInputLength = 20
};
actualSalesDataGridView.Columns.Add(column);
}
}
/// <summary>
/// Constructs the invoices DataGridView.
/// </summary>
private void ConstructInvoicesDataGridView()
{
string[] invoicesColumnNames =
{
"InvoiceDate", "Supplier", "InvoiceNumber", "InvoiceNetAmountAtCost",
"InvoiceNetAmount", "InvoiceNote"
};
foreach (var name in invoicesColumnNames)
{
var column = new DataGridViewTextBoxColumn
{
Name = name,
HeaderText = TextFormat.AddSpacesToSentence(name, false),
ValueType = typeof(string),
SortMode = DataGridViewColumnSortMode.NotSortable,
MaxInputLength = 20
};
invoicesDataGridView.Columns.Add(column);
}
}
private void LoadDate(DateTime date)
{
var databaseTracker = new DatabaseTracker();
var databaseReader = new DatabaseReader();
var dateId = databaseReader.RetrieveDateIdByDateString(date.ToString("d"),
databaseTracker.DatabaseConnectionString);
if (dateId == 0)
{
errorLabel.Text = @"Failed to get the date ID number, aborting load operation." + Environment.NewLine;
return;
}
informationLabel.Text = @"Loading data for " + date.ToString("d") + "." + Environment.NewLine;
var projections = databaseReader.ReturnProjectionsTable(dateId, databaseTracker.DatabaseConnectionString);
var inventory = databaseReader.ReturnInventoryTable(dateId, databaseTracker.DatabaseConnectionString);
var actualSales = databaseReader.ReturnActualSales(dateId, databaseTracker.DatabaseConnectionString);
LoadProjectionsTable(projections);
LoadInventoryTable(inventory);
LoadActualSalesTable(actualSales);
var invoices = databaseReader.ReturnInvoiceTable(dateId, databaseTracker.DatabaseConnectionString);
LoadInvoices(invoices);
var comments = databaseReader.RetrieveComments(int.Parse(dateId.ToString()),
databaseTracker.DatabaseConnectionString);
if (comments.Count == 2)
{
commentsTextBox.Text = comments[1];
}
else
{
informationLabel.Text += @"No comments to display." + Environment.NewLine;
}
var weeklySales = databaseReader.ReturnWeeklySalesFromDateId(dateId,
databaseTracker.DatabaseConnectionString);
if (weeklySales.Rows.Count == 1)
{
LoadWeeklySales(weeklySales);
}
else
{
informationLabel.Text += @"No sales to display." + Environment.NewLine;
}
var taxable = databaseReader.ReturnTaxableFromDateId(dateId, databaseTracker.DatabaseConnectionString);
if (taxable.Rows.Count == 1)
{
LoadTaxable(taxable);
}
else
{
informationLabel.Text += @"No taxable data to display." + Environment.NewLine;
}
var costAnalysis = databaseReader.ReturnCostAnalysis(dateId,
databaseTracker.DatabaseConnectionString);
if (costAnalysis.Rows.Count == 1)
{
LoadCostAnalysis(costAnalysis);
}
else
{
informationLabel.Text += @"No cost analysis data to display." + Environment.NewLine;
}
}
private void LoadProjectionsTable(DataTable projections)
{
if (projections.Rows.Count == 0) return;
var adSpecialIndex = -1;
double totalSales = 0;
double totalProfitReturn = 0;
for (var rowIndex = 0; rowIndex < projections.Rows.Count; rowIndex++)
{
var newRow = new DataGridViewRow();
for (var cellIndex = 0; cellIndex < projections.Rows[rowIndex].ItemArray.Length; cellIndex++)
{
//ID and Ad Item.
if (cellIndex == 1)
{
var cell = new DataGridViewTextBoxCell
{
Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString()
};
newRow.Cells.Add(cell);
continue;
}
//String allowed columns
if (cellIndex > 1 && cellIndex <= 3)
{
if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty)
{
var cell = new DataGridViewTextBoxCell
{
Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString()
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//If the cell is meant to be summed into a totals roll add its contents to the total.
//If the cell is the total sales cell..
if (cellIndex == 4)
{
if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty &&
Math.Abs(double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
{
totalSales += double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString());
var cell = new DataGridViewTextBoxCell
{
Value =
double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())
.ToString("N2")
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//or the total profit return cell.
if (cellIndex == 7)
{
if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty &&
Math.Abs(double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
{
totalProfitReturn += double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString());
var cell = new DataGridViewTextBoxCell
{
Value =
double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())
.ToString("N2")
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//Everything in between the ad item cell and the row attribute cells.
if (cellIndex > 3 && cellIndex < 8)
{
if (Math.Abs(double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
{
var cell = new DataGridViewTextBoxCell
{
Value =
double.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString())
.ToString("N2")
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//Check the attribute cell.
if (cellIndex == 8)
{
var rowAttribute = int.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString());
switch (rowAttribute)
{
case 1:
//Header row
newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
break;
case 2:
//Member Row
newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
break;
}
continue;
}
//Check the group it is part of if any.
if (cellIndex != 9) continue;
//Check to see if this row belongs to an ad special group.
if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0") continue;
//If the ad special index is not set, then create the ad special row with the human friendly group name.
if (adSpecialIndex != -1) continue;
var databaseTracker = new DatabaseTracker();
var databaseReader = new DatabaseReader();
var groupName =
databaseReader.ReturnGroupNameFromGroupId(
projections.Rows[rowIndex].ItemArray[cellIndex].ToString(),
databaseTracker.DatabaseConnectionString);
var adSpecialRow = new DataGridViewRow();
projectionsDataGridView.Rows.Add(adSpecialRow);
projectionsDataGridView.Rows[rowIndex].Cells[3].Value = groupName;
projectionsDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor =
ApplicationColors.AdSpecial;
adSpecialIndex = rowIndex;
}
projectionsDataGridView.Rows.Add(newRow);
}
//Now add the totals row.
var totalsRow = new DataGridViewRow();
projectionsDataGridView.Rows.Add(totalsRow);
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[0].Value = "Total";
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[2].Style.Alignment =
DataGridViewContentAlignment.MiddleRight;
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[2].Value = @"(A)";
if (Math.Abs(totalSales) > 0)
{
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[3].Value =
totalSales.ToString("N2");
}
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[5].Style.Alignment =
DataGridViewContentAlignment.MiddleRight;
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[5].Value = @"(B)";
if (Math.Abs(totalProfitReturn) > 0)
{
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[6].Value =
totalProfitReturn.ToString("N2");
}
}
private void LoadInventoryTable(DataTable inventory)
{
if (inventory.Rows.Count == 0) return;
var adSpecialIndex = -1;
for (var rowIndex = 0; rowIndex < inventory.Rows.Count; rowIndex++)
{
var newRow = new DataGridViewRow();
for (var cellIndex = 1; cellIndex < inventory.Rows[rowIndex].ItemArray.Length; cellIndex++)
{
//String allowed columns
if (cellIndex < 6)
{
if (inventory.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty)
{
var cell = new DataGridViewTextBoxCell
{
Value = inventory.Rows[rowIndex].ItemArray[cellIndex].ToString()
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//Check the attribute cell.
if (cellIndex == 6)
{
var rowAttribute = int.Parse(inventory.Rows[rowIndex].ItemArray[cellIndex].ToString());
switch (rowAttribute)
{
case 1:
//Header row
newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
break;
case 2:
//Member Row
newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
break;
}
continue;
}
//Check the group it is part of if any.
if (cellIndex != 7) continue;
//Check to see if this row belongs to an ad special group.
if (inventory.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0") continue;
//If the ad special index is not set, then create the ad special row with the human friendly group name.
if (adSpecialIndex != -1) continue;
var databaseTracker = new DatabaseTracker();
var databaseReader = new DatabaseReader();
var groupName =
databaseReader.ReturnGroupNameFromGroupId(
inventory.Rows[rowIndex].ItemArray[cellIndex].ToString(),
databaseTracker.DatabaseConnectionString);
var adSpecialRow = new DataGridViewRow();
inventoryDataGridView.Rows.Add(adSpecialRow);
inventoryDataGridView.Rows[rowIndex].Cells[2].Value = groupName;
inventoryDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor =
ApplicationColors.AdSpecial;
adSpecialIndex = rowIndex;
}
inventoryDataGridView.Rows.Add(newRow);
}
}
private void LoadActualSalesTable(DataTable actualSales)
{
if (actualSales.Rows.Count == 0) return;
var adSpecialIndex = -1;
double totalSales = 0;
double totalProfitReturn = 0;
for (var rowIndex = 0; rowIndex < actualSales.Rows.Count; rowIndex++)
{
var newRow = new DataGridViewRow();
for (var cellIndex = 0; cellIndex < actualSales.Rows[rowIndex].ItemArray.Length; cellIndex++)
{
//ID and Ad Item.
if (cellIndex == 1)
{
var cell = new DataGridViewTextBoxCell
{
Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString()
};
newRow.Cells.Add(cell);
continue;
}
//String allowed columns
if (cellIndex > 1 && cellIndex <= 3)
{
if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty)
{
var cell = new DataGridViewTextBoxCell
{
Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString()
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//If the cell is meant to be summed into a totals roll add its contents to the total.
//If the cell is the total sales cell..
if (cellIndex == 4)
{
if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty &&
Math.Abs(double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
{
totalSales += double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString());
var cell = new DataGridViewTextBoxCell
{
Value =
double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())
.ToString("N2")
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//or the total profit return cell.
if (cellIndex == 7)
{
if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() != string.Empty &&
Math.Abs(double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
{
totalProfitReturn += double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString());
var cell = new DataGridViewTextBoxCell
{
Value =
double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())
.ToString("N2")
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//Everything in between the ad item cell and the row attribute cells.
if (cellIndex > 3 && cellIndex < 8)
{
if (Math.Abs(double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())) > 0)
{
var cell = new DataGridViewTextBoxCell
{
Value =
double.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString())
.ToString("N2")
};
newRow.Cells.Add(cell);
}
else
{
var cell = new DataGridViewTextBoxCell {Value = string.Empty};
newRow.Cells.Add(cell);
}
continue;
}
//Check the attribute cell.
if (cellIndex == 8)
{
var rowAttribute = int.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString());
switch (rowAttribute)
{
case 1:
//Header row
newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
break;
case 2:
//Member Row
newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
break;
}
continue;
}
//Check the group it is part of if any.
if (cellIndex != 9) continue;
//Check to see if this row belongs to an ad special group.
if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0") continue;
//If the ad special index is not set, then create the ad special row with the human friendly group name.
if (adSpecialIndex != -1) continue;
var databaseTracker = new DatabaseTracker();
var databaseReader = new DatabaseReader();
var groupName =
databaseReader.ReturnGroupNameFromGroupId(
actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString(),
databaseTracker.DatabaseConnectionString);
var adSpecialRow = new DataGridViewRow();
actualSalesDataGridView.Rows.Add(adSpecialRow);
actualSalesDataGridView.Rows[rowIndex].Cells[3].Value = groupName;
actualSalesDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor =
ApplicationColors.AdSpecial;
adSpecialIndex = rowIndex;
}
actualSalesDataGridView.Rows.Add(newRow);
}
//Now add the totals row.
var totalsRow = new DataGridViewRow();
actualSalesDataGridView.Rows.Add(totalsRow);
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[0].Value = "Total";
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[2].Style.Alignment =
DataGridViewContentAlignment.MiddleRight;
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[2].Value = @"(A)";
if (Math.Abs(totalSales) > 0)
{
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[3].Value =
totalSales.ToString("N2");
}
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[5].Style.Alignment =
DataGridViewContentAlignment.MiddleRight;
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[5].Value = @"(B)";
if (Math.Abs(totalProfitReturn) > 0)
{
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[6].Value =
totalProfitReturn.ToString("N2");
}
}
private void LoadInvoices(DataTable invoices)
{
if (invoices.Rows.Count == 0) return;
_totalInvoicePurchases = 0;
for (var rowIndex = 0; rowIndex < invoices.Rows.Count; rowIndex++)
{
var row = new DataGridViewRow();
for (var cellIndex = 1; cellIndex < invoices.Rows[rowIndex].ItemArray.Length; cellIndex++)
{
var cell = new DataGridViewTextBoxCell();
switch (cellIndex)
{
//Apply formatting to the invoice date to trim the 12:00:00 time stamp.
case 1:
var date = DateTime.Parse(invoices.Rows[rowIndex].ItemArray[cellIndex].ToString());
cell.Value = date.ToString("d");
row.Cells.Add(cell);
continue;
//Apply formatting to the only cells that will have currency values in them.
case 4:
var netAmountAtCost = double.Parse(invoices.Rows[rowIndex].ItemArray[cellIndex].ToString()).ToString("N2");
if (netAmountAtCost != "0.00")
{
cell.Value = netAmountAtCost;
}
row.Cells.Add(cell);
break;
case 5:
var netAmoundExtendedRetail = double.Parse(invoices.Rows[rowIndex].ItemArray[cellIndex].ToString());
if (netAmoundExtendedRetail.ToString("N2") != "0.00")
{
_totalInvoicePurchases += netAmoundExtendedRetail;
cell.Value = netAmoundExtendedRetail.ToString("N2");
}
row.Cells.Add(cell);
break;
default:
//No special formatting rules here so just put the value in and move on.
cell.Value = invoices.Rows[rowIndex].ItemArray[cellIndex].ToString();
row.Cells.Add(cell);
break;
}
}
invoicesDataGridView.Rows.Add(row);
}
//Add the total purchases row to the invoice table.
var totalPurchaesRow = new DataGridViewRow();
invoicesDataGridView.Rows.Add(totalPurchaesRow);
invoicesDataGridView.Rows[invoicesDataGridView.Rows.Count - 1].Cells[0].Value = @"Total Purchases";
if (Math.Abs(_totalInvoicePurchases) > 0)
{
invoicesDataGridView.Rows[invoicesDataGridView.Rows.Count - 1].Cells[4].Value = _totalInvoicePurchases.ToString("N2");
}
}
private void LoadWeeklySales(DataTable weeklySales)
{
//Clear the department sales and prepare to add up a total.
_departmentSales = 0;
//Spin through the only row in the weekly sales table. Item in item
//array index zero (0) is the ID number of the weekly sales.
for (var cellIndex = 1; cellIndex < weeklySales.Rows[0].ItemArray.Length; cellIndex++)
{
double dollarAmount;
switch (cellIndex)
{
case 1: //Sunday
dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
if (dollarAmount.ToString("N2") != "0.00")
{
_departmentSales += dollarAmount;
sundayWeeklySalesLabel.Text = @"Sunday: $" + dollarAmount;
}
else
{
sundayWeeklySalesLabel.Text = @"Sunday: " + CheckForHoliday(DayOfWeek.Sunday);
}
break;
case 2: //Monday
dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
if (dollarAmount.ToString("N2") != "0.00")
{
_departmentSales += dollarAmount;
mondayWeeklySalesLabel.Text = @"Monday: $" + dollarAmount;
}
else
{
mondayWeeklySalesLabel.Text = @"Monday: " + CheckForHoliday(DayOfWeek.Monday);
}
break;
case 3: //Tuesday
dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
if (dollarAmount.ToString("N2") != "0.00")
{
_departmentSales += dollarAmount;
tuesadayWeeklySalesLabel.Text = @"Tuesday: $" + dollarAmount;
}
else
{
tuesadayWeeklySalesLabel.Text = @"Tuesday: " + CheckForHoliday(DayOfWeek.Tuesday);
}
break;
case 4: //Wednesday
dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
if (dollarAmount.ToString("N2") != "0.00")
{
_departmentSales += dollarAmount;
wednesdayWeeklySalesLabel.Text = @"Wednesday: $" + dollarAmount;
}
else
{
wednesdayWeeklySalesLabel.Text = @"Wednesday: " + CheckForHoliday(DayOfWeek.Wednesday);
}
break;
case 5: //Thursday
dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
if (dollarAmount.ToString("N2") != "0.00")
{
_departmentSales += dollarAmount;
thursdayWeeklySalesLabel.Text = @"Thursday: $" + dollarAmount;
}
else
{
thursdayWeeklySalesLabel.Text = @"Thursday: " + CheckForHoliday(DayOfWeek.Thursday);
}
break;
case 6: //Friday
dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
if (dollarAmount.ToString("N2") != "0.00")
{
_departmentSales += dollarAmount;
fridayWeeklySalesLabel.Text = @"Friday: $" + dollarAmount;
}
else
{
fridayWeeklySalesLabel.Text = @"Friday: " + CheckForHoliday(DayOfWeek.Friday);
}
break;
case 7: //Saturday
dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
if (dollarAmount.ToString("N2") != "0.00")
{
_departmentSales += dollarAmount;
saturdayWeeklySalesLabel.Text = @"Saturday: $" + dollarAmount;
}
else
{
saturdayWeeklySalesLabel.Text = @"Saturday: " + CheckForHoliday(DayOfWeek.Saturday);
}
break;
case 8: //Total Sales
dollarAmount = double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
if (dollarAmount.ToString("N2") != "0.00")
{
totalWeeklySalesLabel.Text = @"Total Sales: $" + dollarAmount;
}
else
{
totalWeeklySalesLabel.Text = @"Total Sales: ";
}
break;
}
}
}
private void LoadTaxable(DataTable taxable)
{
//Spin through the only row in the taxable table. Item in item
//array index zero (0) is the ID number of the weekly sales.
for (var cellIndex = 1; cellIndex < taxable.Rows[0].ItemArray.Length; cellIndex++)
{
string formattedNumber;
switch (cellIndex)
{
case 1: //Sunday
formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
sundayTaxableLabel.Text = @"Sunday: $" + formattedNumber;
}
else
{
sundayTaxableLabel.Text = @"Sunday: " + CheckForHoliday(DayOfWeek.Sunday);
}
break;
case 2: //Monday
formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
mondayTaxableLabel.Text = @"Monday: $" + formattedNumber;
}
else
{
mondayTaxableLabel.Text = @"Monday: " + CheckForHoliday(DayOfWeek.Monday);
}
break;
case 3: //Tuesday
formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
tuesdayTaxableLabel.Text = @"Tuesday: $" + formattedNumber;
}
else
{
tuesdayTaxableLabel.Text = @"Tuesday: " + CheckForHoliday(DayOfWeek.Tuesday);
}
break;
case 4: //Wednesday
formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
wednesdayTaxableLabel.Text = @"Wednesday: $" + formattedNumber;
}
else
{
wednesdayTaxableLabel.Text = @"Wednesday: " + CheckForHoliday(DayOfWeek.Wednesday);
}
break;
case 5: //Thursday
formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
thursdayTaxableLabel.Text = @"Thursday: $" + formattedNumber;
}
else
{
thursdayTaxableLabel.Text = @"Thursday: " + CheckForHoliday(DayOfWeek.Thursday);
}
break;
case 6: //Friday
formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
fridayTaxableLabel.Text = @"Friday: $" + formattedNumber;
}
else
{
fridayTaxableLabel.Text = @"Friday: " + CheckForHoliday(DayOfWeek.Friday);
}
break;
case 7: //Saturday
formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
saturdayTaxableLabel.Text = @"Saturday: $" + formattedNumber;
}
else
{
saturdayTaxableLabel.Text = @"Saturday: " + CheckForHoliday(DayOfWeek.Saturday);
}
break;
case 8: //Total Taxable
formattedNumber = double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
totalTaxableLabel.Text = @"Total Taxable: $" + formattedNumber;
}
break;
}
}
}
private void LoadCostAnalysis(DataTable costAnalysis)
{
//Spin through the only row in the taxable table. Item in item
//array index zero (0) is the ID number of the weekly sales.
for (var cellIndex = 1; cellIndex < costAnalysis.Rows[0].ItemArray.Length; cellIndex++)
{
string formattedNumber;
switch (cellIndex)
{
case 1: //Sales per man hour
formattedNumber = double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
salesPerManHourLabel.Text = @"Sales Per Man Hour: $" + formattedNumber;
}
break;
case 2: //Salary Percentage
formattedNumber = double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()).ToString("P2");
if (formattedNumber != "0.00")
{
salaryPercentageLabel.Text = @"Salary Percentage: " + formattedNumber;
}
break;
case 3: //Salary Dollars
formattedNumber = double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
salaryDollarsLabel.Text = @"Salary Dollars: $" + formattedNumber;
}
break;
case 4: //Supplies
formattedNumber = double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()).ToString("N2");
if (formattedNumber != "0.00")
{
suppliesLabel.Text = @"Supplies: $" + formattedNumber;
}
break;
}
}
}
private string CheckForHoliday(DayOfWeek day)
{
var holidayText = string.Empty;
//Get the currently selected date.
var date = monthCalendar.SelectionStart;
//Now make sure the selected day on the calendar (the date that came from the database) is not the same
//as the day provided, unless the day is Saturday. If the end of week date is not on a Saturday and the
//supplied day is Monday, than subtracting 5 would yield an incorrect date.
if (date.DayOfWeek == DayOfWeek.Saturday)
{
switch (day)
{
case DayOfWeek.Sunday:
date = date.AddDays(-6);
break;
case DayOfWeek.Monday:
date = date.AddDays(-5);
break;
case DayOfWeek.Tuesday:
date = date.AddDays(-4);
break;
case DayOfWeek.Wednesday:
date = date.AddDays(-3);
break;
case DayOfWeek.Thursday:
date = date.AddDays(-2);
break;
case DayOfWeek.Friday:
date = date.AddDays(-1);
break;
}
}
var holiday = Holiday.IsHoliday(date);
switch (holiday)
{
case Holidays.Thanksgiving:
case Holidays.Christmas:
holidayText = @"Closed for " + TextFormat.AddSpacesToSentence(holiday.ToString(), false);
break;
}
return holidayText;
}
}
}
//http://stackoverflow.com/questions/487661/how-do-i-suspend-painting-for-a-control-and-its-children
internal class DrawingControl
{
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
parent.Refresh();
}
}