using framework_business;
using framework_library;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class controls_module_salesBak : ICanvasBase, IControlBase
{
MediSwitch mediswitch;
decimal dTotalAmount = 0, dTotalMedicalLiable = 0, dTotalPatientLiable = 0;
public oSales Sales
{
get
{
if (ViewState["sales"] == null)
return null;
else
return (oSales)ViewState["sales"];
}
set
{
ViewState["sales"] = value;
}
}
public void ReloadControl()
{
try
{
if (utils.verifySession("sales"))
this.Sales = (oSales)Session["sales"];
oSales sales = this.Sales;
PopulatePageFormValues(ref sales);
SetupControl(sales);
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, this.Sales);
Response.Redirect("/error", false);
}
}
#region methods
///
/// Method to Bind Sales Data
///
private void BindSalesData(oSales acc)
{
try
{
Session["bal"] = 0;
ArrayList salesList = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId", acc.surfaceItemId.ToString(), "dateOfService,sequence,recId");
ArrayList financialList = new ArrayList();
//temp update missing records
foreach (oSales sale in salesList)
{
if (sale.itemType != "QT" && sale.isVisible)
{
financialList.Add(sale);
}
}
//bind Sales view grid
rptActivity.DataSource = salesList;
rptActivity.DataBind();
//bind Financial View Grid
rptFinancial.DataSource = financialList;
rptFinancial.DataBind();
upSales.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, this.Sales);
Response.Redirect("/error", false);
}
}
///
/// Bind Items
///
private void BindItems(string itemCode, string description)
{
try
{
DataTable itemData = new DataTable();
if (itemCode != String.Empty)
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "code", itemCode, "description");
}
else if (description != String.Empty)
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "description", description, "description");
}
else
{
itemData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oSalesItem), "", "", "description");
}
if (itemData.Rows.Count == 0)
{
txtBillingCode.Text = "Invalid Code";
txtBillingCode.ForeColor = System.Drawing.Color.Red;
txtEditLineCode.Text = "Invalid Code";
txtEditLineCode.ForeColor = System.Drawing.Color.Red;
return;
}
else
{
txtBillingCode.ForeColor = System.Drawing.Color.Black;
txtEditLineCode.ForeColor = System.Drawing.Color.Black;
}
ddEditLineDescription.DataSource = itemData;
ddEditLineDescription.DataTextField = "description";
ddEditLineDescription.DataValueField = "code";
ddEditLineDescription.DataBind();
if (description == String.Empty && itemCode == String.Empty)
ddEditLineDescription.Items.Insert(0, new ListItem("select an item..", ""));
else
{
CalculateAmountEditLine(true);
}
ddBillingDescription.DataSource = itemData;
ddBillingDescription.DataTextField = "description";
ddBillingDescription.DataValueField = "code";
ddBillingDescription.DataBind();
if (description == String.Empty && itemCode == String.Empty)
{
ddBillingDescription.Items.Insert(0, new ListItem("select an item..", ""));
}
else
{
CalculateAmount(true);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// 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;
if (includeCall)
{
foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code", code))
{
unitFee = item.SellPriceIncl;
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)
{
foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code", code))
{
unitFee = item.SellPriceIncl;
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);
}
}
///
/// Bind Billing Lines
///
private void BindBillingLines()
{
ArrayList billings = new ArrayList();
try
{
if (utils.verifySession("billingLines"))
{
billings = (ArrayList)Session["billingLines"];
Session["billingLines"] = billings;
}
Session["bal"] = 0;
rptBillingAccounts.DataSource = billings;
rptBillingAccounts.DataBind();
//upBillingSaless.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Bind Billings to Allocate
///
private void BindBillingsToAllocate()
{
try
{
if (this.Sales != null)
{
oSales acc = this.Sales;
ArrayList billingsTemp = xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId,isVisible", acc.surfaceItemId.ToString() + ",1", "dateOfService,sequence");
ArrayList billings = new ArrayList();
foreach (oSales bill in billingsTemp)
{
if (bill.amount > 0 && bill.amount > bill.allocated)
{
if (bill.itemType == "TI")
{
bill.itemDescription = "d:" + bill.dateOfService.ToString("dd/MM/yyyy") + "-p:" + bill.itemCode + "- R" + utils.returnFormattedDecimal(Convert.ToString(bill.amount));
}
else
{
bill.itemDescription = "d:" + bill.dateOfService.ToString("dd/MM/yyyy") + "-p:" + bill.itemCode + "- R" + utils.returnFormattedDecimal(Convert.ToString(bill.amount));
}
billings.Add(bill);
}
}
lstBillings.DataSource = billings;
lstBillings.DataTextField = "itemDescription";
lstBillings.DataValueField = "recId";
lstBillings.DataBind();
}
}
catch (Exception ex)
{
exception.HandleException("canvas:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Populate Form Values
///
///
private void PopulatePageFormValues(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, this.Sales);
Response.Redirect("/error", false);
}
}
///
/// 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;
if (ddEditLineDescription.Items.FindByValue(_Sales.itemCode) != null)
ddEditLineDescription.SelectedValue = _Sales.itemCode;
txtEditLineQty.Text = utils.returnFormattedDecimal(Convert.ToString(_Sales.qty));
txtEditLineUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(_Sales.unitFee));
CalculateAmountEditLine(true);
}
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
{
//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);
_Sales.unitFee = unitFee;
_Sales.itemDescription = editItem.description;
_Sales.itemCode = editItem.code;
//service date
_Sales.dateOfService = utils.formatStringToDate(txtEditLineDate.Value);
//TO DO Theses will be selectable from setup and billing screen
_Sales.vatRate = 14;
//date of capture
_Sales.dateOfCapture = DateTime.Now;
//amounts
decimal amount = 0;
decimal.TryParse(txtEditLineTotal.Value, out amount);
//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;
//check if invoiceNo should change
_Sales.invoiceNo = xData.GetInvoiceNoSales(_Sales.dateOfService, _Sales.surfaceItemId);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Method to Toggle Panels
///
///
private void TogglePanels(string panelName)
{
switch (panelName)
{
case "pnlSalesPage":
break;
case "pnlSalesList":
break;
}
//clear result
pnlResult.Visible = false;
}
///
/// Post Billing Line
///
///
private bool PostBillingLine()
{
bool result = false;
ArrayList billings = new ArrayList();
try
{
if (this.Sales != null)
{
oSales acc = this.Sales;
if (utils.verifySession("billingLines"))
{
billings = (ArrayList)Session["billingLines"];
}
//create a new billing
oSales accBilling = (oSales)utils.CloneObject(acc);
//get prcoedure
oSalesItem billingProc = new oSalesItem();
foreach (oSalesItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSalesItem), "code", txtBillingCode.Text))
{
billingProc = item;
break;
}
if (billingProc.code != String.Empty)
{
//Tax Invoice
accBilling.itemType = "TI";
//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);
accBilling.unitFee = unitFee;
//modifier - done seperately
//if (ddBillingModifier.SelectedValue != null)
// accBilling.modifier1 = ddBillingModifier.SelectedValue;
accBilling.dateOfService = utils.formatStringToDate(txtBillingDate.Value);
accBilling.itemCode = billingProc.code;
accBilling.itemDescription = billingProc.description;
//TO DO This will read from pal_Setup
accBilling.vatRate = 14;
//date of capture
accBilling.dateOfCapture = DateTime.Now;
//amounts
decimal amount = 0;
decimal.TryParse(txtBillingTotal.Value, out amount);
accBilling.amount = amount;
//visible on statement
accBilling.isVisible = true;
//sequence and invoice no is in finalise procedure
decimal bal = 0;
foreach (oSales billBal in billings)
{
bal += billBal.amount;
}
//running balance
accBilling.runningBal += accBilling.amount + bal;
billings.Add(accBilling);
Session["billingLines"] = billings;
result = true;
}
else
{
//invalid code
pnlResultBilling.Visible = true;
lblResultBilling.Text = "Please provide a valid code";
}
}
else
{
Response.Redirect("/home", false);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
return result;
}
///
/// Update all running totals for sales
///
///
private void UpdateRunningTotals(oSales acc)
{
decimal bal = 0;
foreach (oSales sales in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "surfaceItemId", acc.surfaceItemId.ToString(), "dateOfService,sequence"))
{
bal += sales.amount;
sales.runningBal = bal;
xData.UpdateTyped("recId", sales.recId.ToString(), typeof(oSales), sales);
}
}
///
/// Reset all sequences in saless to captured order
/// - only use once -
///
private void ResetSequences()
{
int seq = 0, surfID = 0;
DateTime dateOfServ = utils.formatStringToDate("1900-01-01");
foreach (oSales sales in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "", "", "surfaceItemId,dateOfService,recId"))
{
if (surfID != sales.surfaceItemId || dateOfServ != sales.dateOfService)
seq = 0;
surfID = sales.surfaceItemId;
dateOfServ = sales.dateOfService;
seq++;
sales.sequence = seq;
xData.UpdateTyped("recId", sales.recId.ToString(), typeof(oSales), sales);
}
}
///
/// bool to finalise a billing session
///
///
private bool FinaliseBilling()
{
bool result = false;
ArrayList billings = new ArrayList();
try
{
if (utils.verifySession("billingLines"))
{
billings = (ArrayList)Session["billingLines"];
//GR - Added the sequence to increment on each line
int nextSequence = 0;
int invNo = 0;
bool mod5 = false;
foreach (oSales bill in billings)
{
if (nextSequence == 0)
{
invNo = xData.GetInvoiceNoSales(utils.formatStringToDate(txtBillingDate.Value), bill.surfaceItemId);
bill.invoiceNo = invNo;
nextSequence = xData.GetNextSequenceSales(utils.formatStringToDate(txtBillingDate.Value), bill.surfaceItemId);
bill.sequence = nextSequence;
}
else
{
bill.invoiceNo = invNo;
nextSequence++;
bill.sequence = nextSequence;
}
}
xData.SaveTypedCollection("recId", typeof(oSales), billings);
if (this.Sales != null)
{
oSales acc = this.Sales;
UpdateRunningTotals(acc);
PopulatePageFormValues(ref acc);
BindSalesData(acc);
result = true;
}
else
{ Response.Redirect("/home", false); }
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
return result;
}
///
/// Post Payment Line
///
///
private bool PostPaymentLine()
{
bool result = false;
oNote updateNote = new oNote();
updateNote.recId = 0;
try
{
if (this.Sales != null)
{
oSales acc = this.Sales;
oSales accPayment = new oSales();
if (utils.verifySession("AllocPayment"))
{
//pick up payment for allocation
accPayment = (oSales)Session["AllocPayment"];
if (ddPaymentMethod.SelectedValue == "CRED")
{
accPayment.itemDescription = accPayment.itemDescription.Replace("Payment - ", "Credit - ");
}
}
else
{
//create a new payment
accPayment = (oSales)utils.CloneObject(acc);
if (ddPaymentMethod.SelectedValue != null && ddPaymentMethod.SelectedValue != String.Empty)
{
//unit fee
decimal unitFee = 0;
decimal.TryParse(txtPaymentAmount.Value, out unitFee);
txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(unitFee));
//procedure info
accPayment.itemCode = ddPaymentMethod.SelectedValue;
string noteCaption = "A payment was receipted to the value of R " + utils.returnFormattedDecimal((unitFee * -1).ToString());
switch (ddPaymentMethod.SelectedValue)
{
case "CRED":
accPayment.itemDescription = "Credit - " + ddPaymentMethod.SelectedItem.Text;
accPayment.itemType = "CJ";
//amounts
accPayment.amount = unitFee * -1;
//receipt number
accPayment.receiptNo = xData.GetNextRecNo();
noteCaption = "A credit note was captured to the value of R " + utils.returnFormattedDecimal((unitFee * -1).ToString());
break;
case "DEB":
accPayment.itemDescription = "Debit - " + ddPaymentMethod.SelectedItem.Text;
accPayment.itemType = "DJ";
//amounts
accPayment.amount = unitFee;
//invoice number
accPayment.invoiceNo = xData.GetNextInvNo();
noteCaption = "A debit note was captured to the value of R " + utils.returnFormattedDecimal((unitFee).ToString());
break;
default:
accPayment.itemDescription = "Payment - " + ddPaymentMethod.SelectedItem.Text;
accPayment.itemType = "PM";
//amounts
accPayment.amount = unitFee * -1;
//receipt number
accPayment.receiptNo = xData.GetNextRecNo();
break;
}
accPayment.qty = 1;
//service date
accPayment.dateOfService = utils.formatStringToDate(txtPaymentDate.Value);
//TO DO Theses will be selectable from setup and billing screen
accPayment.vatRate = 14;
//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(txtPaymentDate.Value), accPayment.surfaceItemId);
accPayment.recId = xData.SaveTyped("recId", typeof(oSales), accPayment);
/* CVH 2016-04-20 Add new note of type "Payment" */
oNote note = new oNote();
note.moduleId = pNums.Module.Surface.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
pnlResultPayment.Visible = true;
lblResultPayment.Text = "Please provide a payment method";
}
}
if (accPayment.recId > 0)
{
bool billingsAllocated = false;
decimal ToAllocate = Math.Abs(accPayment.amount);
//apply allocations
foreach (ListItem item in lstBillings.Items)
{
if (item.Selected && ToAllocate > 0)
{
int billingId = int.Parse(item.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 = 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 = billing.recId.ToString(); }
else
{ accPayment.allocatedReference += "," + billing.recId.ToString() + ":" + Convert.ToString(availToAlloc); }
ToAllocate = 0;
}
}
else if (availToAlloc > ToAllocate)//then we want to partially allocate the billing
{
billing.allocated += ToAllocate;
if (billing.allocatedReference == String.Empty)
{ 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 = billing.recId.ToString(); }
else
{ accPayment.allocatedReference += "," + billing.recId.ToString(); }
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 = 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 = billing.recId.ToString(); }
else
{ accPayment.allocatedReference += "," + billing.recId.ToString(); }
ToAllocate -= availToAlloc;//deduct from whats availabel to allocate
}
}
}
billingsAllocated = true;
}
}
}
if (ToAllocate > 0 && billingsAllocated)//then split payment to allow for allocation later
{
if (ddPaymentMethod.SelectedValue == "CRED")
{
accPayment.itemType = "CJ";
}
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;
accPayment.sequence += 1;
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.Surface.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 + "
Procedures " + 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;
}
///
/// Method to create a test sales
///
private void 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;
this.Sales = sales;
}
///
/// Clear Posting values
///
private void ClearPostings()
{
try
{
txtBillingCode.Text = String.Empty;
BindItems("", "");
txtBillingQty.Text = "1";
txtBillingUnitPrice.Text = "0.00";
txtBillingTotal.Value = "0.00";
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#region events
///
/// Page Load Event
///
///
///
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (utils.verifySession("sales"))
this.Sales = (oSales)Session["sales"];
else
{
CreateTestSales();
}
oSales acc = this.Sales;
PopulatePageFormValues(ref acc);
if (!Page.IsPostBack)
{
BindItems("", "");
SetupControl(acc);
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
private void SetupControl(oSales acc)
{
//clear sessions for billings and payments
Session["billingLines"] = null;
Session["modList"] = null;
Session["AllocPayment"] = null;
txtPaymentDate.Disabled = false;
ddPaymentMethod.Enabled = true;
txtPaymentAmount.Disabled = false;
BindSalesData(acc);
//bind items
BindItems("", "");
txtBillingDate.Value = DateTime.Now.ToString("dd/MM/yyyy");
txtPaymentDate.Value = DateTime.Now.ToString("dd/MM/yyyy");
txtStatementDate.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 > pNums.UserType.WebsiteUser.GetHashCode())
divActions.Visible = true;
else
divActions.Visible = false;
}
}
#region menu events
///
/// Click event to perform a new billing
///
///
///
protected void btnNewBilling_Click(object sender, EventArgs e)
{
try
{
BindBillingLines();
txtBillingCode.Focus();
pnlResultBilling.Visible = false;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myBillingModal", "$('#modBilling').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);
upBilling.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// New Payment
///
///
///
protected void lnkNewPayment_Click(object sender, EventArgs e)
{
try
{
BindBillingsToAllocate();
BindPaymentMethods();
ddPaymentMethod.Focus();
pnlResultPayment.Visible = false;
txtPaymentAmount.Value = "0.00";
Session["AllocPayment"] = null;
txtPaymentDate.Disabled = false;
ddPaymentMethod.Enabled = true;
txtPaymentAmount.Disabled = false;
btnTakePayment.Text = "Process Receipt";
lblPaymentHeading.Text = "New Receipt";
upPayment.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myPaymentModal", "$('#modPayment').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "paymentPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", 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
{
lblEmailResultMedical.Text = "";
lblEmailResultPatient.Text = "";
lblEmailResultPractice.Text = "";
btnCreateStatement.Visible = true;
upStatement.Update();
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
///
/// Toggle To Sales History
///
///
///
protected void lnkToggleFinancial_Click(object sender, EventArgs e)
{
try
{
pnlFinancial.Visible = true;
pnlActivity.Visible = false;
upSales.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Toggle To Assisted Billings
///
///
///
protected void lnkActivityView_Click(object sender, EventArgs e)
{
try
{
pnlFinancial.Visible = false;
pnlActivity.Visible = true;
upSales.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Item Databound Event
///
///
///
protected void rptFinancial_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
HiddenField hfType = e.Item.FindControl("hfType") as HiddenField;
if (hfType != null)
{
//amount field
Label lblAmount = (Label)e.Item.FindControl("lblAmount");
decimal amount = 0;
decimal.TryParse(lblAmount.Text, out amount);
//running balance
decimal bal = 0;
if (utils.verifySession("bal"))
decimal.TryParse(Session["bal"].ToString(), out bal);
Label lblRunBal = (Label)e.Item.FindControl("lblRunBal");
lblRunBal.Text = utils.returnFormattedDecimal(Convert.ToString(amount + bal));
Session["bal"] = amount + bal;
//option links
LinkButton lnkCreditNote = (LinkButton)e.Item.FindControl("lnkCreditNote");
LinkButton lnkReversal = (LinkButton)e.Item.FindControl("lnkReversal");
LinkButton lnkEditFinal = (LinkButton)e.Item.FindControl("lnkEditFinal");
LinkButton lnkAllocate = (LinkButton)e.Item.FindControl("lnkAllocate");
Label lblAllocated = (Label)e.Item.FindControl("lblAllocated");
HiddenField hfAllocRef = e.Item.FindControl("hfAllocRef") as HiddenField;
if (lnkCreditNote != null && lnkReversal != null && lnkEditFinal != null)
{
lnkCreditNote.Visible = false;
lnkReversal.Visible = false;
lnkEditFinal.Visible = false;
switch (hfType.Value)
{
case "TI"://Tax Invoice
decimal Allocated = Convert.ToDecimal(lblAllocated.Text);
if (Allocated > 0 && Allocated == amount)
{ lblAllocated.ForeColor = System.Drawing.Color.Blue; }
else if (Allocated > 0 && Allocated < amount)
{
lblAllocated.ForeColor = System.Drawing.Color.Orange;
}
lnkCreditNote.Visible = true;
lnkReversal.Visible = false;
lnkEditFinal.Visible = true;
lnkAllocate.Visible = false;
break;
case "PM"://Payment
if (amount < 0)
{
if (hfAllocRef.Value == String.Empty)
{
lnkAllocate.Visible = true;
lblAmount.ForeColor = System.Drawing.Color.Red;
}
else
{
lnkAllocate.Visible = false;
lblAmount.ForeColor = System.Drawing.Color.Blue;
}
lnkCreditNote.Visible = false;
lnkReversal.Visible = true;
}
else
{
lblAmount.ForeColor = System.Drawing.Color.Purple;
lnkAllocate.Visible = false;
}
break;
case "DJ":
if (Convert.ToDecimal(lblAllocated.Text) > 0 && Convert.ToDecimal(lblAllocated.Text) == amount)
{ lblAllocated.ForeColor = System.Drawing.Color.Blue; }
else if (Convert.ToDecimal(lblAllocated.Text) > 0 && Convert.ToDecimal(lblAllocated.Text) < amount)
{ lblAllocated.ForeColor = System.Drawing.Color.Orange; }
lnkCreditNote.Visible = true;
lnkAllocate.Visible = false;
break;
case "CJ":
if (amount < 0)
{
if (hfAllocRef.Value == String.Empty)
{
lnkAllocate.Visible = true;
lblAmount.ForeColor = System.Drawing.Color.Red;
}
else
{
lnkAllocate.Visible = false;
lblAmount.ForeColor = System.Drawing.Color.Blue;
}
lnkCreditNote.Visible = false;
lnkReversal.Visible = true;
}
else
{
lblAmount.ForeColor = System.Drawing.Color.Purple;
lnkAllocate.Visible = false;
}
break;
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
protected void rptActivity_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
HiddenField hfType = e.Item.FindControl("hfType") as HiddenField;
if (hfType != null)
{
//amount field
Label lblAmount = (Label)e.Item.FindControl("lblAmount");
Label lblActivityType = (Label)e.Item.FindControl("lblActivityType");
decimal amount = 0;
decimal.TryParse(lblAmount.Text, out amount);
switch (hfType.Value)
{
case "QT":
lblActivityType.Text = "Quote";
break;
case "TI":
lblActivityType.Text = "Invoice";
break;
case "PM":
if (amount > 0)
lblActivityType.Text = "Reversal";
else
lblActivityType.Text = "Receipt";
break;
case "CN":
lblActivityType.Text = "Credit Note";
break;
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Click event to perform a Tax Credit Note
///
///
///
protected void lnkCreditNote_Click(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkRemove = (LinkButton)sender;
int recId = int.Parse(lnkRemove.CommandArgument);
if (this.Sales != null)
{
oSales acc = this.Sales;
PopulatePageFormValues(ref acc);
foreach (oSales billAcc in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", recId.ToString()))
{
if (billAcc.amount > 0 && billAcc.isVisible && (billAcc.itemType == "TI" || billAcc.itemType == "DJ"))
{
oSales creditNote = (oSales)utils.CloneObject(billAcc);
//set the reverse
creditNote.recId = 0;
creditNote.amount = creditNote.amount * -1;
creditNote.itemType = "CN";
creditNote.dateOfCapture = DateTime.Now;
creditNote.itemDescription = "Credit Note";
creditNote.invoiceNo = xData.GetInvoiceNo(creditNote.dateOfCapture, acc.surfaceItemId, 0, "");
creditNote.isVisible = false;
creditNote.userId = acc.userId;
creditNote.allocatedReference = billAcc.recId.ToString();
creditNote.recId = xData.SaveTyped("recId", typeof(oSales), creditNote);
if (creditNote.recId > 0)
{
//update payment to hidden too
billAcc.isVisible = false;
billAcc.allocated = billAcc.amount;
billAcc.allocatedReference = creditNote.recId.ToString();
if (xData.UpdateTyped("recId", billAcc.recId.ToString(), typeof(oSales), billAcc))
{
pnlResult.Visible = true;
lblResult.Text = "The Credit Note was successfully applied.";
PopulatePageFormValues(ref acc);
BindSalesData(acc);
}
}
}
else
{
pnlResult.Visible = true;
lblResult.Text = "A Credit could not be applied. It could be zero amount or the line has already been credited.";
}
}
}
else
{
Response.Redirect("/home", false);
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Click event to perform a reversal
///
///
///
protected void lnkReversal_Click(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkRemove = (LinkButton)sender;
int recId = int.Parse(lnkRemove.CommandArgument);
if (this.Sales != null)
{
oSales acc = this.Sales;
foreach (oSales payAcc in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", recId.ToString()))
{
if (payAcc.amount < 0 && payAcc.isVisible && (payAcc.itemType == "PM" || payAcc.itemType == "CJ"))
{
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 = "PM";
reversal.dateOfCapture = DateTime.Now;
reversal.itemDescription = "Payment Reversal";
reversal.isVisible = false;
reversal.userId = acc.userId;
reversal.receiptNo = xData.GetNextRecNo();
reversal.allocated = reversal.amount;
reversal.allocatedReference = recId.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(acc);
PopulatePageFormValues(ref acc);
upSales.Update();
}
}
}
else
{
pnlResult.Visible = true;
lblResult.Text = "A Reversal could not be applied. It could be zero amount or the line has already been reversed.";
}
}
}
else
{
Response.Redirect("/home", false);
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
protected void lnkAllocate_Click(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkRemove = (LinkButton)sender;
int recId = int.Parse(lnkRemove.CommandArgument);
if (this.Sales != null)
{
oSales acc = this.Sales;
foreach (oSales payLine in xData.GetTypedByCriteriaSpecific("recId", typeof(oSales), "recId", recId.ToString()))
{
BindPaymentMethods();
txtPaymentDate.Disabled = true;
//ddPaymentMethod.Enabled = false;
txtPaymentAmount.Disabled = true;
Session["AllocPayment"] = payLine;
//populate payline into modal
btnTakePayment.Text = "Apply Allocation";
lblPaymentHeading.Text = "New Allocation";
txtPaymentDate.Value = payLine.dateOfService.ToString("dd/MM/yyyy");
txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(Math.Abs(payLine.amount)));
BindBillingsToAllocate();
ddPaymentMethod.Focus();
pnlResultPayment.Visible = false;
upPayment.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myPaymentModal", "$('#modPayment').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "paymentPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true);
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// PreRender Event for Repeater
///
///
///
protected void rptFinancial_PreRender(object sender, EventArgs e)
{
Repeater rpt = (Repeater)sender;
int entryCount = 0;
foreach (RepeaterItem item in rptFinancial.Items)
{
HiddenField hfClaimSent = (HiddenField)item.FindControl("hfClaimSent");
HiddenField hfInvoice = (HiddenField)item.FindControl("hfInvoice");
LinkButton lnkEditFinal = (LinkButton)item.FindControl("lnkEditFinal");
LinkButton lnkNoEdit = (LinkButton)item.FindControl("lnkNoEdit");
LinkButton lnkCreditNote = (LinkButton)item.FindControl("lnkCreditNote");
LinkButton lnkReversal = (LinkButton)item.FindControl("lnkReversal");
LinkButton lnkAllocate = (LinkButton)item.FindControl("lnkAllocate");
}
for (int rowIndex = rpt.Items.Count - 2; rowIndex >= 0; rowIndex--)
{
RepeaterItem row = rpt.Items[rowIndex];
RepeaterItem previousRow = rpt.Items[rowIndex + 1];
Label lblDateOfService = (Label)row.FindControl("lblDateOfService");
Label lblDateOfServicePrev = (Label)previousRow.FindControl("lblDateOfService");
if (lblDateOfService.Text == lblDateOfServicePrev.Text)
{
entryCount++;
}
else
{
if (entryCount == 0)
{
if (rowIndex == 0)
{
LinkButton lnkMoveUp = (LinkButton)row.FindControl("lnkMoveUp");
lnkMoveUp.Visible = false;
LinkButton lnkMoveDown = (LinkButton)row.FindControl("lnkMoveDown");
lnkMoveDown.Visible = false;
}
LinkButton lnkMoveUpPrev = (LinkButton)previousRow.FindControl("lnkMoveUp");
lnkMoveUpPrev.Visible = false;
LinkButton lnkMoveDownPrev = (LinkButton)previousRow.FindControl("lnkMoveDown");
lnkMoveDownPrev.Visible = false;
}
entryCount = 0;
}
if (rowIndex == 0 && lblDateOfService.Text != lblDateOfServicePrev.Text)
{
LinkButton lnkMoveUp = (LinkButton)row.FindControl("lnkMoveUp");
lnkMoveUp.Visible = false;
LinkButton lnkMoveDown = (LinkButton)row.FindControl("lnkMoveDown");
lnkMoveDown.Visible = false;
}
}
}
#endregion
#region payment events
protected void ddPaymentMethod_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (oPaymentType paymentType in xData.GetTypedByCriteriaSpecific("recId", typeof(oPaymentType), "paymentCode", ddPaymentMethod.SelectedValue))
{
divAllocateTo.Visible = paymentType.allowAllocations;
}
}
private void BindPaymentMethods()
{
try
{
ddPaymentMethod.Items.Clear();
DataTable paymentTypeData = new DataTable();
paymentTypeData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oPaymentType), "", "");
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);
}
}
///
/// Take Payment
///
///
///
protected void btnTakePayment_Click(object sender, EventArgs e)
{
try
{
if (PostPaymentLine())
{
if (this.Sales != null)
{
oSales acc = this.Sales;
BindSalesData(acc);
PopulatePageFormValues(ref acc);
pnlResultPayment.Visible = true;
lblResultPayment.Text = lblPaymentHeading.Text + " was successfully posted.";
txtPaymentAmount.Value = "0.00";
ddPaymentMethod.Focus();
//enable payment fields for allocations
txtPaymentDate.Disabled = false;
ddPaymentMethod.Enabled = true;
txtPaymentAmount.Disabled = false;
/* CVH 2016-07-05 If sales balance is zero, show statement modal with email option available */
decimal accBal = xData.GetSalesBalance(acc.surfaceItemId);
if (accBal == 0)
{
lblEmailResultMedical.Text = "";
lblEmailResultPatient.Text = "";
lblEmailResultPractice.Text = "";
btnCreateStatement.Visible = false;
upStatement.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myAutoStatementModal", "$('#modStatement').modal();", true);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "autoStatementPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true);
}
}
else
{
Response.Redirect("/home", false);
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region billing events
protected void rptBillingAccounts_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}
///
/// uinit price Text changed event
///
///
///
protected void txtBillingUnitPrice_TextChanged(object sender, EventArgs e)
{
try
{
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("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
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;
}
upBilling.Update();
}
}
catch (Exception ex)
{
exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Description Selection Changed event
///
///
///
protected void ddDescription_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(DropDownList))
{
DropDownList dd = (DropDownList)sender;
string code = dd.SelectedValue;
switch (dd.ID)
{
case "ddEditLineDescription":
CalculateAmountEditLine(true);
txtEditLineCode.Text = code;
break;
default:
txtBillingCode.Text = code;
CalculateAmount(true);
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 code = lnkRemoveBilling.CommandArgument;
if (utils.verifySession("billingLines"))
{
ArrayList currentBillings = (ArrayList)Session["billingLines"];
ArrayList newBillings = new ArrayList();
//enumerate current billings
foreach (oSales bill in currentBillings)
{
if (bill.itemCode != code)
{
newBillings.Add(bill);
}
}
Session["billingLines"] = newBillings;
BindBillingLines();
}
}
}
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)
{
BindItems(billingCode.Text, "");
switch (billingCode.ID)
{
case "txtEditLineUnitPrice":
CalculateAmountEditLine(true);
break;
default:
CalculateAmount(true);
break;
}
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Post line to billing grid
///
///
///
protected void btnPost_Click(object sender, EventArgs e)
{
try
{
if (PostBillingLine())
{
BindBillingLines();
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)
{
try
{
if (FinaliseBilling())
{
pnlResultBilling.Visible = true;
lblResultBilling.Text = "Billing was successfully finalised.";
Session["billingLines"] = null;
BindBillingLines();
txtBillingCode.Text = String.Empty;
txtBillingUnitPrice.Text = "0.00";
CalculateAmount(false);
BindItems("", "");
txtBillingCode.Focus();
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", 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;
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
{
if (sender.GetType() == typeof(LinkButton))
{
LinkButton lnkEdit = (LinkButton)sender;
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
{
if (this.Sales != null)
{
oSales acc = this.Sales;
if (utils.verifySession("salesEdit"))
{
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))
{
BindSalesData(acc);
}
}
else//posting line not yet commited
{
if (utils.verifySession("billingLines"))
{
billings = (ArrayList)Session["billingLines"];
}
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["billingLines"] = newBillings;
BindBillingLines();
upBilling.Update();
}
}
Session["salesEdit"] = editLine;
pnlResultEditLine.Visible = true;
lblResultEditLine.Text = "The edit has been applied successfully.";
}
}
else
{
Response.Redirect("/home", false);
}
}
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)
{
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(acc);
PopulatePageFormValues(ref acc);
}
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)
{
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(acc);
PopulatePageFormValues(ref acc);
}
else
{
Response.Redirect("/home", false);
}
}
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
#endregion
#region statement events
///
/// Create the Statement
///
///
///
protected void btnCreateStatement_Click(object sender, EventArgs e)
{
try
{
string file = String.Empty;
string path = string.Empty;
string additionalEmailMessage = txtEmailBodyMessage.Value;
int bbfDays = 0;
if (txtBBF.Value != "")
bbfDays = int.Parse(txtBBF.Value);
bool showCorrections = chkShowHidden.Checked;
int maxLines = 15;
if (txtLineCount.Value != "")
maxLines = int.Parse(txtLineCount.Value);
bool fromZeroBalance = chkLatZero.Checked;
DateTime statementDate = DateTime.Now;
if (txtStatementDate.Value != "")
statementDate = utils.formatStringToDate(txtStatementDate.Value);
//TO DO send the email to sales contact
bool success = xSales.CreateStatement(this.Sales, ConfigurationManager.AppSettings["WebAddy"],
additionalEmailMessage, bbfDays, showCorrections, maxLines, fromZeroBalance, statementDate,
ref path, ref file);
if (success)
{
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
if (this.Sales != null)
{
int userId = 0;
if (utils.verifySession("user"))
{
userId = ((oUser)Session["user"]).recId;
}
xDebtors.AddCreateStatementNote(this.Sales.surfaceItemId, "Medical Statement",
"A medical statement was created.", path, file, userId);
}
}
}
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
{
/* CVH 2016-07-05 Methods EmailStatement, CreateStatement etc moved to xDebtors class */
if (!utils.verifySession("user"))
{
Response.Redirect("/home", false);
return;
}
oSales acc = this.Sales;
int userId = ((oUser)Session["user"]).recId;
string additionalEmailMessage = txtEmailBodyMessage.Value;
int bbfDays = 0;
if (txtBBF.Value != "")
bbfDays = int.Parse(txtBBF.Value);
bool showCorrections = chkShowHidden.Checked;
int maxLines = 15;
if (txtLineCount.Value != "")
maxLines = int.Parse(txtLineCount.Value);
bool fromZeroBalance = chkLatZero.Checked;
DateTime statementDate = DateTime.Now;
if (txtStatementDate.Value != "")
statementDate = utils.formatStringToDate(txtStatementDate.Value);
//TO DO create statment tio email to sales contact and not account
bool success = xSales.EmailAccountStatement(acc, ConfigurationManager.AppSettings["from"],
ConfigurationManager.AppSettings["bcc"], ConfigurationManager.AppSettings["admin"],
ConfigurationManager.AppSettings["WebAddy"], additionalEmailMessage, bbfDays,
showCorrections, maxLines, fromZeroBalance, userId, statementDate, "");
if (success)
{
emailResults.Attributes["display"] = "normal";
lblEmailResultPatient.Text = "Email to Sales Holder: Successful.";
lblEmailResultPatient.ForeColor = System.Drawing.Color.Green;
}
else
{
emailResults.Attributes["display"] = "normal";
lblEmailResultMedical.Text = "Email sending failed.";
}
upStatement.Update();
}
catch (Exception ex)
{
exception.HandleException("sales:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#endregion
}