using framework_business;
using framework_library;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
public partial class controls_module_sales : ICanvasBase, IControlBase
{
private const string controlPath = "~/controls/";
private const string surfacePath = "~/controls/surface/";
#region properties
public string NotesFieldName
{
get
{
if (ViewState["notesFieldName"] == null)
return "";
else
return ViewState["notesFieldName"].ToString();
}
set
{
ViewState["notesFieldName"] = value;
}
}
#endregion
#region methods
#region binding methods
///
/// Bind Picklists
///
private void BindSalesToPicklists()
{
try
{
DataTable data = new DataTable();
foreach (oSurface surface in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "Contacts"))
{
data = xData.GetSurfaceData(surface.recId);
//CVH 2016-11-17 Set the Sales notes button field name, used when linking notes to surface
foreach (oSurfaceField field in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId,surfaceFieldTypeId,isActive", surface.recId + "," + pNums.FieldType.Note.GetHashCode() + ",1"))
{
this.NotesFieldName = field.surfaceFieldName;
break;
}
break;
}
string contactName = String.Empty;
foreach (DataColumn col in data.Columns)
{
if (col.ColumnName.EndsWith("_ContactName"))
{
contactName = col.ColumnName;
break;
}
}
DataView dv = data.DefaultView;
dv.Sort = contactName;
ddFilterContact.DataSource = dv.ToTable();
ddFilterContact.DataValueField = "itemID";
ddFilterContact.DataTextField = contactName;
ddFilterContact.DataBind();
ddFilterContact.Items.Insert(0, new ListItem("All", "0"));
rcbSalesContacts.DataSource = dv.ToTable();
rcbSalesContacts.DataValueField = "itemID";
rcbSalesContacts.DataTextField = contactName;
rcbSalesContacts.DataBind();
rcbSalesContacts.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("Select", "0"));
ddStatementContacts.DataSource = data;
ddStatementContacts.DataValueField = "itemID";
ddStatementContacts.DataTextField = contactName;
ddStatementContacts.DataBind();
ddStatementContacts.Items.Insert(0, new ListItem("Select", "0"));
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Method to Bind Sales Data
///
private void BindSalesData()
{
try
{
int mode = 0;//activity view
if (utils.verifySession("mode"))
mode = int.Parse(Session["mode"].ToString());
Session["bal"] = 0;
// filters
//contact
int surfaceItemID = 0;
if (ddFilterContact.SelectedValue != null && ddFilterContact.SelectedValue != "" && ddFilterContact.SelectedValue != "0")
{
int.TryParse(ddFilterContact.SelectedValue, out surfaceItemID);
}
string ItemType = string.Empty;
foreach (ListItem item in ddFilterType.Items)
{
if (item.Selected && item.Value != string.Empty)
ItemType += item.Value + "|";
}
string FromDate = String.Empty;
string ToDate = String.Empty;
if (txtFilterDateFrom.Value != String.Empty)
{
FromDate = utils.formatStringToDate(txtFilterDateFrom.Value).AddDays(-1).ToString("yyyy-MM-dd");
}
if (txtFilterDateTo.Value != String.Empty)
{
ToDate = utils.formatStringToDate(txtFilterDateTo.Value).AddDays(1).ToString("yyyy-MM-dd");
}
string transNumber = txtFilterNumber.Value;
List statuses = new List();
foreach (ListItem item in lstSatuses.Items)
{
if (item.Selected)
{
statuses.Add(item.Value);
}
}
DataTable salesData = xData.GetSalesData(surfaceItemID, ItemType, FromDate, ToDate, String.Join("','", statuses.ToArray()));
if (transNumber != string.Empty)
{
DataTable salesDataFiltered = salesData.Clone();
salesDataFiltered.Clear();
var sData = from salesD in salesData.AsEnumerable()
where salesD.Field("Activity").ToLower().Contains(transNumber.ToLower())
select salesD;
sData.CopyToDataTable(salesDataFiltered, LoadOption.OverwriteChanges);
salesData.Clear();
salesData = salesDataFiltered.Copy();
}
DataTable financialData = salesData.Clone();
financialData.Clear();
var enFindata = from rowSalesData in salesData.AsEnumerable()
where !rowSalesData.Field("itemType").Equals("QT")
select rowSalesData;
enFindata.CopyToDataTable(financialData, LoadOption.OverwriteChanges);
//bind Sales view grid
if (mode == 0)
{
lblActivityHeading.Text = "Activity View";
lnkToggleFinancial.Text = "View Financial ";
rptActivity.DataSource = salesData;
}
else
{
lblActivityHeading.Text = "Financial View";
lnkToggleFinancial.Text = "View Activity ";
rptActivity.DataSource = financialData;
}
rptActivity.DataBind();
////bind Financial View Grid
//rptFinancial.DataSource = financialData;
//rptFinancial.DataBind();
//summary details
decimal dBalance = 0M, dQuotes = 0M, dInvoiced = 0M, dPayments = 0M, dCreditNotes = 0M;
foreach (DataRow row in salesData.Rows)
{
if (row["saleStatus"].ToString() == "Draft")
continue;
//this is incorrect we are not taking into account unallocated receipts
//dBalance += Convert.ToDecimal(row["Due"]);
dInvoiced += Convert.ToDecimal(row["Invoiced"]);
dPayments += Convert.ToDecimal(row["Payments"]);
dQuotes += Convert.ToDecimal(row["Quoted"]);
dCreditNotes += Convert.ToDecimal(row["CreditNotes"]);
}
if (ToDate != String.Empty)
{
DateTime dateTo = DateTime.Parse(ToDate);
dBalance = xData.GetSalesBalance(surfaceItemID, dateTo);
}
else
dBalance = xData.GetSalesBalance(surfaceItemID);
if (ItemType == string.Empty)
{
lblSummaryQuotes.CssClass = lblSummaryQuotes.CssClass.Replace("label-default trans", "label-info");
lblSummaryInvoiced.CssClass = lblSummaryInvoiced.CssClass.Replace("label-default trans", "label-primary");
lblSummaryPayments.CssClass = lblSummaryPayments.CssClass.Replace("label-default trans", "label-success");
lblSummaryCreditNotes.CssClass = lblSummaryCreditNotes.CssClass.Replace("label-default trans", "label-warning");
lblSummaryBalance.CssClass = lblSummaryBalance.CssClass.Replace("label-default trans", "label-danger");
}
else
{
lblSummaryQuotes.CssClass = lblSummaryQuotes.CssClass.Replace("label-info", "label-default trans");
lblSummaryInvoiced.CssClass = lblSummaryInvoiced.CssClass.Replace("label-primary", "label-default trans");
lblSummaryPayments.CssClass = lblSummaryPayments.CssClass.Replace("label-success", "label-default trans");
lblSummaryCreditNotes.CssClass = lblSummaryCreditNotes.CssClass.Replace("label-warning", "label-default trans");
lblSummaryBalance.CssClass = lblSummaryBalance.CssClass.Replace("label-danger", "label-default trans");
if (ItemType.Contains("TI"))
{
lblSummaryInvoiced.CssClass = lblSummaryInvoiced.CssClass.Replace("label-default trans", "label-primary");
}
if (ItemType.Contains("QT"))
{
lblSummaryQuotes.CssClass = lblSummaryQuotes.CssClass.Replace("label-default trans", "label-info");
}
if (ItemType.Contains("PM"))
{
lblSummaryPayments.CssClass = lblSummaryPayments.CssClass.Replace("label-default trans", "label-success");
}
if (ItemType.Contains("CN"))
{
lblSummaryCreditNotes.CssClass = lblSummaryCreditNotes.CssClass.Replace("label-default trans", "label-warning");
}
}
//CVH 2016-09-21 If any of the types have not been selected, show 0 balance.
if ((ItemType != String.Empty) && (!ItemType.Contains("TI") || !ItemType.Contains("QT") || !ItemType.Contains("CN") || !ItemType.Contains("PM")))
dBalance = 0;
if (dBalance > 0)
{
lblSummaryBalance.CssClass = lblSummaryBalance.CssClass.Replace("label-default trans", "label-danger");
}
lblSummaryBalance.Text = dBalance.ToString("N2");
lblSummaryQuotes.Text = dQuotes.ToString("N2");
lblSummaryPayments.Text = dPayments.ToString("N2");
lblSummaryCreditNotes.Text = dCreditNotes.ToString("N2");
lblSummaryInvoiced.Text = dInvoiced.ToString("N2");
upSales.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Bind quotes to be Imported
///
///
private void BindQuotesToImport(string surfaceItemId, bool includeAllocated)
{
if (surfaceItemId != "")
{
ddRelatedTo.Items.Clear();
List paramList = new List();
oDynamicParam p = new oDynamicParam();
p.paramDisplayName = "SurfaceItemID";
p.paramObject = surfaceItemId;
paramList.Add(p);
oDynamicParam p2 = new oDynamicParam();
p2.paramDisplayName = "includeAllocated";
p2.paramObject = includeAllocated ? 1 : 0;
paramList.Add(p2);
DataTable dtQuotesToImport = xData.GetTypedTableByProc("recId", typeof(oSales), "sp_GetSalesQuotesToAllocate", paramList);
ddRelatedTo.DataSource = dtQuotesToImport;
ddRelatedTo.DataTextField = "Display";
ddRelatedTo.DataValueField = "quoteNo";
ddRelatedTo.DataBind();
ddRelatedTo.Items.Insert(0, new ListItem("select...", "0"));
if (dtQuotesToImport != null && dtQuotesToImport.Rows.Count <= 0)
ddRelatedTo.Enabled = false;
else
ddRelatedTo.Enabled = true;
upTransaction.Update();
}
else
{
ddRelatedTo.DataSource = null;
ddRelatedTo.DataBind();
ddRelatedTo.Items.Insert(0, new ListItem("select...", "0"));
ddRelatedTo.Enabled = false;
upTransaction.Update();
}
}
///
/// Bind Items
///
private void BindItemsNew(string itemCode, string description)
{
try
{
DataTable itemData = new DataTable();
//CVH 2016-09-15 Only show items not deleted
if (itemCode != String.Empty)
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "code,isDeleted", itemCode + ",0", "description");
}
else if (description != String.Empty)
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "description,isDeleted", description + ",0", "description");
}
else
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "isDeleted", "0", "description");
}
if (itemData.Rows.Count == 0)
{
txtBillingCode.Text = "Invalid Code";
txtBillingCode.ForeColor = System.Drawing.Color.Red;
return;
}
else
{
txtBillingCode.ForeColor = System.Drawing.Color.Black;
}
rcbBillingDescription.DataSource = itemData;
rcbBillingDescription.DataTextField = "description";
rcbBillingDescription.DataValueField = "code";
rcbBillingDescription.DataBind();
rcbBillingDescription.ClearSelection();
if (description == String.Empty && itemCode == String.Empty)
{
rcbBillingDescription.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("select an item..", ""));
}
else
{
CalculateAmount(true);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Bind Items
///
private void BindItemsEdit(string itemCode, string description)
{
try
{
DataTable itemData = new DataTable();
//CVH 2016-09-15 Only show items not deleted
if (itemCode != String.Empty)
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "code,isDeleted", itemCode + ",0", "description");
}
else if (description != String.Empty)
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "description,isDeleted", description + ",0", "description");
}
else
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "isDeleted", "0", "description");
}
if (itemData.Rows.Count == 0)
{
txtEditLineCode.Text = "Invalid Code";
txtEditLineCode.ForeColor = System.Drawing.Color.Red;
return;
}
else
{
txtEditLineCode.ForeColor = System.Drawing.Color.Black;
}
rcbEditLineDescription.DataSource = itemData;
rcbEditLineDescription.DataTextField = "description";
rcbEditLineDescription.DataValueField = "code";
rcbEditLineDescription.DataBind();
rcbEditLineDescription.ClearSelection();
if (description == String.Empty && itemCode == String.Empty)
rcbEditLineDescription.Items.Insert(0, new RadComboBoxItem("select an item..", ""));
else
{
CalculateAmountEditLine(true);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Bind Invoices to be Allocated
///
///
private void BindInvoicesToAlllocate(string surfaceItemId)
{
if (surfaceItemId != String.Empty)
{
ddRelatedTo.Items.Clear();
List paramList = new List();
oDynamicParam p = new oDynamicParam();
p.paramDisplayName = "SurfaceItemID";
p.paramObject = surfaceItemId;
paramList.Add(p);
DataTable dtInvoicesToImport = xData.GetTypedTableByProc("recId", typeof(oSales), "sp_GetSalesInvoicesToAllocate", paramList);
lstRelatedTo.DataSource = dtInvoicesToImport;
lstRelatedTo.DataTextField = "Display";
lstRelatedTo.DataValueField = "invoiceNo";
lstRelatedTo.DataBind();
// lstRelatedTo.Items.Insert(0, new ListItem("select...", "0"));
//CVH 2016-09-16 If no items, "disable" dropdown, but multiselect not easy to disable, added empty dropdown to show instead
if (dtInvoicesToImport != null && dtInvoicesToImport.Rows.Count <= 0)
{
lstRelatedTo.Visible = false;
lstRelatedToEmpty.Visible = true;
}
else
{
lstRelatedTo.Visible = true;
lstRelatedToEmpty.Visible = false;
}
upTransaction.Update();
}
else
{
ddRelatedTo.DataSource = null;
ddRelatedTo.DataBind();
lstRelatedTo.Visible = false;
lstRelatedToEmpty.Visible = true;
}
}
///
/// Method to Bind Invoices to Receipt
///
private void BindInvoicesToReceipt()
{
try
{
int mode = 0;//activity view
if (utils.verifySession("mode"))
mode = int.Parse(Session["mode"].ToString());
Session["bal"] = 0;
// filters
//contact
int surfaceItemID = 0;
if (rcbSalesContacts.SelectedValue != null && rcbSalesContacts.SelectedValue != "" && rcbSalesContacts.SelectedValue != "0")
{
int.TryParse(rcbSalesContacts.SelectedValue, out surfaceItemID);
}
string ItemType = "TI|";
string FromDate = String.Empty;
string ToDate = String.Empty;
string transNumber = String.Empty;
List statuses = new List();
statuses.Add("Overdue");
statuses.Add("Partially Paid");
statuses.Add("Unpaid");
DataTable salesData = new DataTable();
if (surfaceItemID > 0)
{
salesData = xData.GetSalesData(surfaceItemID, ItemType, FromDate, ToDate, String.Join("','", statuses.ToArray()));
}
rptInvoiceLines.DataSource = salesData;
rptInvoiceLines.DataBind();
grpButonsTransaction.Visible = true;
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Bind Payment Methods
///
private void BindPaymentMethods()
{
try
{
ddPaymentMethod.Items.Clear();
DataTable paymentTypeData = new DataTable();
paymentTypeData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oPaymentType), "transactionTypeId", "1", "paymentType");
ddPaymentMethod.DataSource = paymentTypeData;
ddPaymentMethod.DataTextField = "paymentType";
ddPaymentMethod.DataValueField = "paymentCode";
ddPaymentMethod.DataBind();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Bind Invoice Lines
///
private void BindTransactionLines()
{
ArrayList billings = new ArrayList();
try
{
if (utils.verifySession("transactionLines"))
{
billings = (ArrayList)Session["transactionLines"];
Session["transactionLines"] = billings;
}
Session["bal"] = 0;
rptBillingAccounts.DataSource = billings;
rptBillingAccounts.DataBind();
hsub.Visible = true;
hvat.Visible = true;
string currency = "ZAR";
decimal dSubTotal = 0M;
decimal dVAT = 0M;
decimal dTotalAmount = 0M;
foreach (oSales salesItem in billings)
{
dSubTotal += salesItem.amount - salesItem.allocated;
}
oSetup setup = handler.ReturnSetup();
if (setup.vatRegistered && setup.vatRate > 0)
{
//calculation to work out VAT portion if the amounts are already inclusive
decimal exclBalance = (100.00m / (100.00m + setup.vatRate)) * dSubTotal;
dVAT = dSubTotal - ((100.00m / (100.00m + setup.vatRate)) * dSubTotal);
dTotalAmount = exclBalance + dVAT;
//calculation to add Vat to Amounts Exclusive of VAT
//dVAT = (dSubTotal / 100) * setup.vatRate;
//dTotalAmount = dSubTotal + dVAT;
lblTransactionSubTotal.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(exclBalance));
lblTransactionVATPct.Text = " @ " + String.Format("{0:N0}", setup.vatRate) + "%";
lblTransactionVAT.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(dVAT));
lblTransactionTotal.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(dTotalAmount));
}
else
{
hsub.Visible = false;
hvat.Visible = false;
lblTransactionTotal.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(dSubTotal));
}
/* CVH 2016-08-26 Hide entire columns depending on type */
HtmlTableCell thEdit = (HtmlTableCell)rptBillingAccounts.Controls[0].Controls[0].FindControl("thBillingAccountsEdit");
HtmlTableCell thDelete = (HtmlTableCell)rptBillingAccounts.Controls[0].Controls[0].FindControl("thBillingAccountsDelete");
if (thEdit != null && thDelete != null)
{
switch (ddTransactionType.SelectedValue)
{
case "TI":
thEdit.Visible = true;
thDelete.Visible = true;
break;
case "QT":
thEdit.Visible = true;
thDelete.Visible = true;
break;
case "CN":
thEdit.Visible = false;
thDelete.Visible = true;
break;
case "PM":
thEdit.Visible = false;
thDelete.Visible = true;
break;
case "A":
thEdit.Visible = false;
thDelete.Visible = true;
//hsub.Visible = false;
//hvat.Visible = false;
//lblTransactionTotal.Text = currency + " " + txtPaymentAmount.Value;
break;
default:
thEdit.Visible = true;
thDelete.Visible = true;
break;
}
}
if (billings.Count > 0)
{
grpButonsTransaction.Visible = true;
}
else
{
grpButonsTransaction.Visible = false;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Bind View Transactions
///
private void BindViewTransactionLines()
{
ArrayList billings = new ArrayList();
try
{
if (utils.verifySession("transactionLines"))
{
billings = (ArrayList)Session["transactionLines"];
Session["transactionLines"] = billings;
}
Session["bal"] = 0;
rptViewTransactionLines.DataSource = billings;
rptViewTransactionLines.DataBind();
/* CVH 2016-09-19 Add totals to view */
hsubView.Visible = true;
hvatView.Visible = true;
string currency = "ZAR";
decimal dSubTotal = 0M;
decimal dVAT = 0M;
decimal dTotalAmount = 0M;
foreach (oSales salesItem in billings)
{
dSubTotal += salesItem.amount;
}
oSetup setup = handler.ReturnSetup();
if (setup.vatRegistered && setup.vatRate > 0)
{
//calculation to work out VAT portion if the amounts are already inclusive
decimal exclBalance = (100.00m / (100.00m + setup.vatRate)) * dSubTotal;
dVAT = dSubTotal - ((100.00m / (100.00m + setup.vatRate)) * dSubTotal);
dTotalAmount = exclBalance + dVAT;
//calculation to add Vat to Amounts Exclusive of VAT
//dVAT = (dSubTotal / 100) * setup.vatRate;
//dTotalAmount = dSubTotal + dVAT;
lblTransactionSubTotalView.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(exclBalance));
lblTransactionVATPctView.Text = " @ " + String.Format("{0:N0}", setup.vatRate) + "%";
lblTransactionVATView.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(dVAT));
lblTransactionTotalView.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(dTotalAmount));
}
else
{
hsub.Visible = false;
hvat.Visible = false;
lblTransactionTotalView.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(dSubTotal));
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Bind invoice to Print
///
///
///
private void BindInvoicesToPrint(int itemId, DropDownList dd)
{
dd.Items.Clear();
List paramList = new List();
oDynamicParam p = new oDynamicParam();
p.paramDisplayName = "SurfaceItemID";
p.paramObject = itemId;
paramList.Add(p);
DataTable dtInvoicesToImport = xData.GetTypedTableByProc("recId", typeof(oSales), "sp_GetSalesInvoicesToAllocate", paramList);
dd.DataSource = dtInvoicesToImport;
dd.DataTextField = "Display";
dd.DataValueField = "invoiceNo";
dd.DataBind();
dd.Items.Insert(0, new ListItem("select...", "0"));
}
///
/// Bind quotes to print
///
///
///
private void BindQuotesToPrint(oSales sale, DropDownList dd)
{
if (sale != null)
{
dd.Items.Clear();
List paramList = new List();
oDynamicParam p = new oDynamicParam();
p.paramDisplayName = "SurfaceItemID";
p.paramObject = sale.surfaceItemId;
paramList.Add(p);
oDynamicParam p2 = new oDynamicParam();
p2.paramDisplayName = "includeAllocated";
p2.paramObject = 1;
paramList.Add(p2);
DataTable dtQuotesToImport = xData.GetTypedTableByProc("recId", typeof(oSales), "sp_GetSalesQuotesToAllocate", paramList);
dd.DataSource = dtQuotesToImport;
dd.DataTextField = "Display";
dd.DataValueField = "quoteNo";
dd.DataBind();
dd.Items.Insert(0, new ListItem("select...", "0"));
}
else
{
dd.DataSource = null;
dd.DataBind();
}
}
///
/// Bind Receipts to Print
///
///
///
private void BindReceiptsToPrint(int itemId, DropDownList dd)
{
dd.Items.Clear();
List paramList = new List();
oDynamicParam p = new oDynamicParam();
p.paramDisplayName = "SurfaceItemID";
p.paramObject = itemId;
paramList.Add(p);
DataTable dtInvoicesToImport = xData.GetTypedTableByProc("recId", typeof(oSales), "sp_GetSalesReceipts", paramList);
dd.DataSource = dtInvoicesToImport;
dd.DataTextField = "Display";
dd.DataValueField = "receiptNo";
dd.DataBind();
dd.Items.Insert(0, new ListItem("select...", "0"));
}
public void BindEditorButtons(RadEditor edf)
{
edf.EnsureToolsFileLoaded();
string buttonsToRemove = "Print,SelectAll,Cut,Copy,Paste,ImageManager,DocumentManager,FlashManager,MediaManager,TemplateManager,LinkManager,Unlink,Superscript,Subscript,InsertGroupbox,InsertHorizontalRule,InsertDate,InsertTime,FormatCodeBlock,AbsolutePosition,InsertFormElement,InsertSnippet,ImageMapDialog,InsertCustomLink,ConvertToLower,ConvertToUpper,ModuleManager,ToggleScreenMode,AboutDialog";
string[] buttons = buttonsToRemove.Split(char.Parse(","));
foreach (string name in buttons)
{
foreach (Telerik.Web.UI.EditorToolGroup group in edf.Tools)
{
Telerik.Web.UI.EditorTool tool = group.FindTool(name);
if (tool != null)
{
group.Tools.Remove(tool);
}
}
}
}
private void LoadAddNewItemControl()
{
try
{
plcAddNewItem.Controls.Clear();
foreach (oModule mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oModule), "module", "Products and Services"))
{
dynamic uc = (UserControl)LoadControl(controlPath + mod.control);
uc.ID = "AddNewItemControl";
uc.ReloadControl();
plcAddNewItem.Controls.Add(uc);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
private void LoadAddNewContactControl()
{
try
{
plcAddNewContact.Controls.Clear();
foreach (oModule mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oModule), "module", "Surface"))
{
//get surface app
foreach (oSurface surfApp in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "Contacts"))
{
//create surface app if it does not exist
if (!File.Exists(Server.MapPath(surfacePath + surfApp.name + ".ascx")))
{ surfaceHandler.BuildSurfaceAppTemplate(surfApp, controlPath + mod.control, surfacePath, true); }
//load the surface app control
plcAddNewContact.Controls.Clear();
ISurfaceBase uc = (ISurfaceBase)LoadControl(surfacePath + surfApp.name + ".ascx");
uc.SurfaceApp = surfApp;
uc.ReloadControl(new oSurfaceItem(), false, false);
plcAddNewContact.Controls.Add(uc);
break;
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region populate methods
///
/// Toggle Transaction view
///
///
private void ToggleTransactionType(string type, string surfaceItemId)
{
pnlResultBilling.Visible = false;
ddTransactionType.SelectedValue = type;
ddRelatedTo.Enabled = true;
txtTransactionDate.Disabled = false;
rcbSalesContacts.Enabled = true;
ddPaymentMethod.Enabled = true;
txtPaymentAmount.Disabled = false;
txtPaymentAmount.Value = "0.00";
ViewState["num"] = null;
/* CVH 2016-08-24 Clear reference */
txtReference.Value = "";
txtTransactionDate.Value = DateTime.Now.ToString("dd/MM/yyyy");
//CVH 2016-09-14 Build transaction number with padded 0's
switch (ddTransactionType.SelectedValue)
{
case "TI"://invoice
rptBillingAccounts.Visible = true;
hsub.Visible = true;
hvat.Visible = true;
rptInvoiceLines.Visible = false;
BindTransactionLines();
lblType.Text = "Invoice:";
//bring in next invoice no
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleINVPrefix, handler.ReturnSetup().saleINVNumLength, xData.GetInvoiceNoSales("TI"));
//bind quotes for related to
BindQuotesToImport(surfaceItemId, false);
ddRelatedTo.Visible = true;
lstRelatedTo.Visible = false;
lstRelatedToEmpty.Visible = false;
//show related to
pnlRelatedTo.Visible = true;
pnlPaymentMethods.Visible = false;
pnlPaymentAmount.Visible = false;
pnlAddItems.Visible = true;
pnlDueDate.Visible = true;
lblDueDate.Text = "Due Date:";
break;
case "QT"://quote
rptBillingAccounts.Visible = true;
hsub.Visible = true;
hvat.Visible = true;
rptInvoiceLines.Visible = false;
BindTransactionLines();
lblType.Text = "Quote:";
//bring in next invoice no
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleQTEPrefix, handler.ReturnSetup().saleQTENumLength, xData.GetQuoteNoSales());
//show
pnlRelatedTo.Visible = false;
pnlPaymentMethods.Visible = false;
pnlPaymentAmount.Visible = false;
pnlAddItems.Visible = true;
pnlDueDate.Visible = true;
lblDueDate.Text = "Valid Until:";
break;
case "PM"://receipt
rptBillingAccounts.Visible = false;
hsub.Visible = false;
hvat.Visible = false;
rptInvoiceLines.Visible = true;
BindInvoicesToReceipt();
lblType.Text = "Receipt:";
//bring in next invoice no
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleRCTPrefix, handler.ReturnSetup().saleRCTNumLength, xData.GetNextRecNoSales());
//bind invoices for related to
BindInvoicesToAlllocate(surfaceItemId);
//show related to
pnlRelatedTo.Visible = false;
ddRelatedTo.Visible = false;
//CVH 2016-09-16 lstRelatedTo Visibility set when binding
pnlPaymentMethods.Visible = true;
pnlPaymentAmount.Visible = true;
pnlAddItems.Visible = false;
pnlDueDate.Visible = false;
break;
case "A"://allocate
rptBillingAccounts.Visible = false;
hsub.Visible = false;
hvat.Visible = false;
rptInvoiceLines.Visible = true;
BindInvoicesToReceipt();
lblType.Text = "Allocate:";
rcbSalesContacts.Enabled = false;
//bind invoices for related to
//BindInvoicesToAlllocate(surfaceItemId);
//show related to
pnlRelatedTo.Visible = false;
ddRelatedTo.Visible = false;
//CVH 2016-09-16 lstRelatedTo Visibility set when binding
pnlPaymentMethods.Visible = true;
pnlPaymentAmount.Visible = true;
pnlAddItems.Visible = false;
pnlDueDate.Visible = false;
txtTransactionDate.Disabled = true;
ddPaymentMethod.Enabled = false;
txtPaymentAmount.Disabled = true;
txtReference.Disabled = true;
break;
case "AC"://allocate cn
rptBillingAccounts.Visible = true;
hsub.Visible = true;
hvat.Visible = true;
rptInvoiceLines.Visible = false;
BindTransactionLines();
lblType.Text = "Allocate:";
rcbSalesContacts.Enabled = false;
//bind invoices for related to
BindInvoicesToAlllocate(surfaceItemId);
//show related to
pnlRelatedTo.Visible = true;
ddRelatedTo.Visible = false;
//CVH 2016-09-16 lstRelatedTo Visibility set when binding
pnlPaymentMethods.Visible = true;
pnlPaymentAmount.Visible = true;
pnlAddItems.Visible = true;
pnlDueDate.Visible = false;
txtTransactionDate.Disabled = true;
ddPaymentMethod.Enabled = false;
txtPaymentAmount.Disabled = true;
txtReference.Disabled = true;
break;
case "CN"://credit note
rptBillingAccounts.Visible = true;
hsub.Visible = true;
hvat.Visible = true;
rptInvoiceLines.Visible = false;
BindTransactionLines();
lblType.Text = "Credit Note:";
//bring in next invoice no
/* CVH 2016-08-26 Type is CN not TI */
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleCRNPrefix, handler.ReturnSetup().saleCRNNumLength, xData.GetInvoiceNoSales("CN"));
//bind invoices for related to
BindInvoicesToAlllocate(surfaceItemId);
//show related to
pnlRelatedTo.Visible = true;
ddRelatedTo.Visible = false;
//CVH 2016-09-16 lstRelatedTo Visibility set when binding
pnlPaymentMethods.Visible = false;
pnlPaymentAmount.Visible = false;
pnlAddItems.Visible = true;
pnlDueDate.Visible = false;
break;
}
upTransaction.Update();
}
///
/// Update all running totals for sales
///
///
private void UpdateRunningTotals(string surfaceItemId)
{
decimal bal = 0;
if (surfaceItemId != String.Empty)
{
foreach (oSales sales in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType", surfaceItemId + ",~<>QT", "dateOfService,sequence"))
{
bal += sales.amount;
sales.runningBal = bal;
xData.UpdateTyped("recId", sales.recId.ToString(), typeof(oSales), sales);
}
bal = 0;
//quoteItems running balance
foreach (oSales quoteItems in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType", surfaceItemId + ",QT", "dateOfService,sequence"))
{
bal += quoteItems.amount;
quoteItems.runningBal = bal;
xData.UpdateTyped("recId", quoteItems.recId.ToString(), typeof(oSales), quoteItems);
}
}
}
///
/// Method to create a test sales
///
private oSales CreateTestSales()
{
oUser usr = new oUser();
if (utils.verifySession("user"))
{ usr = (oUser)Session["user"]; }
oSales sales = new oSales();
sales.surfaceItemId = 1;
sales.name = "Graham";
sales.surname = "Rook";
sales.title = "Mr";
sales.initials = "GM";
sales.userId = usr.recId;
return sales;
}
///
/// Get Related To Item Value
///
///
///
private string GetRelatedToItemValue(oSales sale)
{
string value = "";
//CVH 2016-09-14 Build transaction number with padded 0's
switch (sale.itemType)
{
case "TI":
//CVH 2016-09-15 Remove prefix from allocated reference, only use number
foreach (oSales quote in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,allocatedReference", "QT," + sale.surfaceItemId + "," + sale.invoiceNo))
{
value = quote.invoiceNo.ToString();
break;
}
break;
case "CN":
foreach (oSales invoice in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,recId", "TI," + sale.surfaceItemId + "," + sale.allocatedReference))
{
value = invoice.invoiceNo.ToString();
break;
}
break;
case "PM":
break;
}
return value;
}
///
/// Calculate amount
///
private void CalculateAmount(bool includeCall)
{
try
{
string code = String.Empty;
code = txtBillingCode.Text;
decimal qty = 0;
decimal.TryParse(txtBillingQty.Text, out qty);
decimal unitFee = 0;
decimal amount = 0;
oSetup setup = handler.ReturnSetup();
if (includeCall)
{
//CVH 2016-09-15 Only process items not deleted
foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code,isDeleted", code + ",0"))
{
decimal untiPriceExcl = item.SellPriceIncl;
if (setup.vatRegistered && setup.vatRate > 0)
{
untiPriceExcl = (100.00m / (100.00m + setup.vatRate)) * item.SellPriceIncl;
}
unitFee = untiPriceExcl;
if (qty > 0)
{
amount = unitFee * qty;
}
else
{ amount = unitFee; }
txtBillingUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(unitFee));
txtBillingTotal.Value = utils.returnFormattedDecimal(Convert.ToString(amount));
}
}
else
{
decimal.TryParse(txtBillingUnitPrice.Text, out unitFee);
if (qty > 0)
{
amount = unitFee * qty;
}
else
{ amount = unitFee; }
txtBillingUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(unitFee));
txtBillingTotal.Value = utils.returnFormattedDecimal(Convert.ToString(amount));
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Calculate amount
///
private void CalculateAmountEditLine(bool includeCall)
{
try
{
string code = String.Empty;
code = txtEditLineCode.Text;
decimal qty = 0;
decimal.TryParse(txtEditLineQty.Text, out qty);
decimal unitFee = 0;
decimal amount = 0;
if (includeCall)
{
oSetup setup = handler.ReturnSetup();
//CVH 2016-09-15 Only process items not deleted
foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code,isDeleted", code + ",0"))
{
decimal untiPriceExcl = item.SellPriceIncl;
if (setup.vatRegistered && setup.vatRate > 0)
{
untiPriceExcl = (100.00m / (100.00m + setup.vatRate)) * item.SellPriceIncl;
}
unitFee = untiPriceExcl;
if (qty > 0)
{
amount = unitFee * qty;
}
else
{ amount = unitFee; }
txtEditLineUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(unitFee));
txtEditLineTotal.Value = utils.returnFormattedDecimal(Convert.ToString(amount));
}
}
else
{
decimal.TryParse(txtEditLineUnitPrice.Text, out unitFee);
if (qty > 0)
{
amount = unitFee * qty;
}
else
{ amount = unitFee; }
txtEditLineUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(unitFee));
txtEditLineTotal.Value = utils.returnFormattedDecimal(Convert.ToString(amount));
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Populate Form Values
///
///
private void PopulateContactFormValues(ref oSales _Sales)
{
try
{
txtTitle.Value = _Sales.title;
txtInitials.Value = _Sales.initials;
txtName.Value = _Sales.name;
txtSurname.Value = _Sales.surname;
//calculate sales balance
_Sales.runningBal = xData.GetSalesBalance(_Sales.surfaceItemId);
txtAccBalance.Value = utils.returnFormattedDecimal(Convert.ToString(_Sales.runningBal));
if (utils.verifySession("loadType") && Session["loadType"].ToString() == "Redirected")
lnkBack.Visible = true;
else
lnkBack.Visible = false;
upSales.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Clear Posting values
///
private void ClearPostings(string surfaceItemId)
{
try
{
txtBillingCode.Text = String.Empty;
BindItemsNew("", "");
txtBillingQty.Text = "1";
txtBillingUnitPrice.Text = "0.00";
txtBillingTotal.Value = "0.00";
txtDetails.Text = "";
BindQuotesToImport(surfaceItemId, false);
txtTransactionDate.Disabled = false;
ddPaymentMethod.Enabled = true;
txtPaymentAmount.Disabled = false;
upTransaction.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Populate Statuses
///
private void PopulateStatuses()
{
try
{
lstSatuses.Items.Clear();
//lstSatuses.Items.Add(new ListItem("All", ""));
foreach (ListItem item in ddFilterType.Items)
{
if (item.Selected)
{
switch (item.Value)
{
case "CN": //Credit Note
if (lstSatuses.Items.FindByText("Allocated") == null)
{ lstSatuses.Items.Add(new ListItem("Allocated", "Allocated")); }
if (lstSatuses.Items.FindByText("Partially Allocated") == null)
{ lstSatuses.Items.Add(new ListItem("Partially Allocated", "Partially Allocated")); }
if (lstSatuses.Items.FindByText("Unallocated") == null)
{ lstSatuses.Items.Add(new ListItem("Unallocated", "Unallocated")); }
break;
case "TI": //invoice
if (lstSatuses.Items.FindByText("Draft") == null)
{ lstSatuses.Items.Add(new ListItem("Draft", "Draft")); }
if (lstSatuses.Items.FindByText("Overdue") == null)
{ lstSatuses.Items.Add(new ListItem("Overdue", "Overdue")); }
if (lstSatuses.Items.FindByText("Paid") == null)
{ lstSatuses.Items.Add(new ListItem("Paid", "Paid")); }
if (lstSatuses.Items.FindByText("Partially Paid") == null)
{ lstSatuses.Items.Add(new ListItem("Partially Paid", "Partially Paid")); }
if (lstSatuses.Items.FindByText("Unpaid") == null)
{ lstSatuses.Items.Add(new ListItem("Unpaid", "Unpaid")); }
break;
case "QT": //quote
if (lstSatuses.Items.FindByText("Accepted") == null)
{ lstSatuses.Items.Add(new ListItem("Accepted", "Accepted")); }
if (lstSatuses.Items.FindByText("Declined") == null)
{ lstSatuses.Items.Add(new ListItem("Declined", "Declined")); }
if (lstSatuses.Items.FindByText("Draft") == null)
{ lstSatuses.Items.Add(new ListItem("Draft", "Draft")); }
if (lstSatuses.Items.FindByText("Pending") == null)
{ lstSatuses.Items.Add(new ListItem("Pending", "Pending")); }
break;
case "PM": //receipt
if (lstSatuses.Items.FindByText("Allocated") == null)
{ lstSatuses.Items.Add(new ListItem("Allocated", "Allocated")); }
if (lstSatuses.Items.FindByText("Partially Allocated") == null)
{ lstSatuses.Items.Add(new ListItem("Partially Allocated", "Partially Allocated")); }
if (lstSatuses.Items.FindByText("Unallocated") == null)
{ lstSatuses.Items.Add(new ListItem("Unallocated", "Unallocated")); }
break;
}
}
}
//finally sort alphabetically
// get a LINQ-enabled list of the list items
List list = new List(lstSatuses.Items.Cast());
// use LINQ to Objects to order the items as required
list = list.OrderBy(li => li.Text).ToList();
// remove the unordered items from the listbox, so we don't get duplicates
lstSatuses.Items.Clear();
// now add back our sorted items
lstSatuses.Items.AddRange(list.ToArray());
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Bool to save an additonal note against a document type
///
///
///
///
private void PopulateExtraNote(int Type, int number)
{
try
{
foreach (oSalesExtraNote note in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesExtraNote), "type,number", Type + "," + number))
{
txtExtraNote.Text = note.note;
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Tally the total allocated so far
///
private void PopulateAllocatedSoFarTotal(ref decimal totalAllocated)
{
try
{
string currency = "ZAR";
foreach (RepeaterItem itm in rptInvoiceLines.Items)
{
Label lblDue = itm.FindControl("lblDue") as Label;
TextBox txbAllocateAmount = itm.FindControl("txbAllocateAmount") as TextBox;
if (txbAllocateAmount != null && txbAllocateAmount.Text != String.Empty)
{
decimal due = 0;
decimal.TryParse(lblDue.Text, out due);
decimal allocated = 0;
decimal.TryParse(txbAllocateAmount.Text, out allocated);
if (allocated > due)//allocated amount greater than what is due on invoice so fix to due amount
{
txbAllocateAmount.Text = utils.returnFormattedDecimal(Convert.ToString(due));
totalAllocated += due;
}
else if (allocated > 0 && allocated <= due)//allocated amount greater than zero but less or equal to sue so this is correct
{
totalAllocated += allocated;
}
else//not correct so reset to 0
{
txbAllocateAmount.Text = "0.00";
totalAllocated += 0;
}
}
}
lblTransactionTotal.Text = currency + " " + utils.returnFormattedDecimal(Convert.ToString(totalAllocated));
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region saving methods
///
/// Post Transaction Line
///
///
private bool PostTransactionLine(oSales acc)
{
bool result = false;
ArrayList billings = new ArrayList();
try
{
if (acc != null)
{
oSetup _setup = handler.ReturnSetup();
if (utils.verifySession("transactionLines"))
{
billings = (ArrayList)Session["transactionLines"];
/* CVH 2016-08-25 If there are existing sales lines saved, get details from existing line (eg Invoice No) Otherwise adding new lines to existing transactions doesn't work */
if (billings != null && billings.Count > 0)
{
oSales temp = (oSales)billings[0];
acc.accountNo = temp.accountNo;
acc.email = temp.email;
acc.emailCC = temp.emailCC;
acc.initials = temp.initials;
acc.invoiceNo = temp.invoiceNo;
acc.itemType = temp.itemType;
acc.name = temp.name;
acc.postalAddress = temp.postalAddress;
acc.receiptNo = temp.receiptNo;
acc.reference = temp.reference;
acc.surfaceItemId = temp.surfaceItemId;
acc.surname = temp.surname;
acc.title = temp.title;
acc.vatNum = temp.vatNum;
acc.vatRate = temp.vatRate;
}
}
//create a new billing
oSales accBilling = (oSales)utils.CloneObject(acc);
//get prcoedure
oSalesItem billingProc = new oSalesItem();
//CVH 2016-09-15 Only process items not deleted
foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code,isDeleted", txtBillingCode.Text + ",0"))
{
billingProc = item;
break;
}
if (billingProc.code != String.Empty)
{
//item type
accBilling.itemType = ddTransactionType.SelectedValue;
//quantity
decimal qty = 0;
decimal.TryParse(txtBillingQty.Text, out qty);
if (qty > 0)
accBilling.qty = qty;
else
accBilling.qty = 1;
//unit fee
decimal unitFee = 0;
decimal.TryParse(txtBillingUnitPrice.Text, out unitFee);
if (_setup.vatRegistered && _setup.vatRate > 0)
{
unitFee = unitFee + ((unitFee / 100) * _setup.vatRate);
}
accBilling.unitFee = unitFee;
//modifier - done seperately
//if (ddBillingModifier.SelectedValue != null)
// accBilling.modifier1 = ddBillingModifier.SelectedValue;
accBilling.dateOfService = utils.formatStringToDate(txtTransactionDate.Value);
//add time to date of service
TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
accBilling.dateOfService = accBilling.dateOfService.Add(time);
accBilling.dateDue = utils.formatStringToDate(txtTransactionDueDate.Value);
accBilling.itemCode = billingProc.code;
accBilling.itemDescription = txtDetails.Text;
accBilling.reference = txtReference.Value;
if (_setup.vatRegistered && _setup.vatRate > 0)
accBilling.vatRate = _setup.vatRate;
else
accBilling.vatRate = 0M;
//date of capture
accBilling.dateOfCapture = DateTime.Now;
//amounts
decimal amount = 0;
amount = qty * unitFee; //decimal.Ceiling(qty * unitFee);
accBilling.amount = amount;
//visible on statement
accBilling.isVisible = true;
decimal bal = 0;
foreach (oSales billBal in billings)
{
bal += billBal.amount;
}
//running balance
accBilling.runningBal += accBilling.amount + bal;
/* CVH 2016-08-22 If editing item, save line now, don't wait for Edit modal Save */
/* 2016-08-23 Not working, recId is always 0 */
//if (acc.recId > 0)
// accBilling.recId = xData.SaveTyped("recId", typeof(oSales), accBilling);
billings.Add(accBilling);
Session["transactionLines"] = billings;
result = true;
}
else
{
//invalid code
pnlResultBilling.Visible = true;
lblResultBilling.Text = "Please provide a valid code";
}
UpdateRunningTotals(acc.surfaceItemId.ToString());
BindSalesData();
result = true;
}
else
{
Response.Redirect("/home", false);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
return result;
}
///
/// bool to finalise a billing session
///
///
private bool FinaliseTransaction(bool isDraft, oSales acc)
{
bool result = false;
ArrayList transactions = new ArrayList();
try
{
if (utils.verifySession("transactionLines"))
{
transactions = (ArrayList)Session["transactionLines"];
int nextSequence = 0;
int number = 0;
foreach (oSales sale in transactions)
{
/* CVH 2016-08-25 Refresh contact details */
sale.accountNo = acc.accountNo.ToString();
sale.email = acc.email;
sale.emailCC = acc.emailCC;
sale.initials = acc.initials;
sale.name = acc.name;
sale.postalAddress = acc.postalAddress;
sale.surfaceItemId = acc.surfaceItemId;
sale.surname = acc.surname;
sale.title = acc.title;
if (sale.invoiceNo == 0)
{
if (nextSequence == 0)
{
switch (ddTransactionType.SelectedValue)
{
case "TI":
number = xData.GetInvoiceNoSales("TI");
break;
case "QT":
number = xData.GetQuoteNoSales();
sale.allocatedReference = "0";
break;
}
nextSequence = xData.GetNextSequenceSales(utils.formatStringToDate(txtTransactionDate.Value), sale.surfaceItemId);
}
else
{ nextSequence++; }
}
else
{
number = acc.invoiceNo;
if (nextSequence == 0)
nextSequence = xData.GetNextSequenceSales(utils.formatStringToDate(txtTransactionDate.Value), sale.surfaceItemId);
}
sale.invoiceNo = number == 0 ? sale.invoiceNo : number;
sale.reference = txtReference.Value;
sale.dateDue = utils.formatStringToDate(txtTransactionDueDate.Value);
sale.dateOfService = utils.formatStringToDate(txtTransactionDate.Value);
TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
sale.dateOfService = sale.dateOfService.Add(time);
sale.dateOfCapture = DateTime.Now;
sale.itemType = ddTransactionType.SelectedValue;
sale.sequence = nextSequence;
if (ddTransactionType.SelectedValue == "QT")
{
sale.statusId = pNums.SalesSatus.AwaitingAcceptance.GetHashCode();
}
//draft
sale.isDraft = isDraft;
}
if (transactions.Count > 0)
{
xData.UpdateTypedCollection("recId", typeof(oSales), transactions);
if (number == 0) number = ((oSales)transactions[0]).invoiceNo;
switch (ddTransactionType.SelectedValue)
{
case "TI":
SaveExtraNote(pNums.DocumentType.Invoice.GetHashCode(), number);
foreach (oCalendar cal in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendar), "billingModule,isActive", "2,1"))
{
foreach (oCalendarEvent calEv in xData.GetTypedByCriteriaContains("recId", typeof(oCalendarEvent), "users", acc.surfaceItemId.ToString()))
{
//only update appointments to billed if same date or earlier
if (calEv.calendarId == cal.recId && !calEv.isBilled && calEv.start.Date <= utils.formatStringToDate(txtTransactionDate.Value).Date)
{
calEv.isBilled = true;
xData.UpdateTyped("recId", calEv.recId.ToString(), typeof(oCalendarEvent), calEv);
}
}
}
break;
case "QT":
SaveExtraNote(pNums.DocumentType.Quote.GetHashCode(), number);
break;
}
//Update quote reference
if (ddRelatedTo.SelectedValue != "0" && ddTransactionType.SelectedValue == "TI")
{
foreach (oSales quoteItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType,invoiceNo", acc.surfaceItemId.ToString() + ",QT," + ddRelatedTo.SelectedValue, "sequence"))
{
//CVH 2016-09-15 Change allocated reference to only be invoice number, no prefix included, otherwise the link will be broken if prefix or length changes in company setup
quoteItem.allocatedReference = number.ToString();
quoteItem.allocated = quoteItem.amount;
xData.UpdateTyped("recId", quoteItem.recId.ToString(), typeof(oSales), quoteItem);
}
}
ViewState["num"] = number;
RemoveInvoiceReceipts(number, acc.surfaceItemId);
result = true;
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
return result;
}
///
/// Post Receipt Line
///
///
private bool PostReceiptLine(bool isDraft, oSales acc, string type)
{
bool result = false;
oNote updateNote = new oNote();
updateNote.recId = 0;
try
{
oSetup _setup = handler.ReturnSetup();
if (acc != null)
{
decimal CNAmount = 0;
decimal allocamount = 0;
bool canProceed = true;
if (type != "CN" && type != "AC")
{
PopulateAllocatedSoFarTotal(ref allocamount);
if (allocamount > 0)
{
decimal rctAmnt = 0;
decimal.TryParse(txtPaymentAmount.Value, out rctAmnt);
if (allocamount > rctAmnt)
{
canProceed = false;
pnlResultBilling.Visible = true;
lblResultBilling.Text = "You have allocated more than the total receipt amount, please adjust your allocations?";
}
}
}
if (canProceed)
{
oSales accPayment = new oSales();
if (utils.verifySession("AllocPayment"))
{
//pick up payment for allocation
accPayment = (oSales)Session["AllocPayment"];
if (accPayment.itemType == "PM")
{ ViewState["num"] = accPayment.receiptNo; }
else
{
ViewState["num"] = accPayment.invoiceNo;
}
}
else
{
if (Session["EditReceipt"] != null)
accPayment = (oSales)Session["EditReceipt"];
else
//create a new receipt
accPayment = (oSales)utils.CloneObject(acc);
if (ddPaymentMethod.SelectedValue != null && ddPaymentMethod.SelectedValue != String.Empty)
{
/* CVH 2016-08-25 Set Receipt reference */
accPayment.reference = txtReference.Value;
string noteCaption = String.Empty;
if (type == "CN")
{
accPayment.itemCode = "CN";
accPayment.itemDescription = "Credit Note";
accPayment.itemType = "CN";
//receipt number
if (accPayment.recId == 0)
accPayment.invoiceNo = xData.GetInvoiceNoSales("CN");
ViewState["num"] = accPayment.invoiceNo;
foreach (RepeaterItem cnItem in rptBillingAccounts.Items)
{
Label lblAmount = cnItem.FindControl("lblAmount") as Label;
if (lblAmount != null)
{
HiddenField hfAllocated = cnItem.FindControl("hfAllocated") as HiddenField;
decimal alloc = 0;
decimal.TryParse(hfAllocated.Value, out alloc);
decimal amnt = 0;
decimal.TryParse(lblAmount.Text, out amnt);
if (_setup.vatRegistered && _setup.vatRate > 0)
{
amnt = amnt + ((amnt / 100) * _setup.vatRate);
}
CNAmount += amnt - alloc;
}
}
accPayment.amount = CNAmount * -1;
if (_setup.vatRegistered && _setup.vatRate > 0)
{ accPayment.vatRate = _setup.vatRate; }
else
{ accPayment.vatRate = 0; }
noteCaption = "A credit note was passed to the value of R " + utils.returnFormattedDecimal((accPayment.amount).ToString());
}
else
{
//unit fee
decimal unitFee = 0;
decimal.TryParse(txtPaymentAmount.Value, out unitFee);
txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(unitFee));
//procedure info
accPayment.itemCode = ddPaymentMethod.SelectedValue;
noteCaption = "A payment was receipted to the value of R " + utils.returnFormattedDecimal((unitFee * -1).ToString());
accPayment.itemDescription = "Receipt - " + ddPaymentMethod.SelectedItem.Text;
accPayment.itemType = "PM";
accPayment.vatRate = 0;
//amounts
accPayment.amount = unitFee * -1;
//receipt number
if (accPayment.recId == 0)
accPayment.receiptNo = xData.GetNextRecNoSales();
ViewState["num"] = accPayment.receiptNo;
}
accPayment.qty = 1;
//service date
accPayment.dateOfService = utils.formatStringToDate(txtTransactionDate.Value);
TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
accPayment.dateOfService = accPayment.dateOfService.Add(time);
//date of capture
accPayment.dateOfCapture = DateTime.Now;
//visible on statement
accPayment.isVisible = true;
//running balance
accPayment.runningBal += accPayment.amount;
//set sequence on payment
accPayment.sequence = xData.GetNextSequence(utils.formatStringToDate(txtTransactionDate.Value), accPayment.surfaceItemId);
//draft
accPayment.isDraft = isDraft;
//Save receipt line to database
if (accPayment.recId == 0)
accPayment.recId = xData.SaveTyped("recId", typeof(oSales), accPayment);
else
{
//remove any allocations
if (accPayment.itemType == "PM")
{
UnAllocateReceipt(accPayment.receiptNo, accPayment.surfaceItemId);
}
else if (accPayment.itemType == "CN")
{
UnAllocateCreditNote(accPayment.invoiceNo, accPayment.surfaceItemId);
}
accPayment.allocatedReference = "";
accPayment.allocated = 0;
xData.UpdateTyped("recId", accPayment.recId.ToString(), typeof(oSales), accPayment);
Session["EditReceipt"] = null;
}
//add note for receipt
oNote note = new oNote();
note.moduleId = pNums.Module.Sales.GetHashCode();
note.typeId = pNums.NoteType.Payment.GetHashCode();
note.entityId = acc.surfaceItemId;
note.title = accPayment.itemDescription;
note.caption = noteCaption;
note.dateSaved = DateTime.Now;
note.userIdSaved = ((oUser)(Session["user"])).recId;
note.isActive = true;
note.recId = xData.SaveTyped("recId", typeof(oNote), note);
updateNote = note;
}
else
{
//invalid code
pnlResultBilling.Visible = true;
lblResultBilling.Text = "Please provide a payment method";
}
}
if (accPayment.recId > 0)
{
bool billingsAllocated = false;
decimal ToAllocate = 0;
switch (accPayment.itemType)
{
case "PM":
SaveExtraNote(pNums.DocumentType.Receipt.GetHashCode(), accPayment.receiptNo);
//apply allocations for receipt
ToAllocate = allocamount;
//apply allocations
foreach (RepeaterItem item in rptInvoiceLines.Items)
{
HiddenField hfInvoice = item.FindControl("hfInvoice") as HiddenField;
if (hfInvoice != null)
{
//get the amount being allocated to this invoice
TextBox txbAllocateAmount = item.FindControl("txbAllocateAmount") as TextBox;
int invNo = 0;
int.TryParse(hfInvoice.Value, out invNo);
decimal invAllocAmount = 0;
decimal.TryParse(txbAllocateAmount.Text, out invAllocAmount);
if (invAllocAmount > 0 && invNo > 0)
{
ToAllocate = ToAllocate - invAllocAmount;
foreach (oSales billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo", "TI," + invNo, "dateOfService,sequence"))
{
decimal availToAlloc = billing.amount - billing.allocated;
if (availToAlloc == invAllocAmount)//the amount is the same
{
billing.allocated = billing.amount;
if (billing.allocatedReference == String.Empty || billing.allocatedReference == "0")
{ billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
else
{ billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{
//update allocated reference to payment
if (accPayment.allocatedReference == String.Empty || accPayment.allocatedReference == "0")
{
accPayment.allocatedReference = billing.recId.ToString();
accPayment.allocated += availToAlloc;
}
else
{
accPayment.allocatedReference += "," + billing.recId.ToString();
accPayment.allocated += availToAlloc;
}
invAllocAmount = 0;
}
}
else if (availToAlloc > invAllocAmount)//then we want to partially allocate the billing
{
billing.allocated += invAllocAmount;
if (billing.allocatedReference == String.Empty || billing.allocatedReference == "0")
{ billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(invAllocAmount); }
else
{ billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(invAllocAmount); }
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{
//update allocated reference to payment
if (accPayment.allocatedReference == String.Empty || accPayment.allocatedReference == "0")
{
accPayment.allocatedReference = billing.recId.ToString();
accPayment.allocated += invAllocAmount;
}
else
{
accPayment.allocatedReference += "," + billing.recId.ToString();
accPayment.allocated += invAllocAmount;
}
invAllocAmount = 0;
}
}
else if (invAllocAmount > availToAlloc)//we have more to allcoate so will allocate in full and use left over for next billing
{
billing.allocated = billing.amount;
if (billing.allocatedReference == String.Empty || billing.allocatedReference == "0")
{ billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
else
{ billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{
//update allocated reference to payment
if (accPayment.allocatedReference == String.Empty || accPayment.allocatedReference == "0")
{
accPayment.allocatedReference = billing.recId.ToString();
accPayment.allocated += availToAlloc;
}
else
{
accPayment.allocatedReference += "," + billing.recId.ToString();
accPayment.allocated += availToAlloc;
}
invAllocAmount -= availToAlloc;//deduct from whats availabel to allocate
}
}
}
}
}
if (ToAllocate == 0)
{
break;
}
}
billingsAllocated = true;
break;
case "CN"://handle allocation for credit note
SaveExtraNote(pNums.DocumentType.CreditNote.GetHashCode(), accPayment.invoiceNo);
ToAllocate = Math.Abs(accPayment.amount) - accPayment.allocated;
//apply allocations
foreach (RepeaterItem item in rptBillingAccounts.Items)
{
if (ToAllocate > 0)
{
HiddenField hfRecId = (HiddenField)item.FindControl("hfRecId");
if (hfRecId != null)
{
int billingId = int.Parse(hfRecId.Value.ToString());
if (billingId > 0)
{
foreach (oSales billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", billingId.ToString(), "dateOfService,sequence"))
{
//accPayment.itemDescription += " -" + billing.itemCode;
decimal availToAlloc = billing.amount - billing.allocated;
if (availToAlloc == ToAllocate)//the amount is the same
{
billing.allocated = billing.amount;
if (billing.allocatedReference == String.Empty || billing.allocatedReference == "0")
{ billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
else
{ billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{
//update allocated reference to payment
if (accPayment.allocatedReference == String.Empty || accPayment.allocatedReference == "0")
{
accPayment.allocatedReference = billing.recId.ToString();
accPayment.allocated += availToAlloc;
}
else
{
accPayment.allocatedReference += "," + billing.recId.ToString();
accPayment.allocated += availToAlloc;
}
accPayment.itemDescription += "-" + billing.itemDescription;
ToAllocate = 0;
}
}
else if (availToAlloc > ToAllocate)//then we want to partially allocate the billing
{
billing.allocated += ToAllocate;
if (billing.allocatedReference == String.Empty || billing.allocatedReference == "0")
{ billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(ToAllocate); }
else
{ billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(ToAllocate); }
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{
//update allocated reference to payment
if (accPayment.allocatedReference == String.Empty || accPayment.allocatedReference == "0")
{
accPayment.allocatedReference = billing.recId.ToString();
accPayment.allocated += ToAllocate;
}
else
{
accPayment.allocatedReference += "," + billing.recId.ToString();
accPayment.allocated += ToAllocate;
}
accPayment.itemDescription += "-" + billing.itemDescription;
ToAllocate = 0;
}
}
else if (ToAllocate > availToAlloc)//we have more to allcoate so will allocate in full and use left over for next billing
{
billing.allocated = billing.amount;
if (billing.allocatedReference == String.Empty || billing.allocatedReference == "0")
{ billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
else
{ billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{
//update allocated reference to payment
if (accPayment.allocatedReference == String.Empty || accPayment.allocatedReference == "0")
{
accPayment.allocatedReference = billing.recId.ToString();
accPayment.allocated += availToAlloc;
}
else
{
accPayment.allocatedReference += "," + billing.recId.ToString();
accPayment.allocated += availToAlloc;
}
accPayment.itemDescription += "-" + billing.itemDescription;
ToAllocate -= availToAlloc;//deduct from whats availabel to allocate
}
}
}
billingsAllocated = true;
}
else
{
//self allocated credit note
if (accPayment.allocatedReference == String.Empty || accPayment.allocatedReference == "0")
accPayment.allocatedReference = accPayment.recId.ToString();
else
accPayment.allocatedReference += "," + accPayment.recId.ToString();
Label lblItemCode = item.FindControl("lblItemCode") as Label;
Label lblItemDescription = item.FindControl("lblItemDescription") as Label;
if (lblItemDescription != null)
accPayment.itemDescription += "-" + lblItemDescription.Text;
Label lblAmount = item.FindControl("lblAmount") as Label;
if (lblAmount != null)
{
HiddenField hfAllocated = item.FindControl("hfAllocated") as HiddenField;
decimal alloc = 0;
decimal.TryParse(hfAllocated.Value, out alloc);
decimal amnt = 0;
decimal.TryParse(lblAmount.Text, out amnt);
if (_setup.vatRegistered && _setup.vatRate > 0)
{
amnt = amnt + ((amnt / 100) * _setup.vatRate);
}
ToAllocate -= amnt - alloc;
accPayment.allocated += amnt - alloc;
}
//update cn
if (xData.UpdateTyped("recId", accPayment.recId.ToString(), typeof(oSales), accPayment))
{ billingsAllocated = true; }
}
}
}
}
break;
}
if (decimal.Round(ToAllocate) > 0 && billingsAllocated)//then split payment to allow for allocation later
{
accPayment.amount = (Math.Abs(accPayment.amount) - ToAllocate) * -1;
if (xData.UpdateTyped("recId", accPayment.recId.ToString(), typeof(oSales), accPayment))
{
//create a new payment
oSales accPaymentNew = (oSales)utils.CloneObject(accPayment);
accPaymentNew.recId = 0;
accPaymentNew.allocatedReference = "";
accPaymentNew.amount = ToAllocate * -1;
accPaymentNew.allocated = 0;
if (accPaymentNew.itemType == "PM")
{
accPaymentNew.receiptNo = xData.GetNextRecNoSales();
}
else
{
accPaymentNew.invoiceNo = xData.GetInvoiceNoSales("CN");
}
accPayment.sequence += 1;
accPayment.emailSent = false;
accPaymentNew.recId = xData.SaveTyped("recId", typeof(oSales), accPaymentNew);
/* CVH 2016-04-20 Add new note of type "Payment" */
oNote note = new oNote();
note.moduleId = pNums.Module.Sales.GetHashCode();
note.typeId = pNums.NoteType.Payment.GetHashCode();
note.entityId = acc.surfaceItemId;
note.title = accPayment.itemDescription;
note.caption = "A payment was receipted to the value of R " + utils.returnFormattedDecimal((accPayment.amount * -1).ToString());
note.dateSaved = DateTime.Now;
note.userIdSaved = ((oUser)(Session["user"])).recId;
note.isActive = true;
note.recId = xData.SaveTyped("recId", typeof(oNote), note);
}
}
else
{
if (xData.UpdateTyped("recId", accPayment.recId.ToString(), typeof(oSales), accPayment))
{
/* CVH 2016-05-03 Update the title of the note if the payment has been distributed to procedures */
//JR check if updateNote.recId >0
if (updateNote.recId > 0)
{
updateNote.caption = updateNote.caption + "
Items " + accPayment.itemDescription.Replace(updateNote.title, "");
xData.UpdateTyped("recId", updateNote.recId.ToString(), typeof(oNote), updateNote);
}
}
}
result = true;
utils.disposeSession("AllocPayment");
}
}
}
else
{
Response.Redirect("/home", false);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
return result;
}
///
/// Bool to save an additonal note against a document type
///
///
///
///
private bool SaveExtraNote(int Type, int number)
{
bool result = false;
oSalesExtraNote noteExtra = new oSalesExtraNote();
try
{
foreach (oSalesExtraNote note in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesExtraNote), "type,number", Type + "," + number))
{
noteExtra = note;
break;
}
noteExtra.number = number;
noteExtra.type = Type;
noteExtra.note = txtExtraNote.Text;
noteExtra.dateSaved = DateTime.Now;
if (noteExtra.recId > 0)
{
result = xData.UpdateTyped("recId", noteExtra.recId.ToString(), typeof(oSalesExtraNote), noteExtra);
}
else
{
noteExtra.recId = xData.SaveTyped("recId", typeof(oSalesExtraNote), noteExtra);
if (noteExtra.recId > 0)
result = true;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
return result;
}
#endregion
#region edit line methods
///
/// Populate Form Values
///
///
private void PopulateEditLineValues(ref oSales _Sales)
{
try
{
pnlResultEditLine.Visible = false;
txtEditLineDate.Value = _Sales.dateOfService.ToString("dd/MM/yyyy");
txtEditLineCode.Text = _Sales.itemCode;
rcbEditLineDescription.ClearSelection();
if (rcbEditLineDescription.Items.FindItemByValue(_Sales.itemCode) != null)
rcbEditLineDescription.SelectedValue = _Sales.itemCode;
/* CVH 2016-08-22 Load description */
txtEditDetails.Text = _Sales.itemDescription;
txtEditLineQty.Text = utils.returnFormattedDecimal(Convert.ToString(_Sales.qty));
decimal unitFeeExcl = _Sales.unitFee;
oSetup _setup = handler.ReturnSetup();
if (_setup.vatRegistered && _setup.vatRate > 0)
{
unitFeeExcl = (100.00m / (100.00m + _setup.vatRate)) * _Sales.unitFee;
}
txtEditLineUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(unitFeeExcl));
/* CVH 2016-08-24 Give false not true, otherwise it recalculates the amount from the item, it doesn't take the saved amount */
CalculateAmountEditLine(false);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Populate Form Values
///
///
private void SaveEditLineValues(ref oSales _Sales)
{
try
{
oSetup _setup = handler.ReturnSetup();
/* CVh 2016-08-22 Don't get the item from the item setup, just update the sales line */
//get prcoedure
//oSalesItem editItem = new oSalesItem();
//foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code", txtEditLineCode.Text))
//{
// editItem = item;
// break;
//}
//if (editItem.code != String.Empty)
//{
//quantity
decimal qty = 0;
decimal.TryParse(txtEditLineQty.Text, out qty);
if (qty > 0)
_Sales.qty = qty;
else
_Sales.qty = 1;
//unit fee
decimal unitFee = 0;
decimal.TryParse(txtEditLineUnitPrice.Text, out unitFee);
if (_setup.vatRegistered && _setup.vatRate > 0)
{
unitFee = unitFee + ((unitFee / 100) * _setup.vatRate);
}
_Sales.unitFee = unitFee;
/* CVH 2016-08-22 Take description and itemcode from modal */
//_Sales.itemDescription = editItem.description;
//_Sales.itemCode = editItem.code;
_Sales.itemDescription = txtEditDetails.Text;
_Sales.itemCode = txtEditLineCode.Text;
//service date
_Sales.dateOfService = utils.formatStringToDate(txtEditLineDate.Value);
TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
_Sales.dateOfService = _Sales.dateOfService.Add(time);
if (_setup.vatRegistered)
_Sales.vatRate = _setup.vatRate;
else
_Sales.vatRate = 0;
//date of capture
_Sales.dateOfCapture = DateTime.Now;
//amounts
decimal amount = 0;
amount = qty * unitFee; //decimal.Ceiling(qty * unitFee);
//balance
if (amount > _Sales.amount)// amount greater than previous
{
//so lets increase the running balance by that differenc
_Sales.runningBal = _Sales.runningBal += (amount - _Sales.amount);
}
else if (amount < _Sales.amount)//amount less than previous
{
//so lets decrease the balance by tat difference
_Sales.runningBal = _Sales.runningBal -= (_Sales.amount - amount);
}
_Sales.amount = amount;
//}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region quote methods
///
/// Accept a quote
///
///
///
private void AcceptQuote(int invoiceNo, int surfaceItemId)
{
try
{
foreach (oSales salesItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,invoiceNo", "QT," + surfaceItemId.ToString() + "," + invoiceNo.ToString()))
{
salesItem.statusId = pNums.SalesSatus.Accepted.GetHashCode();
salesItem.updateDate = DateTime.Now;
salesItem.updateUserId = ((oUser)(Session["user"])).recId;
xData.UpdateTyped("recId", salesItem.recId.ToString(), typeof(oSales), salesItem);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Accept Quote and invoice
///
///
///
private void AcceptQuoteAndInvoice(int invoiceNo, int surfaceItemId)
{
try
{
oSales quoteSale = null;
foreach (oSales salesItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,invoiceNo", "QT," + surfaceItemId.ToString() + "," + invoiceNo.ToString()))
{
/* CVH 2016-08-24 Set first line as sales object to use */
if (quoteSale == null)
quoteSale = salesItem;
salesItem.statusId = pNums.SalesSatus.Accepted.GetHashCode();
salesItem.updateDate = DateTime.Now;
salesItem.updateUserId = ((oUser)(Session["user"])).recId;
xData.UpdateTyped("recId", salesItem.recId.ToString(), typeof(oSales), salesItem);
}
if (quoteSale == null)
throw new Exception("Quote with number " + invoiceNo + " could not be found.");
/* CVH 2016-08-25 Disable Contact dropdown */
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
rcbSalesContacts.Enabled = false;
BindSalesData();
ToggleTransactionType("TI", surfaceItemId.ToString());
if (ddRelatedTo.Items.FindByValue(invoiceNo.ToString()) != null)
ddRelatedTo.SelectedValue = invoiceNo.ToString();
ddRelatedTo_SelectedIndexChanged(null, null);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myinvoiceModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "invoicePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Decline a Quote
///
///
///
private void DeclineQuote(int invoiceNo, int surfaceItemId)
{
try
{
foreach (oSales salesItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,invoiceNo", "QT," + surfaceItemId.ToString() + "," + invoiceNo.ToString()))
{
salesItem.statusId = pNums.SalesSatus.Declined.GetHashCode();
salesItem.updateDate = DateTime.Now;
salesItem.updateUserId = ((oUser)(Session["user"])).recId;
xData.UpdateTyped("recId", salesItem.recId.ToString(), typeof(oSales), salesItem);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Set Quote into Edit
///
///
///
private void SetQuoteEdit(int invoiceNo, int surfaceItemId)
{
try
{
oSales quoteSale = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo,surfaceItemId", "QT," + invoiceNo.ToString() + "," + surfaceItemId.ToString(), "sequence"))
{
/* CVH 2016-08-24 Set first line as sales object to use */
if (quoteSale == null)
quoteSale = saleItem;
billings.Add(saleItem);
}
if (quoteSale == null)
throw new Exception("Quote with number " + invoiceNo + " could not be found.");
Session["transactionLines"] = billings;
txtTransactionDate.Value = quoteSale.dateOfService.ToString("dd/MM/yyyy");
if (quoteSale.dateDue.Year > 1901)
txtTransactionDueDate.Value = quoteSale.dateDue.ToString("dd/MM/yyyy");
else
txtTransactionDueDate.Value = quoteSale.dateOfService.AddDays(7).ToString("dd/MM/yyyy");
txtReference.Value = quoteSale.reference;
pnlResultBilling.Visible = false;
pnlRelatedTo.Visible = false;
pnlPaymentMethods.Visible = false;
pnlPaymentAmount.Visible = false;
pnlAddItems.Visible = true;
pnlDueDate.Visible = true;
/* CVH 2016-08-25 Disable Contact dropdown */
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
rcbSalesContacts.Enabled = false;
ddTransactionType.SelectedValue = "QT";
txtTransactionDate.Disabled = true;
lblType.Text = "Quote:";
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleQTEPrefix, handler.ReturnSetup().saleQTENumLength, invoiceNo);
lblDueDate.Text = "Valid Until:";
btnSaveDraft.Visible = true;
BindTransactionLines();
upTransaction.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myQuoteModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "quotePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Delete a Quote line
///
///
///
private void DeleteQuote(int invoiceNo, int surfaceItemId)
{
try
{
foreach (oSales salesItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,invoiceNo", "QT," + surfaceItemId.ToString() + "," + invoiceNo.ToString()))
{
salesItem.isVisible = false;
salesItem.allocated = 0;
salesItem.allocatedReference = "0";
xData.UpdateTyped("recId", salesItem.recId.ToString(), typeof(oSales), salesItem);
}
BindSalesData();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myQuoteDeleteModal", "$('#modViewTransaction').modal('hide')", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Set Quote into View mode
///
///
///
private void SetQuoteView(int invoiceNo, int surfaceItemId)
{
try
{
oSales quoteSale = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo,surfaceItemId", "QT," + invoiceNo.ToString() + "," + surfaceItemId.ToString(), "sequence"))
{
/* CVH 2016-08-24 Set first line as sales object to use */
if (quoteSale == null)
quoteSale = saleItem;
billings.Add(saleItem);
}
if (quoteSale == null)
throw new Exception("Quote with number " + invoiceNo + " could not be found.");
pnlViewRelatedTo.Visible = false;
pnlViewPaymentMethod.Visible = false;
pnlViewAmount.Visible = false;
pnlViewDueDate.Visible = true;
lblViewHeading.Text = "Quote";
if (quoteSale.amount == quoteSale.allocated)
{
btnViewCreateInvoiceFromQuote.Visible = false;
btnViewAcceptAndInvoice.Visible = false;
}
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
txtViewContactName.Value = rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()).Text;
//CVH 2016-09-14 Build transaction number with padded 0's
txtViewNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleQTEPrefix, handler.ReturnSetup().saleQTENumLength, invoiceNo);
lblViewDueDateLabel.Text = "Valid Until:";
txtViewDate.Value = quoteSale.dateOfService.ToString("dd/MM/yyyy");
txtViewDueDate.Value = quoteSale.dateDue.ToString("dd/MM/yyyy");
txtViewReference.Value = quoteSale.reference;
Session["transactionLines"] = billings;
BindViewTransactionLines();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myViewQuoteModal", "$('#modViewTransaction').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Set Quote for copy
///
///
///
private void SetQuoteCopy(int invoiceNo, int surfaceItemId)
{
try
{
int newQuoteNo = xData.GetQuoteNoSales();
oSales quoteSale = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo,surfaceItemId", "QT," + invoiceNo.ToString() + "," + surfaceItemId.ToString() + ",", "sequence"))
{
/* CVH 2016-08-24 Set first line as sales object to use */
saleItem.recId = 0;
saleItem.allocated = 0;
saleItem.allocatedReference = string.Empty;
saleItem.invoiceNo = newQuoteNo;
saleItem.statusId = pNums.SalesSatus.AwaitingAcceptance.GetHashCode();
saleItem.emailSent = false;
saleItem.dateOfCapture = DateTime.Now;
saleItem.dateOfService = DateTime.Now;
TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
saleItem.dateOfService = saleItem.dateOfService.Add(time);
if (quoteSale == null)
quoteSale = saleItem;
billings.Add(saleItem);
}
if (quoteSale == null)
throw new Exception("Quote with number " + invoiceNo + " could not be found.");
Session["transactionLines"] = billings;
txtTransactionDate.Value = quoteSale.dateOfService.ToString("dd/MM/yyyy");
if (quoteSale.dateDue.Year > 1901)
txtTransactionDueDate.Value = quoteSale.dateDue.ToString("dd/MM/yyyy");
else
txtTransactionDueDate.Value = quoteSale.dateOfService.AddDays(7).ToString("dd/MM/yyyy");
txtReference.Value = quoteSale.reference;
pnlResultBilling.Visible = false;
pnlRelatedTo.Visible = false;
pnlPaymentMethods.Visible = false;
pnlPaymentAmount.Visible = false;
pnlAddItems.Visible = true;
pnlDueDate.Visible = true;
/* CVH 2016-08-25 Disable Contact dropdown */
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
rcbSalesContacts.Enabled = true;
ddTransactionType.SelectedValue = "QT";
lblType.Text = "Quote:";
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleQTEPrefix, handler.ReturnSetup().saleQTENumLength, newQuoteNo);
lblDueDate.Text = "Valid Until:";
BindTransactionLines();
/* CVH 2016-08-24 Need to be able to Save as Draft */
btnSaveDraft.Visible = true;
upTransaction.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myQuoteModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "quotePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Email a Quote
///
///
///
private void SendQuote(int invoiceNo, int surfaceItemId)
{
try
{
lblSendDocumentResult.Text = String.Empty;
pnlSendDocumentResult.Visible = false;
oSales saleQuote = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,invoiceNo,itemType", surfaceItemId.ToString() + "," + invoiceNo.ToString() + ",QT"))
{
saleQuote = sale;
break;
}
if (saleQuote == null)
throw new Exception("Quote with number " + invoiceNo + " could not be found.");
/* CVH 2016-09-02 Load default email subject from company setup */
string subject = "";
oSetup setup = handler.ReturnSetup();
subject = setup.emailSubjectQuote;
if (subject == String.Empty)
subject = "Quote {Document Number} from {Company Name}";
/* CVH 2016-09-13 Add trading as name to company name */
string companyName = setup.customer;
if (setup.tradingAs != String.Empty && !companyName.Contains(" t/a "))
companyName += " t/a " + setup.tradingAs;
//CVH 2016-09-14 Build transaction number with padded 0's
subject = subject.Replace("{Document Number}", xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleQTEPrefix, handler.ReturnSetup().saleQTENumLength, saleQuote.invoiceNo)).Replace("{Company Name}", companyName);
if (subject == String.Empty)
subject = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleQTEPrefix, handler.ReturnSetup().saleQTENumLength, saleQuote.invoiceNo);
/* CVH 2016-09-02 Load email template for user to edit before sending */
edEmailBody.Content = String.Empty;
foreach (oTemplate template in xData.GetTypedByCriteriaSpecific("recId", typeof(oTemplate), "templateName", "Sales Quote E-mail Template"))
{
edEmailBody.Content = xSales.BuildEmailTemplate(template.templateContent, saleQuote, setup, ConfigurationManager.AppSettings["WebAddy"]);
break;
}
string to = "";
string cc = ConfigurationManager.AppSettings["admin"];
string bcc = ConfigurationManager.AppSettings["bcc"];
to = saleQuote.email;
if (cc == String.Empty)
cc = saleQuote.emailCC;
else if (saleQuote.emailCC != String.Empty)
{ cc += ";" + saleQuote.emailCC; }
/* CVH 2016-08-17 Load email settings */
lblSendDocumentTitle.Text = subject;
txtField1.Text = subject;
txtField2.Value = to;
txtField3.Value = cc;
txtField4.Value = bcc;
txtField1.Focus();
//upSendDocument.Update();
ViewState["SendSale"] = saleQuote;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "mySendDocumentModalQuote", "$('#modSendDocument').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#region invoice methods
///
/// Set invoice into edit mode
///
///
///
private void SetInvoiceEdit(int invoiceNo, int surfaceItemId)
{
try
{
oSales saleInvoice = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo,surfaceItemId", "TI," + invoiceNo.ToString() + "," + surfaceItemId.ToString() + ",", "sequence"))
{
/* CVH 2016-08-24 Set first line as sales object to use */
if (saleInvoice == null)
saleInvoice = saleItem;
billings.Add(saleItem);
}
if (saleInvoice == null)
throw new Exception("Invoice with number " + invoiceNo + " could not be found.");
Session["transactionLines"] = billings;
/* CVH 2016-08-25 Disable Contact dropdown */
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
rcbSalesContacts.Enabled = false;
txtTransactionDate.Value = saleInvoice.dateOfService.ToString("dd/MM/yyyy");
if (saleInvoice.dateDue.Year > 1901)
txtTransactionDueDate.Value = saleInvoice.dateDue.ToString("dd/MM/yyyy");
else
txtTransactionDueDate.Value = saleInvoice.dateOfService.AddDays(7).ToString("dd/MM/yyyy");
txtReference.Value = saleInvoice.reference;
pnlResultBilling.Visible = false;
ddTransactionType.SelectedValue = "TI";
txtTransactionDate.Disabled = false;
ddPaymentMethod.Enabled = true;
txtPaymentAmount.Disabled = false;
lblType.Text = "Invoice:";
//bring in next invoice no
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleINVPrefix, handler.ReturnSetup().saleINVNumLength, invoiceNo);
//bind quotes for related to
BindQuotesToImport(saleInvoice.surfaceItemId.ToString(), true);
/* CVH 2016-08-25 Select Related Quote, and disable */
string relatedValue = GetRelatedToItemValue(saleInvoice);
if (ddRelatedTo.Items.FindByValue(relatedValue) != null)
ddRelatedTo.Items.FindByValue(relatedValue).Selected = true;
ddRelatedTo.Enabled = false;
//show related to
pnlRelatedTo.Visible = true;
pnlPaymentMethods.Visible = false;
pnlPaymentAmount.Visible = false;
pnlAddItems.Visible = true;
pnlDueDate.Visible = true;
lblDueDate.Text = "Due Date:";
btnSaveDraft.Visible = true;
BindTransactionLines();
upTransaction.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myinvoiceModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "invoicePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// set invoice into view mode
///
///
///
private void SetInvoiceView(int invoiceNo, int surfaceItemId)
{
try
{
oSales saleInvoice = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo,surfaceItemId", "TI," + invoiceNo.ToString() + "," + surfaceItemId.ToString() + ",", "sequence"))
{
/* CVH 2016-08-24 Set first line as sales object to use */
if (saleInvoice == null)
saleInvoice = saleItem;
billings.Add(saleItem);
}
if (saleInvoice == null)
throw new Exception("Invoice with number " + invoiceNo + " could not be found.");
//bind quotes for related to
BindQuotesToImport(saleInvoice.surfaceItemId.ToString(), true);
/* CVH 2016-08-25 Select Related Quote, and disable */
string relatedValue = GetRelatedToItemValue(saleInvoice);
if (ddRelatedTo.Items.FindByValue(relatedValue) != null)
txtViewRelatedTo.Value = ddRelatedTo.Items.FindByValue(relatedValue).Text;
pnlViewRelatedTo.Visible = true;
pnlViewPaymentMethod.Visible = false;
pnlViewAmount.Visible = false;
pnlViewDueDate.Visible = true;
lblViewHeading.Text = "Invoice";
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
txtViewContactName.Value = rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()).Text;
//CVH 2016-09-14 Build transaction number with padded 0's
txtViewNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleINVPrefix, handler.ReturnSetup().saleINVNumLength, invoiceNo);
lblViewDueDateLabel.Text = "Due Date:";
txtViewDate.Value = saleInvoice.dateOfService.ToString("dd/MM/yyyy");
txtViewDueDate.Value = saleInvoice.dateDue.ToString("dd/MM/yyyy");
txtViewReference.Value = saleInvoice.reference;
Session["transactionLines"] = billings;
BindViewTransactionLines();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myViewInvoiceModal", "$('#modViewTransaction').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// set invoice for copy
///
///
///
private void SetInvoiceCopy(int invoiceNo, int surfaceItemId)
{
try
{
//bring in next invoice no
int newInvoiceNo = xData.GetInvoiceNoSales("TI");
oSales saleInvoice = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo,surfaceItemId", "TI," + invoiceNo.ToString() + "," + surfaceItemId.ToString() + ",", "sequence"))
{
/* CVH 2016-08-24 Set first line as sales object to use */
if (saleInvoice == null)
saleInvoice = saleItem;
saleItem.recId = 0;
saleItem.invoiceNo = newInvoiceNo;
saleItem.statusId = pNums.SalesSatus.Unpaid.GetHashCode();
saleItem.emailSent = false;
saleItem.allocated = 0;
saleItem.allocatedReference = "";
billings.Add(saleItem);
}
/* CVH 2016-08-24 Even for a copy, there must be at least one oSales line saved */
if (saleInvoice == null)
throw new Exception("Invoice with number " + invoiceNo + " could not be found.");
Session["transactionLines"] = billings;
txtTransactionDate.Value = saleInvoice.dateOfService.ToString("dd/MM/yyyy");
if (saleInvoice.dateDue.Year > 1901)
txtTransactionDueDate.Value = saleInvoice.dateDue.ToString("dd/MM/yyyy");
else
txtTransactionDueDate.Value = saleInvoice.dateOfService.AddDays(7).ToString("dd/MM/yyyy");
txtReference.Value = saleInvoice.reference;
pnlResultBilling.Visible = false;
ddTransactionType.SelectedValue = "TI";
txtTransactionDate.Disabled = false;
ddPaymentMethod.Enabled = true;
txtPaymentAmount.Disabled = false;
lblType.Text = "Invoice:";
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleINVPrefix, handler.ReturnSetup().saleINVNumLength, newInvoiceNo);
/* CVH 2016-08-25 Don't bind related quotes dropdown, and disable. Can't copy existing invoice and relate it to quote */
ddRelatedTo.Enabled = false;
//show related to
pnlRelatedTo.Visible = true;
pnlPaymentMethods.Visible = false;
pnlPaymentAmount.Visible = false;
pnlAddItems.Visible = true;
pnlDueDate.Visible = true;
lblDueDate.Text = "Due Date:";
/* CVH 2016-08-25 Disable Contact dropdown */
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
rcbSalesContacts.Enabled = true;
BindTransactionLines();
upTransaction.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myinvoiceModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "invoicePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Delete a Invoice line
///
///
///
private void Deleteinvoice(int invoiceNo, int surfaceItemId)
{
try
{
//get the invoice lines
foreach (oSales salesItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,invoiceNo", "TI," + surfaceItemId.ToString() + "," + invoiceNo.ToString()))
{
//remove any associated Quotes
//CVH 2016-09-15 Allocated reference now excludes prefix, only number saved
foreach (oSales qt in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,allocatedReference", "QT," + surfaceItemId.ToString() + "," + invoiceNo))
{
qt.allocatedReference = "0";
qt.allocated = 0;
//update quote line
xData.UpdateTyped("recId", qt.recId.ToString(), typeof(oSales), qt);
}
//check if the invoice line item has been allocated
if (salesItem.allocatedReference != String.Empty && salesItem.allocatedReference != "0")
{
//ok now get receipts alloctaed to this invoice to remove their references
string[] references = salesItem.allocatedReference.Split(char.Parse(","));
//enumerate receipt referfences
foreach (string sref in references)
{
int payId = 0;
decimal recAmount = 0;
if (sref.Contains(":"))//first part of strign is the receipt rec id
{
int.TryParse(sref.Substring(0, sref.IndexOf(":")), out payId);
decimal.TryParse(sref.Substring(sref.IndexOf(":") + 1), out recAmount);
}
else
{ int.TryParse(sref, out payId); }
if (payId > 0)//we have a receipt
{
//get the receipt
foreach (oSales recp in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", payId.ToString()))
{
//strign to rebuild the billing references that are not on this invoice
string adjustedPrefs = String.Empty;
//split references
string[] billRefs = recp.allocatedReference.Split(char.Parse(","));
foreach (string bref in billRefs)
{
int billId = 0;
if (bref.Contains(":"))
{ int.TryParse(bref.Substring(0, bref.IndexOf(":")), out billId); }
else
{ int.TryParse(bref, out billId); }
if (billId > 0)//we have a billing id
{
if (billId != salesItem.recId)
{
if (adjustedPrefs == String.Empty)
adjustedPrefs = billId.ToString();
else
adjustedPrefs += "," + billId.ToString();
}
else
{
recp.allocated -= recAmount;
}
}
}
//update receipt with removed billing reference
xData.UpdateTyped("recId", recp.recId.ToString(), typeof(oSales), recp);
}
}
}
}
salesItem.isVisible = false;
salesItem.allocated = 0;
salesItem.allocatedReference = "0";
xData.UpdateTyped("recId", salesItem.recId.ToString(), typeof(oSales), salesItem);
}
BindSalesData();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myQuoteDeleteModal", "$('#modViewTransaction').modal('hide')", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Email and invoice
///
///
///
private void SendInvoice(int invoiceNo, int surfaceItemId)
{
try
{
lblSendDocumentResult.Text = String.Empty;
pnlSendDocumentResult.Visible = false;
oSales saleInvoice = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,invoiceNo,itemType", surfaceItemId.ToString() + "," + invoiceNo.ToString() + ",TI"))
{
saleInvoice = sale;
break;
}
if (saleInvoice == null)
throw new Exception("Invoice with number " + invoiceNo + " could not be found.");
/* CVH 2016-09-02 Load default email subject from company setup */
string subject = "";
oSetup setup = handler.ReturnSetup();
subject = setup.emailSubjectInvoice;
if (subject == String.Empty)
subject = "Invoice {Document Number} from {Company Name}";
/* CVH 2016-09-13 Add trading as name to company name */
string companyName = setup.customer;
if (setup.tradingAs != String.Empty && !companyName.Contains(" t/a "))
companyName += " t/a " + setup.tradingAs;
//CVH 2016-09-14 Build transaction number with padded 0's
subject = subject.Replace("{Document Number}", xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleINVPrefix, handler.ReturnSetup().saleINVNumLength, saleInvoice.invoiceNo)).Replace("{Company Name}", companyName);
if (subject == String.Empty)
subject = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleINVPrefix, handler.ReturnSetup().saleINVNumLength, saleInvoice.invoiceNo);
/* CVH 2016-09-02 Load email template for user to edit before sending */
edEmailBody.Content = String.Empty;
foreach (oTemplate template in xData.GetTypedByCriteriaSpecific("recId", typeof(oTemplate), "templateName", "Sales Invoice E-mail Template"))
{
edEmailBody.Content = xSales.BuildEmailTemplate(template.templateContent, saleInvoice, setup, ConfigurationManager.AppSettings["WebAddy"]);
break;
}
string to = "";
string cc = ConfigurationManager.AppSettings["admin"];
string bcc = ConfigurationManager.AppSettings["bcc"];
to = saleInvoice.email;
if (cc == String.Empty)
cc = saleInvoice.emailCC;
else if (saleInvoice.emailCC != String.Empty)
{ cc += ";" + saleInvoice.emailCC; }
/* CVH 2016-08-17 Load email settings */
lblSendDocumentTitle.Text = subject;
txtField1.Text = subject;
txtField2.Value = to;
txtField3.Value = cc;
txtField4.Value = bcc;
ViewState["SendSale"] = saleInvoice;
//ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "mySetSize", "SetRadEditorSize();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "mySendDocumentModal", "$('#modSendDocument').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Email and invoice
///
///
///
private void RemoveInvoiceReceipts(int invoiceNo, int surfaceItemId)
{
try
{
//get the invoice lines
foreach (oSales salesItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,invoiceNo", "TI," + surfaceItemId.ToString() + "," + invoiceNo.ToString()))
{
//check if the invoice line item has been allocated
if (salesItem.allocatedReference != String.Empty && salesItem.allocatedReference != "0")
{
//ok now get receipts alloctaed to this invoice to remove their references
string[] references = salesItem.allocatedReference.Split(char.Parse(","));
//enumerate receipt referfences
foreach (string sref in references)
{
int payId = 0;
decimal recAmount = 0;
if (sref.Contains(":"))//first part of strign is the receipt rec id
{
int.TryParse(sref.Substring(0, sref.IndexOf(":")), out payId);
decimal.TryParse(sref.Substring(sref.IndexOf(":") + 1), out recAmount);
}
else
{ int.TryParse(sref, out payId); }
if (payId > 0)//we have a receipt
{
//get the receipt
foreach (oSales recp in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", payId.ToString()))
{
//strign to rebuild the billing references that are not on this invoice
string adjustedPrefs = String.Empty;
//split references
string[] billRefs = recp.allocatedReference.Split(char.Parse(","));
foreach (string bref in billRefs)
{
int billId = 0;
if (bref.Contains(":"))
{ int.TryParse(bref.Substring(0, bref.IndexOf(":")), out billId); }
else
{ int.TryParse(bref, out billId); }
if (billId > 0)//we have a billing id
{
if (billId != salesItem.recId)
{
if (adjustedPrefs == String.Empty)
adjustedPrefs = billId.ToString();
else
adjustedPrefs += "," + billId.ToString();
}
else
{
recp.allocated -= recAmount;
}
}
}
//update alloctaed references
recp.allocatedReference = adjustedPrefs;
//update receipt with removed billing reference
xData.UpdateTyped("recId", recp.recId.ToString(), typeof(oSales), recp);
}
}
}
}
salesItem.allocated = 0;
salesItem.allocatedReference = "0";
xData.UpdateTyped("recId", salesItem.recId.ToString(), typeof(oSales), salesItem);
}
BindSalesData();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myQuoteDeleteModal", "$('#modViewTransaction').modal('hide')", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region receipt methods
///
/// Add a new Receipt
///
///
///
private void AddReceipt(int invoiceNo, int surfaceItemId)
{
try
{
foreach (oSales salesItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,invoiceNo", "TI," + surfaceItemId.ToString() + "," + invoiceNo.ToString()))
{
salesItem.updateDate = DateTime.Now;
salesItem.updateUserId = ((oUser)(Session["user"])).recId;
xData.UpdateTyped("recId", salesItem.recId.ToString(), typeof(oSales), salesItem);
}
ToggleTransactionType("PM", surfaceItemId.ToString());
//foreach (ListItem item in lstRelatedTo.Items)
//{
// if (item.Value == invoiceNo.ToString())
// item.Selected = true;
//}
//lstRelatedTo_SelectedIndexChanged(null, null);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myreceiptModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "receiptPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Set Receipt into view mode
///
///
///
private void SetReceiptView(int receiptNo, int surfaceItemId)
{
try
{
oSales saleCreditNote = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,receiptNo,surfaceItemId", "PM," + receiptNo.ToString() + "," + surfaceItemId.ToString() + ",", "sequence"))
{
/* CVH 2016-08-24 Set first line as sales object to use */
if (saleCreditNote == null)
saleCreditNote = saleItem;
billings.Add(saleItem);
}
if (saleCreditNote == null)
throw new Exception("Receipt with number " + receiptNo + " could not be found.");
//bind quotes for related to
BindInvoicesToAlllocate(saleCreditNote.surfaceItemId.ToString());
/* CVH 2016-08-25 Select Related Quote, and disable */
string relatedValue = GetRelatedToItemValue(saleCreditNote);
foreach (ListItem item in lstRelatedTo.Items)
{
if (item.Value == relatedValue)
item.Selected = true;
}
pnlViewRelatedTo.Visible = true;
//CVH 2016-09-16 lstRelatedTo Visibility set when binding
ddRelatedTo.Visible = false;
pnlViewPaymentMethod.Visible = false;
pnlViewAmount.Visible = false;
pnlViewDueDate.Visible = false;
lblViewHeading.Text = "Receipt";
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
txtViewContactName.Value = rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()).Text;
//CVH 2016-09-14 Build transaction number with padded 0's
txtViewNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleRCTPrefix, handler.ReturnSetup().saleRCTNumLength, receiptNo);
txtViewDate.Value = saleCreditNote.dateOfService.ToString("dd/MM/yyyy");
txtViewDueDate.Value = saleCreditNote.dateDue.ToString("dd/MM/yyyy");
txtViewReference.Value = saleCreditNote.reference;
Session["transactionLines"] = billings;
BindViewTransactionLines();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myViewInvoiceModal", "$('#modViewTransaction').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Set Receipt for Edit mode
///
///
///
private void SetReceiptEdit(int receiptNo, int surfaceItemId)
{
try
{
oSales saleReceipt = null;
Session["EditReceipt"] = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,receiptNo,surfaceItemId", "PM," + receiptNo.ToString() + "," + surfaceItemId.ToString() + ",", "sequence"))
{
saleReceipt = saleItem;
break;
}
if (saleReceipt == null)
throw new Exception("Receipt with number " + receiptNo + " could not be found.");
Session["transactionLines"] = billings;
ToggleTransactionType("PM", saleReceipt.surfaceItemId.ToString());
saleReceipt.allocated = 0;
saleReceipt.allocatedReference = "";
Session["EditReceipt"] = saleReceipt;
txtTransactionDate.Value = saleReceipt.dateOfService.ToString("dd/MM/yyyy");
if (saleReceipt.dateDue.Year > 1901)
txtTransactionDueDate.Value = saleReceipt.dateDue.ToString("dd/MM/yyyy");
else
txtTransactionDueDate.Value = saleReceipt.dateOfService.AddDays(7).ToString("dd/MM/yyyy");
txtReference.Value = saleReceipt.reference;
txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(Math.Abs(saleReceipt.amount)));
//bring in next invoice no
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleRCTPrefix, handler.ReturnSetup().saleRCTNumLength, receiptNo);
//bind invoiced for allocation
BindInvoicesToAlllocate(saleReceipt.surfaceItemId.ToString());
//show related to
pnlRelatedTo.Visible = true;
//CVH 2016-09-16 lstRelatedTo Visibility set when binding
ddRelatedTo.Visible = false;
pnlPaymentMethods.Visible = true;
pnlPaymentAmount.Visible = true;
pnlAddItems.Visible = false;
pnlDueDate.Visible = false;
txtReference.Disabled = false;
btnSaveDraft.Visible = true;
/* CVH 2016-08-25 Disable Contact dropdown */
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
rcbSalesContacts.Enabled = false;
BindTransactionLines();
upTransaction.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myinvoiceModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "invoicePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Email a Receipt
///
///
///
private void SendReceipt(int receiptNo, int surfaceItemId)
{
try
{
lblSendDocumentResult.Text = String.Empty;
pnlSendDocumentResult.Visible = false;
oSales saleReceipt = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,receiptNo,itemType", surfaceItemId.ToString() + "," + receiptNo.ToString() + ",PM"))
{
saleReceipt = sale;
break;
}
if (saleReceipt == null)
throw new Exception("Receipt with number " + receiptNo + " could not be found.");
/* CVH 2016-09-02 Load default email subject from company setup */
string subject = "";
oSetup setup = handler.ReturnSetup();
subject = setup.emailSubjectReceipt;
if (subject == String.Empty)
subject = "Receipt {Document Number} from {Company Name}";
/* CVH 2016-09-13 Add trading as name to company name */
string companyName = setup.customer;
if (setup.tradingAs != String.Empty && !companyName.Contains(" t/a "))
companyName += " t/a " + setup.tradingAs;
//CVH 2016-09-14 Build transaction number with padded 0's
subject = subject.Replace("{Document Number}", xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleRCTPrefix, handler.ReturnSetup().saleRCTNumLength, saleReceipt.receiptNo)).Replace("{Company Name}", companyName);
if (subject == String.Empty)
subject = "Receipt " + saleReceipt.receiptNo;
/* CVH 2016-09-02 Load email template for user to edit before sending */
edEmailBody.Content = String.Empty;
foreach (oTemplate template in xData.GetTypedByCriteriaSpecific("recId", typeof(oTemplate), "templateName", "Sales Receipt E-mail Template"))
{
edEmailBody.Content = xSales.BuildEmailTemplate(template.templateContent, saleReceipt, setup, ConfigurationManager.AppSettings["WebAddy"]);
break;
}
string to = "";
string cc = ConfigurationManager.AppSettings["admin"];
string bcc = ConfigurationManager.AppSettings["bcc"];
to = saleReceipt.email;
if (cc == String.Empty)
cc = saleReceipt.emailCC;
else if (saleReceipt.emailCC != String.Empty)
{ cc += ";" + saleReceipt.emailCC; }
/* CVH 2016-08-17 Load email settings */
lblSendDocumentTitle.Text = subject;
txtField1.Text = subject;
txtField2.Value = to;
txtField3.Value = cc;
txtField4.Value = bcc;
//upSendDocument.Update();
ViewState["SendSale"] = saleReceipt;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "mySendDocumentModal", "$('#modSendDocument').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Unallocate a Receipt
///
///
///
private void UnAllocateReceipt(int receiptNo, int surfaceItemId)
{
try
{
oSales saleReceipt = new oSales();
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,receiptNo,itemType", surfaceItemId.ToString() + "," + receiptNo.ToString() + ",PM"))
{
saleReceipt = sale;
break;
}
if (saleReceipt.recId > 0)
{
if (saleReceipt.allocatedReference != String.Empty)
{
//then we need to undo these allocations
string[] allocBillingIds = saleReceipt.allocatedReference.Split(char.Parse(","));
decimal amountAllocated = Math.Abs(saleReceipt.amount);
foreach (string sId in allocBillingIds)
{
int billId = 0;
if (sId.Contains(":"))
{ int.TryParse(sId.Substring(0, sId.IndexOf(":")), out billId); }
else
{ int.TryParse(sId, out billId); }
foreach (oSales billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", billId.ToString()))
{
string[] references = billing.allocatedReference.Split(char.Parse(","));
string adjustedReferences = String.Empty;
foreach (string sref in references)
{
if (sref.Contains(":"))
{
int payId = int.Parse(sref.Substring(0, sref.IndexOf(":")));
if (payId == saleReceipt.recId)
{
decimal amount = Convert.ToDecimal(sref.Substring(sref.IndexOf(":") + 1));
amountAllocated -= amount;
billing.allocated -= amount;
}
else
{
if (adjustedReferences == String.Empty)
{ adjustedReferences = sref; }
else
{ adjustedReferences += "," + sref; }
}
}
}
billing.allocatedReference = adjustedReferences;
//update alloc reference on billing line
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{ }
}
saleReceipt.allocatedReference = "";
saleReceipt.allocated = 0;
//update receipt
if (xData.UpdateTyped("recId", saleReceipt.recId.ToString(), typeof(oSales), saleReceipt))
{
BindSalesData();
}
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Delete a Receipt
///
///
///
private void DeleteReceipt(int receiptNo, int surfaceItemId)
{
try
{
oSales saleReceipt = new oSales();
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,receiptNo,itemType", surfaceItemId.ToString() + "," + receiptNo.ToString() + ",PM"))
{
saleReceipt = sale;
break;
}
if (saleReceipt.recId > 0)
{
if (saleReceipt.allocatedReference != String.Empty)
{
//then we need to undo these allocations
string[] allocBillingIds = saleReceipt.allocatedReference.Split(char.Parse(","));
decimal amountAllocated = Math.Abs(saleReceipt.amount);
foreach (string sId in allocBillingIds)
{
int billId = 0;
if (sId.Contains(":"))
{ int.TryParse(sId.Substring(0, sId.IndexOf(":")), out billId); }
else
{ int.TryParse(sId, out billId); }
foreach (oSales billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", billId.ToString()))
{
string[] references = billing.allocatedReference.Split(char.Parse(","));
string adjustedReferences = String.Empty;
foreach (string sref in references)
{
if (sref.Contains(":"))
{
int payId = int.Parse(sref.Substring(0, sref.IndexOf(":")));
if (payId == saleReceipt.recId)
{
decimal amount = Convert.ToDecimal(sref.Substring(sref.IndexOf(":") + 1));
amountAllocated -= amount;
billing.allocated -= amount;
}
else
{
if (adjustedReferences == String.Empty)
{ adjustedReferences = sref; }
else
{ adjustedReferences += "," + sref; }
}
}
}
billing.allocatedReference = adjustedReferences;
//update alloc reference on billing line
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{ }
}
saleReceipt.allocatedReference = "";
saleReceipt.allocated = 0;
}
}
saleReceipt.isVisible = false;
//update receipt
if (xData.UpdateTyped("recId", saleReceipt.recId.ToString(), typeof(oSales), saleReceipt))
{
BindSalesData();
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#region credit note methods
///
/// Add a new Credit Note
///
///
///
private void AddCreditNote(int invoiceNo, int surfaceItemId)
{
try
{
foreach (oSales salesItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,surfaceItemId,invoiceNo", "TI," + surfaceItemId.ToString() + "," + invoiceNo.ToString()))
{
salesItem.updateDate = DateTime.Now;
salesItem.updateUserId = ((oUser)(Session["user"])).recId;
xData.UpdateTyped("recId", salesItem.recId.ToString(), typeof(oSales), salesItem);
}
ToggleTransactionType("CN", surfaceItemId.ToString());
rcbSalesContacts.ClearSelection();
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
foreach (ListItem item in lstRelatedTo.Items)
{
if (item.Value == invoiceNo.ToString())
item.Selected = true;
}
lstRelatedTo_SelectedIndexChanged(null, null);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myreceiptModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "receiptPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Set Credit note into view mode
///
///
///
private void SetCreditNoteView(int invoiceNo, int surfaceItemId)
{
try
{
oSales saleCreditNote = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo,surfaceItemId", "CN," + invoiceNo.ToString() + "," + surfaceItemId.ToString() + ",", "sequence"))
{
/* CVH 2016-08-24 Set first line as sales object to use */
if (saleCreditNote == null)
saleCreditNote = saleItem;
billings.Add(saleItem);
}
if (saleCreditNote == null)
throw new Exception("Credit Note with number " + invoiceNo + " could not be found.");
//bind quotes for related to
BindInvoicesToAlllocate(saleCreditNote.surfaceItemId.ToString());
/* CVH 2016-08-25 Select Related Quote, and disable */
string relatedValue = GetRelatedToItemValue(saleCreditNote);
foreach (ListItem item in lstRelatedTo.Items)
{
if (item.Value == relatedValue)
item.Selected = true;
}
pnlViewRelatedTo.Visible = true;
//CVH 2016-09-16 lstRelatedTo Visibility set when binding
ddRelatedTo.Visible = false;
pnlViewPaymentMethod.Visible = false;
pnlViewAmount.Visible = false;
pnlViewDueDate.Visible = false;
lblViewHeading.Text = "Credit Note";
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
txtViewContactName.Value = rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()).Text;
//CVH 2016-09-14 Build transaction number with padded 0's
txtViewNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleCRNPrefix, handler.ReturnSetup().saleCRNNumLength, invoiceNo);
txtViewDate.Value = saleCreditNote.dateOfService.ToString("dd/MM/yyyy");
txtViewDueDate.Value = saleCreditNote.dateDue.ToString("dd/MM/yyyy");
txtViewReference.Value = saleCreditNote.reference;
Session["transactionLines"] = billings;
BindViewTransactionLines();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myViewInvoiceModal", "$('#modViewTransaction').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Set Credit note in Edit mode
///
///
///
private void SetCreditNoteEdit(int invoiceNo, int surfaceItemId)
{
try
{
oSales saleReceipt = null;
Session["EditReceipt"] = null;
ArrayList billings = new ArrayList();
foreach (oSales saleItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "itemType,invoiceNo,surfaceItemId", "CN," + invoiceNo.ToString() + "," + surfaceItemId.ToString() + ",", "sequence"))
{
saleReceipt = saleItem;
break;
}
if (saleReceipt == null)
throw new Exception("Credit Note with number " + invoiceNo + " could not be found.");
Session["transactionLines"] = billings;
ToggleTransactionType("CN", saleReceipt.surfaceItemId.ToString());
saleReceipt.allocated = 0;
saleReceipt.allocatedReference = "";
Session["EditReceipt"] = saleReceipt;
txtTransactionDate.Value = saleReceipt.dateOfService.ToString("dd/MM/yyyy");
if (saleReceipt.dateDue.Year > 1901)
txtTransactionDueDate.Value = saleReceipt.dateDue.ToString("dd/MM/yyyy");
else
txtTransactionDueDate.Value = saleReceipt.dateOfService.AddDays(7).ToString("dd/MM/yyyy");
txtReference.Value = saleReceipt.reference;
txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(Math.Abs(saleReceipt.amount)));
//bring in next invoice no
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleCRNPrefix, handler.ReturnSetup().saleCRNNumLength, invoiceNo);
//bind invoiced for allocation
BindInvoicesToAlllocate(saleReceipt.surfaceItemId.ToString());
//show related to
pnlRelatedTo.Visible = true;
//CVH 2016-09-16 lstRelatedTo Visibility set when binding
ddRelatedTo.Visible = false;
pnlPaymentMethods.Visible = true;
pnlPaymentAmount.Visible = true;
pnlAddItems.Visible = false;
pnlDueDate.Visible = false;
txtReference.Disabled = false;
btnSaveDraft.Visible = true;
/* CVH 2016-08-25 Disable Contact dropdown */
rcbSalesContacts.ClearSelection();
if (rcbSalesContacts.Items.FindItemByValue(surfaceItemId.ToString()) != null)
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
rcbSalesContacts.Enabled = false;
BindTransactionLines();
upTransaction.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myinvoiceModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "invoicePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Print a Credit Note
///
///
///
private void PrintCreditNote(int creditNoteNo, int surfaceItemId, string noteSurfaceFieldName)
{
try
{
/* CVH 2016-08-17 Print credit note, no modal */
string file = String.Empty;
string path = string.Empty;
DateTime creditNoteDate = DateTime.Now.Date;
oSales saleCreditNote = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,invoiceNo,itemType", surfaceItemId.ToString() + "," + creditNoteNo.ToString() + ",CN"))
{
saleCreditNote = sale;
break;
}
if (saleCreditNote == null)
throw new Exception("Credit note with number " + creditNoteNo + " could not be found.");
bool success = xSales.CreateSalesDocument(saleCreditNote, ConfigurationManager.AppSettings["WebAddy"], creditNoteDate, null, null, ref path, ref file, pNums.DocumentType.CreditNote, creditNoteNo.ToString());
if (success)
{
Response.Clear();
//Set the appropriate ContentType.
/* CVH 2016-08-22 Use text/html, otherwise Chrome gives error Resource interpreted as Document but transferred with MIME type application/pdf */
//Response.ContentType = "Application/pdf";
Response.ContentType = "text/html";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file);
Response.TransmitFile(path + file);
Response.Flush();
Response.SuppressContent = true;
ApplicationInstance.CompleteRequest();
//add note
int userId = 0;
if (utils.verifySession("user"))
{
userId = ((oUser)Session["user"]).recId;
}
xSales.AddCreateStatementNote(saleCreditNote.surfaceItemId, "Credit Note", "A credit note was created.", path, file, userId, noteSurfaceFieldName);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Email a Credit Note
///
///
///
private void SendCreditNote(int invoiceNo, int surfaceItemId)
{
try
{
lblSendDocumentResult.Text = String.Empty;
pnlSendDocumentResult.Visible = false;
oSales saleCreditNote = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,invoiceNo,itemType", surfaceItemId.ToString() + "," + invoiceNo.ToString() + ",CN"))
{
saleCreditNote = sale;
break;
}
if (saleCreditNote == null)
throw new Exception("Credit Note with number " + invoiceNo + " could not be found.");
/* CVH 2016-09-02 Load default email subject from company setup */
string subject = "";
oSetup setup = handler.ReturnSetup();
subject = setup.emailSubjectCreditNote;
if (subject == String.Empty)
subject = "Credit Note {Document Number} from {Company Name}";
/* CVH 2016-09-13 Add trading as name to company name */
string companyName = setup.customer;
if (setup.tradingAs != String.Empty && !companyName.Contains(" t/a "))
companyName += " t/a " + setup.tradingAs;
//CVH 2016-09-14 Build transaction number with padded 0's
subject = subject.Replace("{Document Number}", xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleCRNPrefix, handler.ReturnSetup().saleCRNNumLength, saleCreditNote.invoiceNo)).Replace("{Company Name}", companyName);
;
if (subject == String.Empty)
subject = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleCRNPrefix, handler.ReturnSetup().saleCRNNumLength, saleCreditNote.invoiceNo);
/* CVH 2016-09-02 Load email template for user to edit before sending */
edEmailBody.Content = String.Empty;
foreach (oTemplate template in xData.GetTypedByCriteriaSpecific("recId", typeof(oTemplate), "templateName", "Sales Credit Note E-mail Template"))
{
edEmailBody.Content = xSales.BuildEmailTemplate(template.templateContent, saleCreditNote, setup, ConfigurationManager.AppSettings["WebAddy"]);
break;
}
string to = "";
string cc = ConfigurationManager.AppSettings["admin"];
string bcc = ConfigurationManager.AppSettings["bcc"];
to = saleCreditNote.email;
if (cc == String.Empty)
cc = saleCreditNote.emailCC;
else if (saleCreditNote.emailCC != String.Empty)
cc += ";" + saleCreditNote.emailCC;
/* CVH 2016-08-17 Load email settings */
lblSendDocumentTitle.Text = subject;
txtField1.Text = subject;
txtField2.Value = to;
txtField3.Value = cc;
txtField4.Value = bcc;
//upSendDocument.Update();
ViewState["SendSale"] = saleCreditNote;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "mySendDocumentModal", "$('#modSendDocument').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Unallocate a Credit Note
///
///
///
private void UnAllocateCreditNote(int invoiceNo, int surfaceItemId)
{
try
{
oSales saleReceipt = new oSales();
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,invoiceNo,itemType", surfaceItemId.ToString() + "," + invoiceNo.ToString() + ",CN"))
{
saleReceipt = sale;
break;
}
if (saleReceipt.recId > 0)
{
if (saleReceipt.allocatedReference != String.Empty)
{
//then we need to undo these allocations
string[] allocBillingIds = saleReceipt.allocatedReference.Split(char.Parse(","));
decimal amountAllocated = Math.Abs(saleReceipt.amount);
foreach (string sId in allocBillingIds)
{
int billId = 0;
if (sId.Contains(":"))
{ int.TryParse(sId.Substring(0, sId.IndexOf(":")), out billId); }
else
{ int.TryParse(sId, out billId); }
foreach (oSales billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", billId.ToString()))
{
string[] references = billing.allocatedReference.Split(char.Parse(","));
string adjustedReferences = String.Empty;
foreach (string sref in references)
{
if (sref.Contains(":"))
{
int payId = int.Parse(sref.Substring(0, sref.IndexOf(":")));
if (payId == saleReceipt.recId)
{
decimal amount = Convert.ToDecimal(sref.Substring(sref.IndexOf(":") + 1));
amountAllocated -= amount;
billing.allocated -= amount;
}
else
{
if (adjustedReferences == String.Empty)
{ adjustedReferences = sref; }
else
{ adjustedReferences += "," + sref; }
}
}
}
billing.allocatedReference = adjustedReferences;
//update alloc reference on billing line
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{ }
}
saleReceipt.allocatedReference = "";
saleReceipt.allocated = 0;
//update credit note
if (xData.UpdateTyped("recId", saleReceipt.recId.ToString(), typeof(oSales), saleReceipt))
{
BindSalesData();
}
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Unallocate a Credit Note
///
///
///
private void DeleteCreditNote(int invoiceNo, int surfaceItemId)
{
try
{
oSales saleReceipt = new oSales();
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,invoiceNo,itemType", surfaceItemId.ToString() + "," + invoiceNo.ToString() + ",CN"))
{
saleReceipt = sale;
break;
}
if (saleReceipt.recId > 0)
{
if (saleReceipt.allocatedReference != String.Empty)
{
//then we need to undo these allocations
string[] allocBillingIds = saleReceipt.allocatedReference.Split(char.Parse(","));
decimal amountAllocated = Math.Abs(saleReceipt.amount);
foreach (string sId in allocBillingIds)
{
int billId = 0;
if (sId.Contains(":"))
{ int.TryParse(sId.Substring(0, sId.IndexOf(":")), out billId); }
else
{ int.TryParse(sId, out billId); }
foreach (oSales billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", billId.ToString()))
{
string[] references = billing.allocatedReference.Split(char.Parse(","));
string adjustedReferences = String.Empty;
foreach (string sref in references)
{
if (sref.Contains(":"))
{
int payId = int.Parse(sref.Substring(0, sref.IndexOf(":")));
if (payId == saleReceipt.recId)
{
decimal amount = Convert.ToDecimal(sref.Substring(sref.IndexOf(":") + 1));
amountAllocated -= amount;
billing.allocated -= amount;
}
else
{
if (adjustedReferences == String.Empty)
{ adjustedReferences = sref; }
else
{ adjustedReferences += "," + sref; }
}
}
}
billing.allocatedReference = adjustedReferences;
//update alloc reference on billing line
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{ }
}
saleReceipt.allocatedReference = "";
saleReceipt.allocated = 0;
}
}
saleReceipt.isVisible = false;
//update credit note
if (xData.UpdateTyped("recId", saleReceipt.recId.ToString(), typeof(oSales), saleReceipt))
{
BindSalesData();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myCreditNoteDeleteModal", "$('#modViewTransaction').modal('toggle')", true);
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#region action methods
///
/// Get parameter values from command argument
///
///
///
///
///
///
private static void GetParamValues(object sender, out string itemType, out int surfaceItemId, out int invoiceNo, out int receiptNo)
{
itemType = string.Empty;
receiptNo = 0;
surfaceItemId = 0;
invoiceNo = 0;
string[] argumentArray = ((LinkButton)sender).CommandArgument.Split(';');
surfaceItemId = Convert.ToInt32(argumentArray[0]);
itemType = argumentArray[1];
invoiceNo = Convert.ToInt32(argumentArray[2]);
receiptNo = Convert.ToInt32(argumentArray[3]);
}
///
/// Allocate a Line
///
///
///
///
///
private void AllocateLine(int surfaceItemId, string itemType, int receiptNo, int invoiceNo)
{
try
{
oSales allocLine = new oSales();
switch (itemType)
{
case "PM":
foreach (oSales payLine in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType,receiptNo", surfaceItemId + "," + itemType + "," + receiptNo))
{
allocLine = payLine;
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleRCTPrefix, handler.ReturnSetup().saleRCTNumLength, receiptNo);
break;
}
break;
case "CN":
foreach (oSales payLine in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType,invoiceNo", surfaceItemId + "," + itemType + "," + invoiceNo))
{
allocLine = payLine;
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleCRNPrefix, handler.ReturnSetup().saleCRNNumLength, invoiceNo);
break;
}
break;
}
if (allocLine.recId > 0)
{
Session["transactionLines"] = null;
BindTransactionLines();
Session["AllocPayment"] = allocLine;
switch (itemType)
{
case "PM":
ToggleTransactionType("A", allocLine.surfaceItemId.ToString());
break;
case "CN":
ToggleTransactionType("AC", allocLine.surfaceItemId.ToString());
break;
}
txtTransactionDate.Value = allocLine.dateOfService.ToString("dd/MM/yyyy");
txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(Math.Abs(allocLine.amount)));
ddPaymentMethod.Focus();
txtReference.Value = allocLine.reference;
rcbSalesContacts.ClearSelection();
rcbSalesContacts.SelectedValue = allocLine.surfaceItemId.ToString();
upTransaction.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myAllocModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "allocPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// PRint a Receipt
///
///
///
private void PrintReceipt(int receiptNo, int surfaceItemId, string noteSurfaceFieldName)
{
try
{
/* CVH 2016-08-17 Print receipt, no modal */
string file = String.Empty;
string path = string.Empty;
DateTime receiptDate = DateTime.Now.Date;
oSales saleReceipt = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,receiptNo,itemType", surfaceItemId.ToString() + "," + receiptNo.ToString() + ",PM"))
{
saleReceipt = sale;
break;
}
if (saleReceipt == null)
throw new Exception("Receipt with number " + receiptNo + " could not be found.");
bool success = xSales.CreateSalesDocument(saleReceipt, ConfigurationManager.AppSettings["WebAddy"], receiptDate, null, null, ref path, ref file, pNums.DocumentType.Receipt, receiptNo.ToString());
if (success)
{
Response.Clear();
//Set the appropriate ContentType.
/* CVH 2016-08-22 Use text/html, otherwise Chrome gives error Resource interpreted as Document but transferred with MIME type application/pdf */
//Response.ContentType = "Application/pdf";
Response.ContentType = "text/html";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file);
Response.TransmitFile(path + file);
Response.Flush();
Response.SuppressContent = true;
ApplicationInstance.CompleteRequest();
//add note
int userId = 0;
if (utils.verifySession("user"))
{
userId = ((oUser)Session["user"]).recId;
}
xSales.AddCreateStatementNote(saleReceipt.surfaceItemId, "Receipt", "A receipt was created.", path, file, userId, noteSurfaceFieldName);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Print an invoice
///
///
///
private void PrintInvoice(int invoiceNo, int surfaceItemId, string noteSurfaceFieldName)
{
try
{
/* CVH 2016-08-17 Print invoice, no modal */
string file = String.Empty;
string path = string.Empty;
DateTime invoiceDate = DateTime.Now.Date;
oSales saleInvoice = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,invoiceNo,itemType", surfaceItemId.ToString() + "," + invoiceNo.ToString() + ",TI"))
{
saleInvoice = sale;
break;
}
if (saleInvoice == null)
throw new Exception("Invoice with number " + invoiceNo + " could not be found.");
bool success = xSales.CreateSalesDocument(saleInvoice, ConfigurationManager.AppSettings["WebAddy"], invoiceDate, null, null, ref path, ref file, pNums.DocumentType.Invoice, invoiceNo.ToString());
if (success)
{
Response.Clear();
//Set the appropriate ContentType.
/* CVH 2016-08-22 Use text/html, otherwise Chrome gives error Resource interpreted as Document but transferred with MIME type application/pdf */
//Response.ContentType = "Application/pdf";
Response.ContentType = "text/html";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file);
Response.TransmitFile(path + file);
Response.Flush();
Response.SuppressContent = true;
ApplicationInstance.CompleteRequest();
//add note
int userId = 0;
if (utils.verifySession("user"))
{
userId = ((oUser)Session["user"]).recId;
}
xSales.AddCreateStatementNote(saleInvoice.surfaceItemId, "Tax Invoice", "A tax invoice was created.", path, file, userId, noteSurfaceFieldName);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Print a Quote
///
///
///
private void PrintQuote(int invoiceNo, int surfaceItemId, string noteSurfaceFieldName)
{
try
{
/* CVH 2016-08-17 Print Quote, no modal */
string file = String.Empty;
string path = string.Empty;
DateTime quoteDate = DateTime.Now.Date;
oSales quoteSale = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,invoiceNo,itemType", surfaceItemId.ToString() + "," + invoiceNo.ToString() + ",QT"))
{
quoteSale = sale;
break;
}
if (quoteSale == null)
throw new Exception("Quote with number " + invoiceNo + " could not be found.");
bool success = xSales.CreateSalesDocument(quoteSale, ConfigurationManager.AppSettings["WebAddy"], quoteDate, null, null, ref path, ref file, pNums.DocumentType.Quote, invoiceNo.ToString());
if (success)
{
Response.Clear();
//Set the appropriate ContentType.
/* CVH 2016-08-22 Use text/html, otherwise Chrome gives error Resource interpreted as Document but transferred with MIME type application/pdf */
Response.ContentType = "text/html";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file);
Response.TransmitFile(path + file);
Response.Flush();
Response.SuppressContent = true;
ApplicationInstance.CompleteRequest();
//add note
int userId = 0;
if (utils.verifySession("user"))
{
userId = ((oUser)Session["user"]).recId;
}
xSales.AddCreateStatementNote(quoteSale.surfaceItemId, "Quote", "A quote was created.", path, file, userId, noteSurfaceFieldName);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#endregion
#region events
#region initialisation events
///
/// Reload Control
///
public void ReloadControl()
{
try
{
oSales acc = null;
SetupControl(acc);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
public void SaveControlData()
{
}
protected void Page_Init(object sender, EventArgs e)
{
//CVH 2016-09-21 Reload user control
if (utils.verifySession("AddItemLoaded") && Session["AddItemLoaded"].ToString() == "true")
{
LoadAddNewItemControl();
}
if (utils.verifySession("AddContactLoaded") && Session["AddContactLoaded"].ToString() == "true")
{
LoadAddNewContactControl();
}
}
///
/// Page Load Event
///
///
///
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
utils.disposeSession("AddItemLoaded");
utils.disposeSession("AddContactLoaded");
oSales acc = new oSales();
/* CVH 2016-08-23 Moving to inside IsPostBack, otherwise it overrides this.Sales with every postback */
if (!utils.verifySession("user"))
{
Response.Redirect("/home", false);
return;
}
else if (utils.verifySession("sales"))
{
/* CVH 2016-08-24 Only use session first time, then remove, otherwise it still causes problems */
acc = (oSales)Session["sales"];
utils.disposeSession("sales");
}
else
{
//CreateTestSales();
}
//CVH 2016-09-21 Remove rad editor buttons
BindEditorButtons(edEmailBody);
BindEditorButtons(edStatementEmailBody);
if (utils.verifySession("referItem"))
{
int itemId = int.Parse(Session["referItem"].ToString());
acc.surfaceItemId = itemId;
utils.disposeSession("referItem");
}
SetupControl(acc);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Setup Control
///
///
private void SetupControl(oSales acc)
{
//clear sessions for billings and payments
Session["transactionLines"] = null;
Session["AllocPayment"] = null;
txtTransactionDate.Disabled = false;
ddPaymentMethod.Enabled = true;
txtPaymentAmount.Disabled = false;
BindSalesToPicklists();
if (acc != null)
{
ddFilterContact.SelectedValue = acc.surfaceItemId.ToString();
rcbSalesContacts.ClearSelection();
rcbSalesContacts.SelectedValue = acc.surfaceItemId.ToString();
/* CVH 2016-08-17 Bind dropdowns before open modal */
//BindInvoicesToPrint(this.Sales.surfaceItemId);
//BindQuotesToPrint(this.Sales);
lnkStatement.Enabled = true;
}
else
lnkStatement.Enabled = false;
BindSalesData();
//bind items
BindItemsNew("", "");
txtTransactionDate.Value = DateTime.Now.ToString("dd/MM/yyyy");
txtTransactionDueDate.Value = DateTime.Now.AddDays(7).ToString("dd/MM/yyyy");
txtTransactionDate.Value = DateTime.Now.ToString("dd/MM/yyyy");
txtStatementDateFrom.Value = DateTime.Now.AddMonths(-3).ToString("dd/MM/yyyy");
txtStatementDateTo.Value = DateTime.Now.ToString("dd/MM/yyyy");
//JR - created table UserAccess to define credit access
if (utils.verifySession("user"))
{
//JR set visibility on actions so users can see their history.
oUser user = (oUser)Session["user"];
if ((user.userType > (int)pNums.UserType.WebsiteUser && user.userType != (int)pNums.UserType.CustomUser)
|| (user.mimicUserType > (int)pNums.UserType.WebsiteUser && user.userType == (int)pNums.UserType.CustomUser))
divActions.Visible = true;
else
divActions.Visible = false;
}
}
#endregion
#region menu events
///
/// Click event to perform a new quote
///
///
///
protected void lnkNewQuote_Click(object sender, EventArgs e)
{
try
{
string surfaceItemId = "";
//CVH 2016-09-16 Sales Contact is loaded on Filter Contact index changed. If filter contact selected, sales contact will be selected, but if no filter contact selected, need to clear selection on sales contact
if (ddFilterContact.SelectedItem != null)
surfaceItemId = ddFilterContact.SelectedItem.Value;
if (surfaceItemId == "0")
surfaceItemId = "";
rcbSalesContacts.Enabled = true;
if (surfaceItemId == "" && rcbSalesContacts.Items.FindItemByValue("0") != null)
{
rcbSalesContacts.ClearSelection();
rcbSalesContacts.Items.FindItemByValue("0").Selected = true;
}
Session["transactionLines"] = new ArrayList();
ToggleTransactionType("QT", surfaceItemId);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myQuoteModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "quotePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Click event to perform a new invoice
///
///
///
protected void lnkNewInvoice_Click(object sender, EventArgs e)
{
try
{
string surfaceItemId = "";
//CVH 2016-09-16 Sales Contact is loaded on Filter Contact index changed. If filter contact selected, sales contact will be selected, but if no filter contact selected, need to clear selection on sales contact
if (ddFilterContact.SelectedItem != null)
surfaceItemId = ddFilterContact.SelectedItem.Value;
if (surfaceItemId == "0")
surfaceItemId = "";
rcbSalesContacts.Enabled = true;
if (surfaceItemId == "" && rcbSalesContacts.Items.FindItemByValue("0") != null)
{
rcbSalesContacts.ClearSelection();
rcbSalesContacts.Items.FindItemByValue("0").Selected = true;
}
Session["transactionLines"] = new ArrayList();
ToggleTransactionType("TI", surfaceItemId);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myinvoiceModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "invoicePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// New Credit Note button
///
///
///
protected void lnkNewCreditNote_Click(object sender, EventArgs e)
{
try
{
string surfaceItemId = "";
//CVH 2016-09-16 Sales Contact is loaded on Filter Contact index changed. If filter contact selected, sales contact will be selected, but if no filter contact selected, need to clear selection on sales contact
if (ddFilterContact.SelectedItem != null)
surfaceItemId = ddFilterContact.SelectedItem.Value;
if (surfaceItemId == "0")
surfaceItemId = "";
rcbSalesContacts.Enabled = true;
if (surfaceItemId == "" && rcbSalesContacts.Items.FindItemByValue("0") != null)
{
rcbSalesContacts.ClearSelection();
rcbSalesContacts.Items.FindItemByValue("0").Selected = true;
}
Session["transactionLines"] = new ArrayList();
ToggleTransactionType("CN", surfaceItemId);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myCreditModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "creditPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// New Receipt
///
///
///
protected void lnkNewReceipt_Click(object sender, EventArgs e)
{
try
{
string surfaceItemId = "";
//CVH 2016-09-16 Sales Contact is loaded on Filter Contact index changed. If filter contact selected, sales contact will be selected, but if no filter contact selected, need to clear selection on sales contact
if (ddFilterContact.SelectedItem != null)
surfaceItemId = ddFilterContact.SelectedItem.Value;
if (surfaceItemId == "0")
surfaceItemId = "";
rcbSalesContacts.Enabled = true;
if (surfaceItemId == "" && rcbSalesContacts.Items.FindItemByValue("0") != null)
{
rcbSalesContacts.ClearSelection();
rcbSalesContacts.Items.FindItemByValue("0").Selected = true;
}
Session["transactionLines"] = new ArrayList();
ToggleTransactionType("PM", surfaceItemId);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myreceiptModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "receiptPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Create a Statement
///
///
///
protected void lnkStatement_Click(object sender, EventArgs e)
{
try
{
string surfaceItemIdTmp = "";
if (ddFilterContact.SelectedItem != null)
surfaceItemIdTmp = ddFilterContact.SelectedItem.Value;
int surfaceItemId = 0;
int.TryParse(surfaceItemIdTmp, out surfaceItemId);
if (ddStatementContacts.Items.FindByValue(surfaceItemId.ToString()) != null)
{
ddStatementContacts.ClearSelection();
ddStatementContacts.Items.FindByValue(surfaceItemId.ToString()).Selected = true;
}
oSales statementSale = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId", surfaceItemId.ToString(), "recId DESC"))
{
statementSale = sale;
break;
}
/* CVH 2016-08-24 Allow blank object, blank statement, but get contact details */
if (statementSale == null && surfaceItemId > 0)
statementSale = xSales.SetSalesContact(surfaceItemId);
lblResultStatement.Text = String.Empty;
pnlResultStatement.Visible = false;
/* CVH 2016-09-02 Load default email subject from company setup */
string subject = "";
oSetup setup = handler.ReturnSetup();
subject = setup.emailSubjectStatement;
if (subject == String.Empty)
subject = "Statement from {Company Name}";
/* CVH 2016-09-13 Add trading as name to company name */
string companyName = setup.customer;
if (setup.tradingAs != String.Empty && !companyName.Contains(" t/a "))
companyName += " t/a " + setup.tradingAs;
subject = subject.Replace("{Company Name}", companyName);
if (subject == String.Empty)
subject = "Statement";
/* CVH 2016-09-02 Load email template for user to edit before sending */
edStatementEmailBody.Content = String.Empty;
foreach (oTemplate template in xData.GetTypedByCriteriaSpecific("recId", typeof(oTemplate), "templateName", "Sales Statement E-mail Template"))
{
edStatementEmailBody.Content = xSales.BuildEmailTemplate(template.templateContent, statementSale, setup, ConfigurationManager.AppSettings["WebAddy"]);
break;
}
string to = "";
string cc = ConfigurationManager.AppSettings["admin"];
string bcc = ConfigurationManager.AppSettings["bcc"];
if (statementSale != null)
{
to = statementSale.email;
if (cc == String.Empty)
cc = statementSale.emailCC;
else
cc += ";" + statementSale.emailCC;
}
/* CVH 2016-08-17 Load email settings */
txtStatementEmailSubject.Value = subject;
txtStatementEmailTo.Value = to;
txtStatementEmailCc.Value = cc;
txtStatementEmailBcc.Value = bcc;
/* CVH 2016-09-02 Set visibility based on selected action */
rblStatementAction.SelectedValue = "Print";
pnlEmailStatement.Visible = false;
btnEmailStatement.Visible = false;
btnCreateStatement.Visible = true;
upStatement.Update();
ViewState["SendStatement"] = statementSale;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myStatementModal", "$('#modStatement').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "statementPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region sales events
///
/// Filter Type Seelction Index Changed
///
///
///
protected void ddFilterType_SelectedIndexChanged(object sender, EventArgs e)
{
PopulateStatuses();
}
///
/// Filter Click event
///
///
///
protected void btnFilter_Click(object sender, EventArgs e)
{
try
{
BindSalesData();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Toggle To Sales History
///
///
///
protected void lnkToggleFinancial_Click(object sender, EventArgs e)
{
try
{
//pnlFinancial.Visible = true;
//pnlActivity.Visible = false;
int mode = 0;//activity view
if (utils.verifySession("mode"))
mode = int.Parse(Session["mode"].ToString());
ddFilterType.Items.Clear();
ddFilterType.Items.Add(new ListItem("Credit Note", "CN"));
ddFilterType.Items.Add(new ListItem("Invoice", "TI"));
if (mode == 0)//changing to fincancial view
{
mode = 1;
lnkNewQuote.Visible = false;
quotesSummary.Visible = false;
//set title/button to "Toggle to Activity View"
}
else//changing to activity view
{
lnkNewQuote.Visible = false;
quotesSummary.Visible = true;
ddFilterType.Items.Add(new ListItem("Quote", "QT"));
mode = 0;
//set title/button to "Toggle to Financial View"
}
ddFilterType.Items.Add(new ListItem("Receipt", "PM"));
Session["mode"] = mode;
BindSalesData();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Item Data Bound
///
///
///
protected void rptActivity_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
HiddenField hfType = e.Item.FindControl("hfType") as HiddenField;
if (hfType != null)
{
HiddenField hfAllocated = e.Item.FindControl("hfAllocated") as HiddenField;
HiddenField hfReceipt = e.Item.FindControl("hfReceipt") as HiddenField;
HiddenField hfStatus = e.Item.FindControl("hfStatus") as HiddenField;
HiddenField hfEmailSent = e.Item.FindControl("hfEmailSent") as HiddenField;
//option links
LinkButton btnAccept = (LinkButton)e.Item.FindControl("btnAccept");
LinkButton btnAcceptAndInvoice = (LinkButton)e.Item.FindControl("btnAcceptAndInvoice");
LinkButton btnCreateInvoiceFromQuote = (LinkButton)e.Item.FindControl("btnCreateInvoiceFromQuote");
LinkButton btnDecline = (LinkButton)e.Item.FindControl("btnDecline");
LinkButton btnAddReceipt = (LinkButton)e.Item.FindControl("btnAddReceipt");
LinkButton btnAllocate = (LinkButton)e.Item.FindControl("btnAllocate");
LinkButton btnUnAllocate = (LinkButton)e.Item.FindControl("btnUnAllocate");
LinkButton btnSend = (LinkButton)e.Item.FindControl("btnSend");
LinkButton btnPrint = (LinkButton)e.Item.FindControl("btnPrint");
LinkButton btnView = (LinkButton)e.Item.FindControl("btnView");
LinkButton btnEdit = (LinkButton)e.Item.FindControl("btnEdit");
LinkButton btnCopy = (LinkButton)e.Item.FindControl("btnCopy");
LinkButton btnOptions = (LinkButton)e.Item.FindControl("btnOptions");
Label lblActivityType = (Label)e.Item.FindControl("lblActivityType");
Label lblQuoted = (Label)e.Item.FindControl("lblQuoted");
Label lblReceived = (Label)e.Item.FindControl("lblReceived");
Label lblInvoiced = (Label)e.Item.FindControl("lblInvoiced");
Label lblAmount = (Label)e.Item.FindControl("lblAmount");
Label lblSentStatus = (Label)e.Item.FindControl("lblSentStatus");
Label lblDue = (Label)e.Item.FindControl("lblDue");
decimal quoted = 0;
decimal.TryParse(lblQuoted.Text, out quoted);
decimal received = 0;
decimal.TryParse(lblReceived.Text, out received);
decimal invoiced = 0;
decimal.TryParse(lblInvoiced.Text, out invoiced);
decimal amount = 0;
decimal.TryParse(lblAmount.Text, out amount);
decimal allocated = 0;
decimal.TryParse(hfAllocated.Value, out allocated);
int receiptNo = 0;
int.TryParse(hfReceipt.Value, out receiptNo);
ScriptManager sm = ScriptManager.GetCurrent(this.Parent.Page);
if (sm != null)
{
sm.RegisterPostBackControl(btnPrint);
}
//handle emsil sent status
if (hfEmailSent.Value == "True")
{
lblSentStatus.CssClass = "alert-success";
lblSentStatus.Text = "(Sent)";
}
else
{
lblSentStatus.CssClass = "alert-warning";
lblSentStatus.Text = "(Unsent)";
}
switch (hfType.Value)
{
case "QT":
btnOptions.CssClass = "dropdown-toggle palette-btn-blue";
btnOptions.Text = "Q";
if (allocated != quoted)
{ lblDue.ForeColor = System.Drawing.Color.Red; }
lblActivityType.Text = "Quote";
btnCopy.Visible = true;
switch (hfStatus.Value)
{
case "Draft":
lblSentStatus.Visible = false;
break;
case "Pending":
btnDecline.Visible = true;
break;
case "Declined":
btnAccept.Visible = true;
if (allocated != quoted)
btnAcceptAndInvoice.Visible = true;
btnDecline.Visible = false;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
case "Accepted":
if (allocated != quoted)
btnCreateInvoiceFromQuote.Visible = true;
btnDecline.Visible = true;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
default:
break;
}
break;
case "TI":
btnOptions.CssClass = "dropdown-toggle palette-btn-dark-blue";
btnOptions.Text = "I";
if (allocated != invoiced)
{
if (allocated > 0)
lblDue.ForeColor = System.Drawing.Color.Orange;
else
lblDue.ForeColor = System.Drawing.Color.Red;
}
lblActivityType.Text = "Invoice";
btnCopy.Visible = true;
switch (hfStatus.Value)
{
case "Draft":
break;
case "Unpaid":
case "Partially Paid":
case "Overdue":
btnAddReceipt.Visible = true;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
case "Paid":
btnSend.Visible = true;
btnPrint.Visible = true;
break;
default:
break;
}
break;
case "PM":
btnOptions.CssClass = "dropdown-toggle palette-btn-green";
btnOptions.Text = "R";
if (allocated == 0)
{ lblDue.ForeColor = System.Drawing.Color.Red; }
else if (allocated != received)
lblDue.ForeColor = System.Drawing.Color.Orange;
lblActivityType.Text = "Receipt";
switch (hfStatus.Value)
{
case "Draft":
break;
case "Unallocated":
btnAllocate.Visible = true;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
case "Partially Allocated":
btnAllocate.Visible = true;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
case "Allocated":
btnUnAllocate.Visible = true;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
default:
break;
}
break;
case "CN":
btnOptions.CssClass = "dropdown-toggle palette-btn-orange";
btnOptions.Text = "C";
if (allocated == 0)
{ lblDue.ForeColor = System.Drawing.Color.Red; }
else if (allocated != received)
lblDue.ForeColor = System.Drawing.Color.Orange;
lblActivityType.Text = "Credit Note";
switch (hfStatus.Value)
{
case "Draft":
break;
case "Unallocated":
btnAllocate.Visible = true;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
case "Partially Allocated":
btnAllocate.Visible = true;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
case "Allocated":
btnUnAllocate.Visible = true;
btnSend.Visible = true;
btnPrint.Visible = true;
break;
default:
break;
}
break;
case "PR":
btnOptions.CssClass = "dropdown-toggle palette-btn-red";
btnOptions.Text = "R";
lblActivityType.Text = "Reversal";
break;
default:
break;
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
/////
///// Create the invocie for print
/////
/////
/////
//protected void lnkCreateInvoice_Click(object sender, EventArgs e)
//{
// try
// {
// /* CVH 2016-08-17 Print invoice, no modal */
// string file = String.Empty;
// string path = string.Empty;
// DateTime invoiceDate = DateTime.Now.Date;
// string invoiceNo = ((LinkButton)sender).CommandArgument;
// oSales saleInvoice = null;
// foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "invoiceNo,itemType", invoiceNo + ",TI"))
// {
// saleInvoice = sale;
// break;
// }
// if (saleInvoice == null)
// throw new Exception("Invoice with number " + invoiceNo + " could not be found.");
// bool success = xSales.CreateSalesDocument(saleInvoice, ConfigurationManager.AppSettings["WebAddy"], invoiceDate, null, null, ref path, ref file, pNums.DocumentType.Invoice, invoiceNo);
// if (success)
// {
// Response.Clear();
// //Set the appropriate ContentType.
// /* CVH 2016-08-22 Use text/html, otherwise Chrome gives error Resource interpreted as Document but transferred with MIME type application/pdf */
// //Response.ContentType = "Application/pdf";
// Response.ContentType = "text/html";
// Response.AppendHeader("Content-Disposition", "attachment; filename=" + file);
// Response.TransmitFile(path + file);
// Response.Flush();
// Response.SuppressContent = true;
// ApplicationInstance.CompleteRequest();
// //add note
// int userId = 0;
// if (utils.verifySession("user"))
// {
// userId = ((oUser)Session["user"]).recId;
// }
// xSales.AddCreateStatementNote(saleInvoice.surfaceItemId, "Tax Invoice", "A tax invoice was created.", path, file, userId);
// }
// }
// catch (Exception ex)
// {
// exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
// Response.Redirect("/error", false);
// }
//}
/////
///// Create the Credit Note for Print
/////
/////
/////
//protected void lnkCreateCreditNote_Click(object sender, EventArgs e)
//{
//}
/////
///// Create the receipt for print
/////
/////
/////
//protected void lnkCreateReceipt_Click(object sender, EventArgs e)
//{
// try
// {
// int receiptNo = int.Parse(((LinkButton)sender).CommandArgument);
// /* CVH 2016-08-17 Print receipt, no modal */
// string file = String.Empty;
// string path = string.Empty;
// DateTime receiptDate = DateTime.Now.Date;
// oSales saleReceipt = null;
// foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "receiptNo,itemType", receiptNo + ",PM"))
// {
// saleReceipt = sale;
// break;
// }
// if (saleReceipt == null)
// throw new Exception("Receipt with number " + receiptNo + " could not be found.");
// bool success = xSales.CreateSalesDocument(saleReceipt, ConfigurationManager.AppSettings["WebAddy"], receiptDate, null, null, ref path, ref file, pNums.DocumentType.Receipt, receiptNo.ToString());
// if (success)
// {
// Response.Clear();
// //Set the appropriate ContentType.
// /* CVH 2016-08-22 Use text/html, otherwise Chrome gives error Resource interpreted as Document but transferred with MIME type application/pdf */
// //Response.ContentType = "Application/pdf";
// Response.ContentType = "text/html";
// Response.AppendHeader("Content-Disposition", "attachment; filename=" + file);
// Response.TransmitFile(path + file);
// Response.Flush();
// Response.SuppressContent = true;
// ApplicationInstance.CompleteRequest();
// //add note
// if (saleReceipt != null)
// {
// int userId = 0;
// if (utils.verifySession("user"))
// {
// userId = ((oUser)Session["user"]).recId;
// }
// xSales.AddCreateStatementNote(saleReceipt.surfaceItemId, "Receipt", "A receipt was created.", path, file, userId);
// }
// }
// }
// catch (Exception ex)
// {
// exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
// Response.Redirect("/error", false);
// }
//}
/////
///// Create Quote Click
/////
/////
/////
//protected void lnkCreateQuote_Click(object sender, EventArgs e)
//{
// try
// {
// /* CVH 2016-08-17 Print Quote, no modal */
// string file = String.Empty;
// string path = string.Empty;
// DateTime quoteDate = DateTime.Now.Date;
// string quoteNo = ((LinkButton)sender).CommandArgument;
// oSales quoteSale = null;
// foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "invoiceNo,itemType", quoteNo + ",QT"))
// {
// quoteSale = sale;
// break;
// }
// if (quoteSale == null)
// throw new Exception("Quote with number " + quoteNo + " could not be found.");
// bool success = xSales.CreateSalesDocument(quoteSale, ConfigurationManager.AppSettings["WebAddy"], quoteDate, null, null, ref path, ref file, pNums.DocumentType.Quote, quoteNo);
// if (success)
// {
// Response.Clear();
// //Set the appropriate ContentType.
// /* CVH 2016-08-22 Use text/html, otherwise Chrome gives error Resource interpreted as Document but transferred with MIME type application/pdf */
// //Response.ContentType = "Application/pdf";
// Response.ContentType = "text/html";
// Response.AppendHeader("Content-Disposition", "attachment; filename=" + file);
// Response.TransmitFile(path + file);
// Response.Flush();
// Response.SuppressContent = true;
// ApplicationInstance.CompleteRequest();
// //add note
// int userId = 0;
// if (utils.verifySession("user"))
// {
// userId = ((oUser)Session["user"]).recId;
// }
// xSales.AddCreateStatementNote(quoteSale.surfaceItemId, "Quote", "A quote was created.", path, file, userId);
// }
// }
// catch (Exception ex)
// {
// exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
// Response.Redirect("/error", false);
// }
//}
///
/// Allocate the Receipt
///
///
///
protected void lnkAllocateReceipt_Click(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkRemove = (LinkButton)sender;
int recNo = int.Parse(lnkRemove.CommandArgument);
foreach (oSales payLine in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "receiptNo", recNo.ToString()))
{
Session["AllocPayment"] = payLine;
//CVH 2016-09-14 Build transaction number with padded 0's
txtNumber.Value = xSales.BuildNextTransactionNumber(handler.ReturnSetup().saleRCTPrefix, handler.ReturnSetup().saleRCTNumLength, recNo);
txtTransactionDate.Value = payLine.dateOfService.ToString("dd/MM/yyyy");
txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(Math.Abs(payLine.amount)));
ddPaymentMethod.Focus();
ToggleTransactionType("A", payLine.surfaceItemId.ToString());
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myAllocModal", "$('#modTransaction').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "allocPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Reverse the Receipt
///
///
///
protected void lnkReverseReceipt_Click(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkRemove = (LinkButton)sender;
int recNo = int.Parse(lnkRemove.CommandArgument);
foreach (oSales payAcc in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "receiptNo", recNo.ToString()))
{
if (payAcc.amount < 0 && payAcc.isVisible && (payAcc.itemType == "PM"))
{
if (payAcc.allocatedReference != String.Empty)
{
//then we need to undo these allocations
string[] allocBillingIds = payAcc.allocatedReference.Split(char.Parse(","));
decimal amountAllocated = Math.Abs(payAcc.amount);
foreach (string sId in allocBillingIds)
{
int billId = 0;
if (sId.Contains(":"))
{ int.TryParse(sId.Substring(0, sId.IndexOf(":")), out billId); }
else
{ int.TryParse(sId, out billId); }
foreach (oSales billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", billId.ToString()))
{
string[] references = billing.allocatedReference.Split(char.Parse(","));
string adjustedReferences = String.Empty;
foreach (string sref in references)
{
if (sref.Contains(":"))
{
int payId = int.Parse(sref.Substring(0, sref.IndexOf(":")));
if (payId == payAcc.recId)
{
decimal amount = Convert.ToDecimal(sref.Substring(sref.IndexOf(":") + 1));
amountAllocated -= amount;
billing.allocated -= amount;
}
else
{
if (adjustedReferences == String.Empty)
{ adjustedReferences = sref; }
else
{ adjustedReferences += "," + sref; }
}
}
}
billing.allocatedReference = adjustedReferences;
//update alloc reference on billing line
if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oSales), billing))
{ }
}
}
}
oSales reversal = (oSales)utils.CloneObject(payAcc);
//set the reverse
reversal.recId = 0;
reversal.amount = reversal.amount * -1;
reversal.itemType = "PR";
reversal.dateOfCapture = DateTime.Now;
reversal.itemDescription = "Payment Reversal";
reversal.isVisible = false;
reversal.userId = payAcc.userId;
reversal.receiptNo = xData.GetNextRecNoSales();
reversal.allocated = reversal.amount * -1;
//CVH 2016-09-15 Don't include Prefix, only save number
reversal.allocatedReference = payAcc.receiptNo.ToString();
reversal.recId = xData.SaveTyped("recId", typeof(oSales), reversal);
if (reversal.recId > 0)
{
//update payment to hidden too
payAcc.isVisible = false;
payAcc.allocatedReference = reversal.recId.ToString();
if (xData.UpdateTyped("recId", payAcc.recId.ToString(), typeof(oSales), payAcc))
{
pnlResult.Visible = true;
lblResult.Text = "The Reversal was successfully applied.";
BindSalesData();
upSales.Update();
}
}
//CVH 2016-09-14 Update Next Transaction number in company setup. Get current db setup
oSetup setupUpdate = handler.ReturnSetup();
setupUpdate = (oSetup)(xData.GetTypedByCriteriaSpecific("recId", typeof(oSetup), "isActive", "1")[0]);
setupUpdate.saleRCTNextNum = xData.GetNextRecNoSales();
xData.UpdateTyped("recId", setupUpdate.recId.ToString(), typeof(oSetup), setupUpdate);
}
else
{
pnlResult.Visible = true;
lblResult.Text = "A Reversal could not be applied. It could be zero amount or the line has already been reversed.";
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Selected Index Changed event
///
///
///
protected void ddFilterContact_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (ddFilterContact.SelectedValue != null && ddFilterContact.SelectedValue != String.Empty)
{
int surfaceItemId = 0;
int.TryParse(ddFilterContact.SelectedValue, out surfaceItemId);
if (surfaceItemId > 0)
{
rcbSalesContacts.ClearSelection();
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
BindSalesData();
ToggleTransactionType(ddTransactionType.SelectedValue, surfaceItemId.ToString());
/* CVH 2016-08-17 Bind dropdowns before open modal */
//BindInvoicesToPrint(this.Sales.surfaceItemId);
//BindQuotesToPrint(this.Sales);
upTransaction.Update();
lnkStatement.Enabled = true;
upSales.Update();
}
else
{
rcbSalesContacts.ClearSelection();
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
lnkStatement.Enabled = false;
BindSalesData();
ToggleTransactionType(ddTransactionType.SelectedValue, "");
upTransaction.Update();
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region action events
///
/// Accept Click Event
///
///
///
protected void btnAccept_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
AcceptQuote(invoiceNo, surfaceItemId);
break;
default:
break;
}
BindSalesData();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Accept and invocie event
///
///
///
protected void btnAcceptAndInvoice_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
AcceptQuoteAndInvoice(invoiceNo, surfaceItemId);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Decline Click event
///
///
///
protected void btnDecline_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
DeclineQuote(invoiceNo, surfaceItemId);
break;
default:
break;
}
BindSalesData();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Add Receipt Event Click
///
///
///
protected void btnAddReceipt_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "TI":
rcbSalesContacts.ClearSelection();
rcbSalesContacts.SelectedValue = surfaceItemId.ToString();
AddReceipt(invoiceNo, surfaceItemId);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Add Credit Note Event Click
///
///
///
protected void btnAddCreditNote_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "TI":
AddCreditNote(invoiceNo, surfaceItemId);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Allocate a Receipt / Credit Note
///
///
///
protected void btnAllocate_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
AllocateLine(surfaceItemId, itemType, receiptNo, invoiceNo);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Unallocate
///
///
///
protected void btnUnAllocate_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "PM":
UnAllocateReceipt(receiptNo, surfaceItemId);
break;
case "CN":
UnAllocateCreditNote(invoiceNo, surfaceItemId);
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Email a Document
///
///
///
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
SendQuote(invoiceNo, surfaceItemId);
break;
case "TI":
SendInvoice(invoiceNo, surfaceItemId);
break;
case "PM":
SendReceipt(receiptNo, surfaceItemId);
break;
case "CN":
SendCreditNote(invoiceNo, surfaceItemId);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Save a Transaction and Email
///
///
///
protected void btnSaveSend_Click(object sender, EventArgs e)
{
try
{
btnFinaliseBill_Click(sender, e);
int surfaceItemId = 0;
int.TryParse(rcbSalesContacts.SelectedValue, out surfaceItemId);
int number = 0;
if (ViewState["num"] != null)
{
number = int.Parse(ViewState["num"].ToString());
}
if (number > 0 && surfaceItemId > 0)
{
switch (ddTransactionType.SelectedValue)
{
case "QT":
SendQuote(number, surfaceItemId);
break;
case "TI":
SendInvoice(number, surfaceItemId);
break;
case "PM":
SendReceipt(number, surfaceItemId);
break;
case "CN":
SendCreditNote(number, surfaceItemId);
break;
default:
break;
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Remove invoice Receipts
///
///
///
protected void btnViewRemoveReceipt_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "TI":
RemoveInvoiceReceipts(invoiceNo, surfaceItemId);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// View Transaction
///
///
///
protected void btnView_Click(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(button, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
btnViewAccept.Visible = false;
btnViewAcceptAndInvoice.Visible = false;
btnViewCreateInvoiceFromQuote.Visible = false;
btnViewDecline.Visible = false;
btnViewAddReceipt.Visible = false;
btnViewAllocate.Visible = false;
btnViewUnAllocate.Visible = false;
btnViewSend.Visible = false;
btnViewEdit.Visible = true;
btnViewPrint.Visible = false;
btnViewCopy.Visible = false;
btnViewRemoveReceipt.Visible = false;
btnViewAddCreditNote.Visible = false;
btnViewRemoveCreditNote.Visible = false;
btnViewDelete.Visible = true;
btnViewAccept.CommandArgument = button.CommandArgument;
btnViewAcceptAndInvoice.CommandArgument = button.CommandArgument;
btnViewCreateInvoiceFromQuote.CommandArgument = button.CommandArgument;
btnViewDecline.CommandArgument = button.CommandArgument;
btnViewAddReceipt.CommandArgument = button.CommandArgument;
btnViewAllocate.CommandArgument = button.CommandArgument;
btnViewUnAllocate.CommandArgument = button.CommandArgument;
btnViewSend.CommandArgument = button.CommandArgument;
btnViewEdit.CommandArgument = button.CommandArgument;
btnViewPrint.CommandArgument = button.CommandArgument;
btnViewCopy.CommandArgument = button.CommandArgument;
btnViewRemoveReceipt.CommandArgument = button.CommandArgument;
btnViewAddCreditNote.CommandArgument = button.CommandArgument;
btnViewRemoveCreditNote.CommandArgument = button.CommandArgument;
btnViewDelete.CommandArgument = button.CommandArgument;
string status = "";
if (button.Parent.GetType() == typeof(RepeaterItem))
{
RepeaterItem item = (RepeaterItem)(button).Parent;
HiddenField hfStatus = (HiddenField)item.FindControl("hfStatus");
if (hfStatus != null)
status = hfStatus.Value;
}
switch (itemType)
{
case "QT":
btnViewCopy.Visible = true;
switch (status)
{
case "Draft":
break;
case "Pending":
btnViewAccept.Visible = true;
btnViewAcceptAndInvoice.Visible = true;
btnViewDecline.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
case "Declined":
btnViewAccept.Visible = true;
btnViewAcceptAndInvoice.Visible = true;
btnViewDecline.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
case "Accepted":
btnViewCreateInvoiceFromQuote.Visible = true;
btnViewDecline.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
default:
break;
}
SetQuoteView(invoiceNo, surfaceItemId);
break;
case "TI":
btnViewCopy.Visible = true;
switch (status)
{
case "Draft":
break;
case "Unpaid":
btnViewAddReceipt.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
btnViewCopy.Visible = true;
btnViewAddCreditNote.Visible = true;
break;
case "Partially Paid":
case "Overdue":
btnViewAddReceipt.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
btnViewCopy.Visible = true;
btnViewRemoveReceipt.Visible = true;
btnViewAddCreditNote.Visible = true;
btnViewRemoveCreditNote.Visible = true;
break;
case "Paid":
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
btnViewCopy.Visible = true;
btnViewRemoveReceipt.Visible = true;
btnViewRemoveCreditNote.Visible = true;
break;
default:
break;
}
SetInvoiceView(invoiceNo, surfaceItemId);
break;
case "PM":
switch (status)
{
case "Draft":
break;
case "Unallocated":
btnViewAllocate.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
case "Partially Allocated":
btnViewAllocate.Visible = true;
btnViewUnAllocate.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
case "Allocated":
btnViewUnAllocate.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
default:
break;
}
SetReceiptView(receiptNo, surfaceItemId);
break;
case "CN":
switch (status)
{
case "Draft":
break;
case "Unallocated":
btnViewAllocate.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
case "Partially Allocated":
btnViewAllocate.Visible = true;
btnViewUnAllocate.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
case "Allocated":
btnViewUnAllocate.Visible = true;
btnViewSend.Visible = true;
btnViewPrint.Visible = true;
break;
default:
break;
}
SetCreditNoteView(invoiceNo, surfaceItemId);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Edit Click
///
///
///
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
SetQuoteEdit(invoiceNo, surfaceItemId);
PopulateExtraNote(pNums.DocumentType.Quote.GetHashCode(), invoiceNo);
break;
case "TI":
SetInvoiceEdit(invoiceNo, surfaceItemId);
PopulateExtraNote(pNums.DocumentType.Invoice.GetHashCode(), invoiceNo);
break;
case "PM":
SetReceiptEdit(receiptNo, surfaceItemId);
PopulateExtraNote(pNums.DocumentType.Receipt.GetHashCode(), receiptNo);
break;
case "CN":
SetCreditNoteEdit(invoiceNo, surfaceItemId);
PopulateExtraNote(pNums.DocumentType.CreditNote.GetHashCode(), invoiceNo);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Delete Click Event
///
///
///
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
DeleteQuote(invoiceNo, surfaceItemId);
break;
case "TI":
Deleteinvoice(invoiceNo, surfaceItemId);
break;
case "PM":
DeleteReceipt(receiptNo, surfaceItemId);
break;
case "CN":
DeleteCreditNote(invoiceNo, surfaceItemId);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Print Click event
///
///
///
protected void btnPrint_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
PrintQuote(invoiceNo, surfaceItemId, this.NotesFieldName);
break;
case "TI":
PrintInvoice(invoiceNo, surfaceItemId, this.NotesFieldName);
break;
case "PM":
PrintReceipt(receiptNo, surfaceItemId, this.NotesFieldName);
break;
case "CN":
PrintCreditNote(invoiceNo, surfaceItemId, this.NotesFieldName);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Copy Click Event
///
///
///
protected void btnCopy_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
SetQuoteCopy(invoiceNo, surfaceItemId);
break;
case "TI":
SetInvoiceCopy(invoiceNo, surfaceItemId);
break;
case "PM":
break;
case "CN":
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Create invoice Click
///
///
///
protected void btnCreateInvoiceFromQuote_Click(object sender, EventArgs e)
{
try
{
string itemType;
int surfaceItemId, invoiceNo, receiptNo;
GetParamValues(sender, out itemType, out surfaceItemId, out invoiceNo, out receiptNo);
switch (itemType)
{
case "QT":
AcceptQuoteAndInvoice(invoiceNo, surfaceItemId);
break;
default:
break;
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region transaction modal events
///
/// Selected Index Changed event
///
///
///
protected void ddTransactionType_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string surfaceItemId = "";
if (ddFilterContact.SelectedItem != null)
surfaceItemId = ddFilterContact.SelectedItem.Value;
if (surfaceItemId == "0")
surfaceItemId = "";
ToggleTransactionType(ddTransactionType.SelectedValue, surfaceItemId);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Contacts Selected index changed
///
///
///
protected void rcbSalesContacts_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
utils.disposeSession("AddContactLoaded");
if (rcbSalesContacts.SelectedValue != null && rcbSalesContacts.SelectedValue != String.Empty)
{
int surfaceItemId = 0;
int.TryParse(rcbSalesContacts.SelectedValue, out surfaceItemId);
if (surfaceItemId > 0)
{
ToggleTransactionType(ddTransactionType.SelectedValue, surfaceItemId.ToString());
BindSalesData();
/* CVH 2016-08-17 Bind dropdowns before open modal */
//BindInvoicesToPrint(this.Sales.surfaceItemId);
//BindQuotesToPrint(this.Sales);
upTransaction.Update();
upSales.Update();
}
else
{
//CVH 2016-09-16 If no contact selected, disable related to
switch (ddTransactionType.SelectedValue)
{
case "TI"://invoice
ddRelatedTo.Visible = true;
ddRelatedTo.Enabled = false;
lstRelatedTo.Visible = false;
lstRelatedToEmpty.Visible = false;
break;
default:
ddRelatedTo.Visible = false;
lstRelatedTo.Visible = false;
lstRelatedToEmpty.Visible = true;
break;
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Item Data Bound Event
///
///
///
protected void rptBillingAccounts_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
/* CVH 2016-08-26 Hide entire columns */
HtmlTableCell tdBillingAccountsEdit = (HtmlTableCell)e.Item.FindControl("tdBillingAccountsEdit");
HtmlTableCell tdBillingAccountsDelete = (HtmlTableCell)e.Item.FindControl("tdBillingAccountsDelete");
//LinkButton lnkEdit = (LinkButton)e.Item.FindControl("lnkEdit");
if (tdBillingAccountsEdit != null && tdBillingAccountsDelete != null)
{
switch (ddTransactionType.SelectedValue)
{
case "TI":
tdBillingAccountsEdit.Visible = true;
tdBillingAccountsDelete.Visible = true;
break;
case "QT":
tdBillingAccountsEdit.Visible = true;
tdBillingAccountsDelete.Visible = true;
break;
case "CN":
tdBillingAccountsEdit.Visible = false;
tdBillingAccountsDelete.Visible = true;
break;
case "PM":
tdBillingAccountsEdit.Visible = false;
tdBillingAccountsDelete.Visible = true;
break;
case "A":
tdBillingAccountsEdit.Visible = false;
tdBillingAccountsDelete.Visible = true;
break;
default:
tdBillingAccountsEdit.Visible = true;
tdBillingAccountsDelete.Visible = true;
break;
}
}
//handle amount to display as exclusive
HiddenField hfVatRate = (HiddenField)e.Item.FindControl("hfVatRate");
if (hfVatRate != null)
{
decimal vatRate = 0;
decimal.TryParse(hfVatRate.Value.ToString(), out vatRate);
if (vatRate > 0)
{
Label lblUnitFee = (Label)e.Item.FindControl("lblUnitFee");
Label lblAmount = (Label)e.Item.FindControl("lblAmount");
decimal unitFee = 0;
decimal.TryParse(lblUnitFee.Text, out unitFee);
decimal amount = 0;
decimal.TryParse(lblAmount.Text, out amount);
if (unitFee > 0 && amount > 0)
{
lblUnitFee.Text = utils.returnFormattedDecimal(Convert.ToString((100.00m / (100.00m + vatRate)) * unitFee));
lblAmount.Text = utils.returnFormattedDecimal(Convert.ToString((100.00m / (100.00m + vatRate)) * amount));
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Item Data bound event for the invoice lines for receipting and allocation
///
///
///
protected void rptInvoiceLines_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
HiddenField hfType = e.Item.FindControl("hfType") as HiddenField;
if (hfType != null)
{
HiddenField hfAllocated = e.Item.FindControl("hfAllocated") as HiddenField;
HiddenField hfReceipt = e.Item.FindControl("hfReceipt") as HiddenField;
HiddenField hfStatus = e.Item.FindControl("hfStatus") as HiddenField;
HiddenField hfEmailSent = e.Item.FindControl("hfEmailSent") as HiddenField;
TextBox txbAllocateAmount = e.Item.FindControl("txbAllocateAmount") as TextBox;
Label lblAmount = (Label)e.Item.FindControl("lblAmount");
Label lblSentStatus = (Label)e.Item.FindControl("lblSentStatus");
Label lblDue = (Label)e.Item.FindControl("lblDue");
decimal amount = 0;
decimal.TryParse(lblAmount.Text, out amount);
decimal due = 0;
decimal.TryParse(lblDue.Text, out due);
//txtAllocateAmount.Value = utils.returnFormattedDecimal(Convert.ToString(due));
decimal allocated = 0;
decimal.TryParse(hfAllocated.Value, out allocated);
int receiptNo = 0;
int.TryParse(hfReceipt.Value, out receiptNo);
//handle emsil sent status
if (hfEmailSent.Value == "True")
{
lblSentStatus.CssClass = "alert-success";
lblSentStatus.Text = "(Sent)";
}
else
{
lblSentStatus.CssClass = "alert-warning";
lblSentStatus.Text = "(Unsent)";
}
switch (hfType.Value)
{
case "TI":
switch (hfStatus.Value)
{
case "Draft":
break;
case "Unpaid":
case "Partially Paid":
case "Overdue":
break;
case "Paid":
break;
default:
break;
}
break;
default:
break;
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Item Databound for view
///
///
///
protected void rptViewTransactionLines_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
HiddenField hfVatRate = (HiddenField)e.Item.FindControl("hfVatRate");
if (hfVatRate != null)
{
decimal vatRate = 0;
decimal.TryParse(hfVatRate.Value.ToString(), out vatRate);
if (vatRate > 0)
{
Label lblUnitFee = (Label)e.Item.FindControl("lblViewUnitFee");
Label lblAmount = (Label)e.Item.FindControl("lblViewAmount");
decimal unitFee = 0;
decimal.TryParse(lblUnitFee.Text, out unitFee);
decimal amount = 0;
decimal.TryParse(lblAmount.Text, out amount);
if (unitFee > 0 && amount > 0)
{
lblUnitFee.Text = utils.returnFormattedDecimal(Convert.ToString((100.00m / (100.00m + vatRate)) * unitFee));
lblAmount.Text = utils.returnFormattedDecimal(Convert.ToString((100.00m / (100.00m + vatRate)) * amount));
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// uinit price Text changed event
///
///
///
protected void txtBillingUnitPrice_TextChanged(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(TextBox))
{
TextBox unitFee = (TextBox)sender;
switch (unitFee.ID)
{
case "txtEditLineUnitPrice":
CalculateAmountEditLine(false);
break;
default:
CalculateAmount(false);
break;
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Qty Text Changed Event
///
///
///
protected void txtBillingQty_TextChanged(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(TextBox))
{
TextBox qty = (TextBox)sender;
switch (qty.ID)
{
case "txtEditLineQty":
CalculateAmountEditLine(false);
break;
default:
CalculateAmount(false);
break;
}
upTransaction.Update();
}
}
catch (Exception ex)
{
exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Description Selection Changed event
///
///
///
protected void rcbDescription_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string code = "";
string id = "";
utils.disposeSession("AddItemLoaded");
if (sender.GetType() == typeof(RadComboBox))
{
RadComboBox dd = (RadComboBox)sender;
code = dd.SelectedValue;
id = dd.ID;
//CVH 2016-09-15 Only process items not deleted
foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code,isDeleted", code + ",0"))
{
switch (id)
{
case "rcbEditLineDescription":
CalculateAmountEditLine(true);
txtEditLineCode.Text = item.code;
txtEditDetails.Text = item.code + " - " + item.description;
if (item.comments != String.Empty)
txtEditDetails.Text += " - " + item.comments;
break;
default:
txtBillingCode.Text = item.code;
CalculateAmount(true);
txtDetails.Text = item.code + " - " + item.description;
if (item.comments != String.Empty)
txtDetails.Text += " - " + item.comments;
break;
}
break;
}
}
}
catch (Exception ex)
{
exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// remove billing line in posting session
///
///
///
protected void lnkRemoveBilling_Click(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkRemoveBilling = (LinkButton)sender;
string recId = lnkRemoveBilling.CommandArgument;
if (recId == "0")
{
if (utils.verifySession("transactionLines"))
{
ArrayList currentBillings = (ArrayList)Session["transactionLines"];
if (currentBillings != null && currentBillings.Count > 0)
{
if (lnkRemoveBilling.Parent.Parent.GetType() == typeof(RepeaterItem))
{
RepeaterItem item = (RepeaterItem)(lnkRemoveBilling).Parent.Parent;
if (currentBillings.Count > item.ItemIndex)
currentBillings.RemoveAt(item.ItemIndex);
Session["transactionLines"] = currentBillings;
}
}
}
}
else
{
/* CVH 2016-08-22 CommandArgument changed from itemCode to recId, item can be added on different lines, not unique.
* Also delete line, don't just remove from session lines, otherwise line is never deleted
* Also refresh sales data, in case close modal, not save */
if (ddTransactionType.SelectedValue == "TI")
xData.DeleteTyped("recId", recId, typeof(oSales));
if (utils.verifySession("transactionLines"))
{
ArrayList currentBillings = (ArrayList)Session["transactionLines"];
ArrayList newBillings = new ArrayList();
//enumerate current billings
foreach (oSales bill in currentBillings)
{
if (bill.recId.ToString() != recId)
{
newBillings.Add(bill);
}
}
Session["transactionLines"] = newBillings;
}
}
BindTransactionLines();
BindSalesData();
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Fee code text changed event
///
///
///
protected void txtBillingCode_TextChanged(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(TextBox))
{
TextBox billingCode = (TextBox)sender;
if (billingCode.Text.Length >= 2)
{
//CVH 2016-09-15 Only process items not deleted
foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code,isDeleted", billingCode.Text + ",0"))
{
switch (billingCode.ID)
{
case "txtEditLineUnitPrice":
BindItemsEdit(billingCode.Text, "");
CalculateAmountEditLine(true);
txtEditDetails.Text = item.code + " - " + item.description;
if (item.comments != String.Empty)
txtEditDetails.Text += " - " + item.comments;
break;
default:
BindItemsNew(billingCode.Text, "");
CalculateAmount(true);
txtDetails.Text = item.code + " - " + item.description;
if (item.comments != String.Empty)
txtDetails.Text += " - " + item.comments;
break;
}
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
/* CVH 2016-08-24 Not being used I think....
///
/// Post line to billing grid
///
///
///
protected void btnPost_Click(object sender, EventArgs e)
{
try
{
if (PostTransactionLine())
{
pnlResultEditLine.Visible = true;
lblResultEditLine.Text = "item added successfully";
BindTransactionLines();
ClearPostings();
txtBillingCode.Focus();
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
*/
///
/// Finalise Billing
///
///
///
protected void btnFinaliseBill_Click(object sender, EventArgs e)
{
/* CVH 2016-08-24 Set initial sales object, override with transaction line details saved in session */
string surfaceItemIdTmp = "";
if (rcbSalesContacts.SelectedItem != null)
surfaceItemIdTmp = rcbSalesContacts.SelectedItem.Value;
int surfaceItemId = 0;
int.TryParse(surfaceItemIdTmp, out surfaceItemId);
if (surfaceItemId <= 0)
{
lblResultBilling.Text = "Please select a Contact.";
pnlResultBilling.Visible = true;
return;
}
oSales acc = xSales.SetSalesContact(surfaceItemId);
SaveTransaction(false, acc);
}
///
/// Save Transaction
///
///
///
private void SaveTransaction(bool isDraft, oSales acc)
{
try
{
bool result = false;
switch (ddTransactionType.SelectedValue)
{
case "PM":
result = PostReceiptLine(isDraft, acc, ddTransactionType.SelectedValue);
break;
case "A":
result = PostReceiptLine(isDraft, acc, ddTransactionType.SelectedValue);
break;
case "AC":
result = PostReceiptLine(isDraft, acc, ddTransactionType.SelectedValue);
break;
case "CN":
result = PostReceiptLine(isDraft, acc, ddTransactionType.SelectedValue);
break;
default:
result = FinaliseTransaction(isDraft, acc);
break;
}
if (result)
{
txtPaymentAmount.Value = "0.00";
ddPaymentMethod.Focus();
pnlResultBilling.Visible = true;
lblResultBilling.Text = ddTransactionType.SelectedItem.Text + " was successfully saved.";
Session["transactionLines"] = null;
txtExtraNote.Text = "";
BindTransactionLines();
UpdateRunningTotals(acc.surfaceItemId.ToString());
BindSalesData();
txtBillingCode.Text = String.Empty;
txtBillingUnitPrice.Text = "0.00";
txtReference.Value = "";
CalculateAmount(false);
BindItemsNew("", "");
txtBillingCode.Focus();
BindQuotesToImport(acc.surfaceItemId.ToString(), false);
//CVH 2016-09-14 Update Next Transaction number in company setup. Get current db setup
oSetup setupUpdate = handler.ReturnSetup();
setupUpdate = (oSetup)(xData.GetTypedByCriteriaSpecific("recId", typeof(oSetup), "isActive", "1")[0]);
setupUpdate.saleQTENextNum = xData.GetQuoteNoSales();
setupUpdate.saleINVNextNum = xData.GetInvoiceNoSales("TI");
setupUpdate.saleRCTNextNum = xData.GetNextRecNoSales();
setupUpdate.saleCRNNextNum = xData.GetInvoiceNoSales("CN");
xData.UpdateTyped("recId", setupUpdate.recId.ToString(), typeof(oSetup), setupUpdate);
/* CVH 2016-09-13 Close modal */
// OnClientClick="$('#modTransaction').modal('toggle'); "
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myCloseTransModal", "$('#modTransaction').modal('hide');", true);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Save Draft Click
///
///
///
protected void btnSaveDraft_Click(object sender, EventArgs e)
{
try
{
/* CVH 2016-08-24 Set initial sales object, override with transaction line details saved in session */
string surfaceItemIdTmp = "";
if (rcbSalesContacts.SelectedItem != null)
surfaceItemIdTmp = rcbSalesContacts.SelectedItem.Value;
int surfaceItemId = 0;
int.TryParse(surfaceItemIdTmp, out surfaceItemId);
if (surfaceItemId <= 0)
{
lblResultBilling.Text = "Please select a Contact.";
pnlResultBilling.Visible = true;
return;
}
oSales acc = xSales.SetSalesContact(surfaceItemId);
SaveTransaction(true, acc);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Selected Index Changd event
///
///
///
protected void ddRelatedTo_SelectedIndexChanged(object sender, EventArgs e)
{
string numberToImport = ddRelatedTo.SelectedValue;
ArrayList billings = new ArrayList();
try
{
/* CVH 2016-08-24 Use Contact selected on modal */
string surfaceItemId = "";
if (rcbSalesContacts.SelectedItem != null)
surfaceItemId = rcbSalesContacts.SelectedItem.Value;
if (surfaceItemId == "0")
surfaceItemId = "";
string currentType = ddTransactionType.SelectedValue;
string docType = String.Empty;
ArrayList salesRecords = new ArrayList();
switch (currentType)
{
case "TI"://invoice so we need quotes to be imported
docType = "QT";
salesRecords = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType,invoiceNo", surfaceItemId + "," + docType + "," + numberToImport, "sequence");
break;
case "PM"://receipt so we need invoices to be imported that are not fully allocated
docType = "TI";
salesRecords = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType,invoiceNo", surfaceItemId + "," + docType + "," + numberToImport, "sequence");
break;
case "A"://allocation so we need invoices to be imported that are not fully allocated
docType = "TI";
salesRecords = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType,invoiceNo", surfaceItemId + "," + docType + "," + numberToImport, "sequence");
break;
case "CN"://credit note so we need invoices to be imported that are not yet allocated already
docType = "TI";
salesRecords = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,itemType,invoiceNo,allocated", surfaceItemId + "," + docType + "," + numberToImport + ",0", "sequence");
break;
}
foreach (oSales quoteItem in salesRecords)
{
//create a new billing
oSales accBilling = (oSales)utils.CloneObject(quoteItem);
if (currentType == "TI")
accBilling.recId = 0;
/* CVH 2016-08-25 Also when Credit Note. Needs to save new transactions for credit note based on linked invoice transaction */
if (currentType == "CN")
{
accBilling.allocatedReference = accBilling.recId.ToString();
accBilling.recId = 0;
}
if (currentType != "CN")
accBilling.itemType = currentType;
accBilling.dateOfService = utils.formatStringToDate(txtTransactionDate.Value);
//add time to date of service
TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
accBilling.dateOfService = accBilling.dateOfService.Add(time);
accBilling.dateOfCapture = DateTime.Now;
accBilling.isVisible = true;
accBilling.emailSent = false;
decimal bal = 0;
foreach (oSales billBal in billings)
{
bal += billBal.amount;
}
//running balance
accBilling.runningBal += accBilling.amount + bal;
accBilling.invoiceNo = 0;
billings.Add(accBilling);
}
Session["transactionLines"] = billings;
BindTransactionLines();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Selected Index changed event
///
///
///
protected void lstRelatedTo_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string numbersToImport = String.Empty;
foreach (ListItem item in lstRelatedTo.Items)
{
if (item.Selected && item.Value != string.Empty)
{
if (numbersToImport == String.Empty)
{ numbersToImport = item.Value; }
else
{ numbersToImport += "," + item.Value; }
}
}
ArrayList billings = new ArrayList();
int surfaceItemID = 0;
if (rcbSalesContacts.SelectedItem != null)
int.TryParse(rcbSalesContacts.SelectedItem.Value, out surfaceItemID);
string currentType = ddTransactionType.SelectedValue;
string docType = String.Empty;
ArrayList salesRecords = new ArrayList();
switch (currentType)
{
case "PM"://receipt so we need invoices to be imported that are not fully allocated
docType = "TI";
salesRecords = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "invoiceNo", numbersToImport, "sequence");
break;
case "A"://allocation so we need invoices to be imported that are not fully allocated
docType = "TI";
salesRecords = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "invoiceNo", numbersToImport, "sequence");
break;
case "AC"://allocation so we need invoices to be imported that are not fully allocated
docType = "TI";
salesRecords = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "invoiceNo", numbersToImport, "sequence");
break;
case "CN"://credit note so we need invoices to be imported that are not yet allocated already
docType = "TI";
salesRecords = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "invoiceNo", numbersToImport, "sequence");
break;
}
foreach (oSales invItem in salesRecords)
{
if (invItem.surfaceItemId == surfaceItemID && invItem.allocated < invItem.amount)
{
//create a new billing
oSales accBilling = (oSales)utils.CloneObject(invItem);
accBilling.dateOfService = utils.formatStringToDate(txtTransactionDate.Value);
//add time to date of service
TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
accBilling.dateOfService = accBilling.dateOfService.Add(time);
accBilling.dateOfCapture = DateTime.Now;
accBilling.isVisible = true;
decimal bal = 0;
foreach (oSales billBal in billings)
{
bal += billBal.amount;
}
//running balance
accBilling.runningBal += accBilling.amount + bal;
accBilling.invoiceNo = 0;
billings.Add(accBilling);
}
}
if (billings.Count > 0)
btnSaveDraft.Visible = false;
else
btnSaveDraft.Visible = true;
Session["transactionLines"] = billings;
BindTransactionLines();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Textbox Text Changed Event
///
///
///
protected void txbAllocateAmount_TextChanged(object sender, EventArgs e)
{
try
{
decimal allocated = 0;
PopulateAllocatedSoFarTotal(ref allocated);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
protected void btnAddContact_Click(object sender, EventArgs e)
{
try
{
Session["AddContactLoaded"] = "true";
LoadAddNewContactControl();
upAddNewContact.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myAddNewContactModal", "$('#modAddNewContact').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
protected override bool OnBubbleEvent(object source, EventArgs args)
{
try
{
CommandEventArgs e = (CommandEventArgs)args;
if (e.CommandName == "ReloadItems")
{
//CVH 2016-09-22 Need to refresh items in drop down after it was saved in items control
BindItemsNew("", "");
if (rcbEditLineDescription.Items.FindItemByValue(txtEditLineCode.Text) != null)
{
rcbEditLineDescription.ClearSelection();
rcbEditLineDescription.Items.FindItemByValue(txtEditLineCode.Text).Selected = true;
}
upEdit.Update();
upItem.Update();
}
else if (e.CommandName == "ReloadContacts")
{
//CVH 2016-09-22 Need to refresh contacts in drop down after it was saved in surface control
BindSalesToPicklists();
upTransaction.Update();
}
return true;
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
return false;
}
}
#endregion
#region edit line events
///
/// Edit click for Finalised billings
///
///
///
protected void lnkEditFinal_Click(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkEditFinal = (LinkButton)sender;
int recId = int.Parse(lnkEditFinal.CommandArgument);
foreach (oSales accEdit in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", recId.ToString()))
{
oSales acc = accEdit;
Session["salesEdit"] = acc;
BindItemsEdit("", "");
PopulateEditLineValues(ref acc);
upEdit.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myEditFinalModal", "$('#modEdit').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "editFinalPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true);
break;
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Edit Line Event
///
///
///
protected void lnkEdit_Click(object sender, EventArgs e)
{
try
{
/* CVH 2016-08-25 Get details of the line to edit from the CommandArgument recId, not session (which is first line on transaction) */
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkEdit = (LinkButton)sender;
if (lnkEdit != null)
{
if (lnkEdit.Parent.Parent.GetType() == typeof(RepeaterItem))
{
RepeaterItem item = (RepeaterItem)(lnkEdit).Parent.Parent;
string recId = lnkEdit.CommandArgument;
oSales editLine = new oSales();
if (recId == "0")
{
//get from transaction list session
if (utils.verifySession("transactionLines"))
{
ArrayList currentBillings = (ArrayList)Session["transactionLines"];
if (currentBillings != null && currentBillings.Count > item.ItemIndex)
{
editLine = (oSales)currentBillings[item.ItemIndex];
}
}
}
else
{
ArrayList list = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", recId);
if (list == null || list.Count <= 0)
throw new Exception("Sales line with ID " + recId + " not found.");
editLine = (oSales)list[0];
}
Session["editIndex"] = item.ItemIndex;
Session["salesEdit"] = editLine;
BindItemsEdit("", "");
PopulateEditLineValues(ref editLine);
upEdit.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myEditLineModal", "$('#modEdit').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "editLinePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true);
}
}
/*
if (lnkEdit.Parent.GetType() == typeof(RepeaterItem))
{
RepeaterItem item = (RepeaterItem)(lnkEdit).Parent;
if (this.Sales != null)
{
Session["editIndex"] = item.ItemIndex;
oSales acc = this.Sales;
oSales editLine = (oSales)utils.CloneObject(acc);
//get values from row
Label lblDateOfService = (Label)item.FindControl("lblDateOfService");
if (lblDateOfService != null)
{
editLine.dateOfService = utils.formatStringToDate(lblDateOfService.Text);
}
Label lblInvoiceNo = (Label)item.FindControl("lblInvoiceNo");
if (lblInvoiceNo != null)
{
editLine.invoiceNo = int.Parse(lblInvoiceNo.Text);
}
Label lblProcedureCode = (Label)item.FindControl("lblProcedureCode");
if (lblProcedureCode != null)
{
editLine.itemCode = lblProcedureCode.Text;
}
Label lblQty = (Label)item.FindControl("lblQty");
if (lblQty != null)
{
editLine.qty = Decimal.Parse(lblQty.Text);
}
Label lblUnitFee = (Label)item.FindControl("lblUnitFee");
if (lblUnitFee != null)
{
editLine.unitFee = Decimal.Parse(lblUnitFee.Text);
}
Session["salesEdit"] = editLine;
PopulateEditLineValues(ref editLine);
upEdit.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myEditLineModal", "$('#modEdit').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "editLinePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true);
}
else
{
Response.Redirect("/home", false);
}
}
*/
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// apply edit
///
///
///
protected void btnSaveEdit_Click(object sender, EventArgs e)
{
ArrayList billings = new ArrayList();
try
{
oSales editLine = (oSales)Session["salesEdit"];
SaveEditLineValues(ref editLine);
if (editLine.recId > 0)//this is a finalised line we are editing
{
if (xData.UpdateTyped("recId", editLine.recId.ToString(), typeof(oSales), editLine))
{
if (editLine.itemType == "TI")//remove any allocate drecpeipts or credit notes
RemoveInvoiceReceipts(editLine.invoiceNo, editLine.surfaceItemId);
if (editLine.itemType == "PM")//unallocate the receipt
UnAllocateReceipt(editLine.receiptNo, editLine.surfaceItemId);
if (editLine.itemType == "CN")//unallocate the credit note
UnAllocateCreditNote(editLine.invoiceNo, editLine.surfaceItemId);
/* CVH 2016-08-22 Update line in session */
if (utils.verifySession("transactionLines"))
{
ArrayList currentBillings = (ArrayList)Session["transactionLines"];
ArrayList newBillings = new ArrayList();
//enumerate current billings
foreach (oSales bill in currentBillings)
{
if (bill.recId != editLine.recId)
newBillings.Add(bill);
else
newBillings.Add(editLine);
}
Session["transactionLines"] = newBillings;
BindTransactionLines();
}
BindSalesData();
upTransaction.Update();
}
}
else//posting line not yet commited
{
if (utils.verifySession("transactionLines"))
{
billings = (ArrayList)Session["transactionLines"];
}
if (utils.verifySession("editIndex"))
{
int index = int.Parse(Session["editIndex"].ToString());
int count = 0;
ArrayList newBillings = new ArrayList();
foreach (oSales billing in billings)
{
if (index == count)
{
editLine.isVisible = true;
newBillings.Add(editLine);
}
else
{
newBillings.Add(billing);
}
count++;
}
Session["transactionLines"] = newBillings;
BindTransactionLines();
upTransaction.Update();
}
}
Session["salesEdit"] = editLine;
pnlResultEditLine.Visible = true;
lblResultEditLine.Text = "The edit has been applied successfully.";
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Move sequence up
///
///
///
protected void lnkMoveUp_Click(object sender, EventArgs e)
{
/* CVH 2016-08-24 Not being used
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkMoveUp = (LinkButton)sender;
string[] commandArgs = lnkMoveUp.CommandArgument.ToString().Split(new char[] { ',' });
int recId = int.Parse(commandArgs[0]);
int surfaceItemId = int.Parse(commandArgs[1]);
string dateOfService = commandArgs[2];
int sequence = int.Parse(commandArgs[3]);
int swopSeqOld = 0;
int swopSeqNew = 0;
bool setNext = false;
foreach (oSales acc in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,dateOfService,isVisible", surfaceItemId.ToString() + "," + dateOfService.ToString() + ",1", "sequence desc"))
{
if (setNext)
{
swopSeqNew = acc.sequence;
acc.sequence = swopSeqOld;
xData.UpdateTyped("recId", acc.recId.ToString(), typeof(oSales), acc);
foreach (oSales sales in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", recId.ToString()))
{
sales.sequence = swopSeqNew;
xData.UpdateTyped("recId", recId.ToString(), typeof(oSales), sales);
}
break;
}
if (recId == acc.recId && acc.sequence > 1)
{
//acc.sequence--;
//xData.UpdateTyped("recId", acc.recId.ToString(), typeof(oSales), acc);
setNext = true;
swopSeqOld = acc.sequence;
}
}
if (this.Sales != null)
{
oSales acc = this.Sales;
UpdateRunningTotals(acc);
BindSalesData();
}
else
{
Response.Redirect("/home", false);
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
*/
}
///
/// Move sequence down
///
///
///
protected void lnkMoveDown_Click(object sender, EventArgs e)
{
/* CVH 2016-08-24 Not being used
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkMoveDown = (LinkButton)sender;
string[] commandArgs = lnkMoveDown.CommandArgument.ToString().Split(new char[] { ',' });
int recId = int.Parse(commandArgs[0]);
int surfaceItemId = int.Parse(commandArgs[1]);
string dateOfService = commandArgs[2];
int sequence = int.Parse(commandArgs[3]);
int swopSeqOld = 0;
int swopSeqNew = 0;
bool setNext = false;
foreach (oSales acc in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,dateOfService,isVisible", surfaceItemId.ToString() + "," + dateOfService.ToString() + ",1", "sequence"))
{
if (setNext)
{
swopSeqNew = acc.sequence;
acc.sequence = swopSeqOld;
xData.UpdateTyped("recId", acc.recId.ToString(), typeof(oSales), acc);
foreach (oSales sales in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", recId.ToString()))
{
sales.sequence = swopSeqNew;
xData.UpdateTyped("recId", recId.ToString(), typeof(oSales), sales);
}
break;
}
if (recId == acc.recId)
{
setNext = true;
swopSeqOld = acc.sequence;
}
}
if (this.Sales != null)
{
oSales acc = this.Sales;
UpdateRunningTotals(acc);
BindSalesData();
}
else
{
Response.Redirect("/home", false);
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
*/
}
#endregion
#region statement events
///
/// Selected index changed event
///
///
///
protected void ddStatementContacts_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int surfaceItemId = 0;
if (ddStatementContacts.SelectedItem != null)
int.TryParse(ddStatementContacts.SelectedItem.Value, out surfaceItemId);
oSales statementSale = null;
foreach (oSales sale in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId", surfaceItemId.ToString(), "recId DESC"))
{
statementSale = sale;
break;
}
/* CVH 2016-08-24 Allow blank object, blank statement, but get contact details */
if (statementSale == null && surfaceItemId > 0)
statementSale = xSales.SetSalesContact(surfaceItemId);
lblResultStatement.Text = String.Empty;
pnlResultStatement.Visible = false;
/* CVH 2016-09-02 Load email template for user to edit before sending */
oSetup setup = handler.ReturnSetup();
edStatementEmailBody.Content = String.Empty;
foreach (oTemplate template in xData.GetTypedByCriteriaSpecific("recId", typeof(oTemplate), "templateName", "Sales Statement E-mail Template"))
{
edStatementEmailBody.Content = xSales.BuildEmailTemplate(template.templateContent, statementSale, setup, ConfigurationManager.AppSettings["WebAddy"]);
break;
}
string to = "";
string cc = ConfigurationManager.AppSettings["admin"];
string bcc = ConfigurationManager.AppSettings["bcc"];
if (statementSale != null)
{
to = statementSale.email;
if (cc == String.Empty)
cc = statementSale.emailCC;
else
cc += ";" + statementSale.emailCC;
}
/* CVH 2016-08-17 Load email settings */
/* CVH 2016-09-02 Don't change subject here, it's already been loaded correctly before modal was opened */
//txtStatementEmailSubject.Value = subject;
txtStatementEmailTo.Value = to;
txtStatementEmailCc.Value = cc;
txtStatementEmailBcc.Value = bcc;
if (pnlEmailStatement.Visible)
{
btnCreateStatement.Visible = false;
btnEmailStatement.Visible = true;
}
else
{
btnCreateStatement.Visible = true;
btnEmailStatement.Visible = false;
}
upStatement.Update();
ViewState["SendStatement"] = statementSale;
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Statement action selection changed
///
///
///
protected void rblStatementAction_SelectedIndexChanged(object sender, EventArgs e)
{
if (rblStatementAction.SelectedItem.Value == "Print")
{
pnlEmailStatement.Visible = false;
btnEmailStatement.Visible = false;
btnCreateStatement.Visible = true;
}
else
{
pnlEmailStatement.Visible = true;
btnEmailStatement.Visible = true;
btnCreateStatement.Visible = false;
}
upStatement.Update();
}
///
/// Create the Statement
///
///
///
protected void btnCreateStatement_Click(object sender, EventArgs e)
{
try
{
string file = String.Empty;
string path = string.Empty;
if (ViewState["SendStatement"] == null)
{
Response.Redirect("/home", false);
return;
}
oSales acc = (oSales)ViewState["SendStatement"];
ViewState.Remove("SendStatement");
DateTime statementDateFrom = DateTime.Now.Date;
DateTime statementDateTo = DateTime.Now.Date;
if (txtStatementDateFrom.Value != "")
statementDateFrom = utils.formatStringToDate(txtStatementDateFrom.Value);
if (txtStatementDateTo.Value != "")
statementDateTo = utils.formatStringToDate(txtStatementDateTo.Value);
if (acc != null)
{
bool success = xSales.CreateSalesDocument(acc, ConfigurationManager.AppSettings["WebAddy"], DateTime.Now.Date, statementDateFrom, statementDateTo, ref path, ref file, pNums.DocumentType.Statement);
if (success)
{
pnlResultStatement.Visible = true;
lblResultStatement.Text = "Statement successful.";
upStatement.Update();
Response.Clear();
//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file);
Response.TransmitFile(path + file);
Response.Flush();
Response.SuppressContent = true;
ApplicationInstance.CompleteRequest();
//add note
int userId = 0;
if (utils.verifySession("user"))
{
userId = ((oUser)Session["user"]).recId;
}
xSales.AddCreateStatementNote(acc.surfaceItemId, "Sales Statement",
"A statement was created.", path, file, userId, this.NotesFieldName);
}
else
{
pnlResultStatement.Visible = true;
lblResultStatement.Text = "Statement failed.";
upStatement.Update();
}
}
else
{
pnlResultStatement.Visible = true;
lblResultStatement.Text = "Sales account not found.";
upStatement.Update();
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Email statement
///
///
///
protected void btnEmailStatement_Click(object sender, EventArgs e)
{
try
{
if (!utils.verifySession("user"))
{
Response.Redirect("/home", false);
return;
}
int userId = ((oUser)Session["user"]).recId;
if (ViewState["SendStatement"] == null)
{
Response.Redirect("/home", false);
return;
}
oSales acc = (oSales)ViewState["SendStatement"];
ViewState.Remove("SendStatement");
DateTime documentDate = System.DateTime.Now.Date;
DateTime statementDateFrom = DateTime.Now.Date;
if (txtStatementDateFrom.Value != "")
statementDateFrom = utils.formatStringToDate(txtStatementDateFrom.Value);
DateTime statementDateTo = DateTime.Now.Date;
if (txtStatementDateTo.Value != "")
statementDateTo = utils.formatStringToDate(txtStatementDateTo.Value);
string subject = txtStatementEmailSubject.Value;
string to = "";
string cc = "";
string bcc = "";
string emailBody = edStatementEmailBody.Content;
//validate email addresses
string errorMessage = "";
foreach (string emailTo in txtStatementEmailTo.Value.Split(';'))
{
if (emailTo.Trim() == String.Empty)
continue;
if (!utils.validateEmail(emailTo))
{
errorMessage = "Invalid email: To. ";
break;
}
else
{
if (to == String.Empty)
to = emailTo;
else
to += ";" + emailTo;
}
}
foreach (string emailCC in txtStatementEmailCc.Value.Split(';'))
{
if (emailCC.Trim() == String.Empty)
continue;
if (!utils.validateEmail(emailCC))
{
errorMessage += "Invalid email: Cc. ";
break;
}
else
{
if (cc == String.Empty)
cc = emailCC;
else
cc += ";" + emailCC;
}
}
foreach (string emailBcc in txtStatementEmailBcc.Value.Split(';'))
{
if (emailBcc.Trim() == String.Empty)
continue;
if (!utils.validateEmail(emailBcc))
{
errorMessage += "Invalid email: Bcc. ";
break;
}
else
{
if (bcc == String.Empty)
bcc = emailBcc;
else
bcc += ";" + emailBcc;
}
}
if (errorMessage != String.Empty)
{
pnlResultStatement.Visible = true;
lblResultStatement.Text = errorMessage;
upStatement.Update();
return;
}
/* CVH 2016-09-13 Use communication email in Company Setup as from email address, and set from address display name */
oSetup setup = handler.ReturnSetup();
bool success = xSales.EmailSalesDocument(acc, setup.communicationEmail,
subject, to, cc, bcc, emailBody, ConfigurationManager.AppSettings["WebAddy"],
userId, documentDate, statementDateFrom, statementDateTo, pNums.DocumentType.Statement, "", setup.sendingEmailName, this.NotesFieldName);
if (success)
{
pnlResultStatement.Visible = true;
lblResultStatement.Text = "Email to Sales Holder: Successful.";
}
else
{
pnlResultStatement.Visible = true;
lblResultStatement.Text = "Email sending failed.";
}
upStatement.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Send Document
///
///
///
protected void btnSendDocument_Click(object sender, EventArgs e)
{
try
{
if (!utils.verifySession("user"))
{
Response.Redirect("/home", false);
return;
}
int userId = ((oUser)Session["user"]).recId;
if (ViewState["SendSale"] == null)
{
Response.Redirect("/home", false);
return;
}
oSales acc = (oSales)ViewState["SendSale"];
ViewState.Remove("SendSale");
pNums.DocumentType docType;
string documentNumber = "";
switch (acc.itemType)
{
case "TI":
docType = pNums.DocumentType.Invoice;
documentNumber = acc.invoiceNo.ToString();
break;
case "PM":
docType = pNums.DocumentType.Receipt;
documentNumber = acc.receiptNo.ToString();
break;
case "QT":
docType = pNums.DocumentType.Quote;
documentNumber = acc.invoiceNo.ToString();
break;
case "CN":
docType = pNums.DocumentType.CreditNote;
documentNumber = acc.invoiceNo.ToString();
break;
default:
docType = pNums.DocumentType.Invoice;
documentNumber = acc.invoiceNo.ToString();
break;
}
DateTime documentDate = System.DateTime.Now.Date;
string subject = txtField1.Text;
string to = "";
string cc = "";
string bcc = "";
string emailBody = edEmailBody.Content;
//validate email addresses
string errorMessage = "";
foreach (string emailTo in txtField2.Value.Split(';'))
{
if (emailTo.Trim() == String.Empty)
continue;
if (!utils.validateEmail(emailTo))
{
errorMessage = "Invalid email: To. ";
break;
}
else
{
if (to == String.Empty)
to = emailTo;
else
to += ";" + emailTo;
}
}
foreach (string emailCC in txtField3.Value.Split(';'))
{
if (emailCC.Trim() == String.Empty)
continue;
if (!utils.validateEmail(emailCC))
{
errorMessage += "Invalid email: Cc. ";
break;
}
else
{
if (cc == String.Empty)
cc = emailCC;
else
cc += ";" + emailCC;
}
}
foreach (string emailBcc in txtField4.Value.Split(';'))
{
if (emailBcc.Trim() == String.Empty)
continue;
if (!utils.validateEmail(emailBcc))
{
errorMessage += "Invalid email: Bcc. ";
break;
}
else
{
if (bcc == String.Empty)
bcc = emailBcc;
else
bcc += ";" + emailBcc;
}
}
if (errorMessage != String.Empty)
{
pnlSendDocumentResult.Visible = true;
lblSendDocumentResult.Text = errorMessage;
//upSendDocument.Update();
return;
}
/* CVH 2016-09-13 Use communication email in Company Setup as from email address, and set from address display name */
oSetup setup = handler.ReturnSetup();
bool success = xSales.EmailSalesDocument(acc, setup.communicationEmail,
subject, to, cc, bcc, emailBody, ConfigurationManager.AppSettings["WebAddy"],
userId, documentDate, null, null, docType, documentNumber, setup.sendingEmailName, this.NotesFieldName);
if (success)
{
pnlSendDocumentResult.Visible = true;
lblSendDocumentResult.Text = "Email to Sales Holder: Successful.";
acc.emailSent = true;
if (xData.UpdateTyped("recId", acc.recId.ToString(), typeof(oSales), acc))
{
BindSalesData();
}
}
else
{
pnlSendDocumentResult.Visible = true;
lblSendDocumentResult.Text = "Email sending failed.";
}
//upSendDocument.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#region item events
///
/// Add items
///
///
///
protected void btnAddItems_Click(object sender, EventArgs e)
{
/* CVH 2016-08-24 Set initial sales object, override with transaction line details saved in session */
string surfaceItemIdTmp = "";
if (rcbSalesContacts.SelectedItem != null)
surfaceItemIdTmp = rcbSalesContacts.SelectedItem.Value;
int surfaceItemId = 0;
int.TryParse(surfaceItemIdTmp, out surfaceItemId);
if (surfaceItemId <= 0)
{
lblResultBilling.Text = "Please select a Contact.";
pnlResultBilling.Visible = true;
return;
}
/* CVH 2016-08-22 Clear Item fields */
ClearPostings(surfaceItemId.ToString());
//show add item modal
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myItemModal", "$('#modItem').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "billingPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true);
}
///
/// Add item to
///
///
///
protected void btnAddItem_Click(object sender, EventArgs e)
{
try
{
/* CVH 2016-08-24 Set initial sales object, override with transaction line details saved in session */
string surfaceItemIdTmp = "";
if (rcbSalesContacts.SelectedItem != null)
surfaceItemIdTmp = rcbSalesContacts.SelectedItem.Value;
int surfaceItemId = 0;
int.TryParse(surfaceItemIdTmp, out surfaceItemId);
if (surfaceItemId <= 0)
{
lblResultItem.Text = "Please select a Contact.";
pnlResultItem.Visible = true;
return;
}
oSales acc = xSales.SetSalesContact(surfaceItemId);
if (PostTransactionLine(acc))
{
BindTransactionLines();
upTransaction.Update();
ClearPostings(surfaceItemId.ToString());
txtBillingCode.Focus();
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
protected void btnNewItem_Click(object sender, EventArgs e)
{
try
{
Session["AddItemLoaded"] = "true";
LoadAddNewItemControl();
upAddNewItem.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myAddNewItemModal", "$('#modAddNewItem').modal();", true);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#endregion
}