Files
2019-10-08 21:50:51 +00:00

2665 lines
78 KiB
C#

///////////////////////////////////////////////////////////
// Client.cs
// Implementation of Class Client
// CSLA type: Editable Root
// Created on: 07-Jun-2004 8:41:14 AM
// Object design: Joyce
// Coded: John 02-July-2004
///////////////////////////////////////////////////////////
using System;
using System.Data;
using CSLA.Data;
using GZTW.Data;
using CSLA;
using System.Threading;
using CSLA.Security;
using System.ComponentModel;
namespace GZTW.AyaNova.BLL
{
/// <summary>
/// AyaNova client object representing a customer.
/// </summary>
[Serializable]
public class Client : BusinessBase
{
// Create a logger for use in this class
//private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#region Attributes
private bool bReadOnly;
private Guid mID;
private string mName=null;
private SmartDate mCreated;
private SmartDate mModified;
private bool mActive;
private Guid mCreator;
private Guid mModifier;
private Guid mDispatchZoneID;
private Address mGoToAddress;
private Address mMailToAddress;
//private long mOriginalCheckSum;
//private Contacts mContacts;
private string mWebAddress="";
private AssignedDocs mDocs;
private string mPopUpNotes="";
private Guid mClientGroupID;
private bool mBillHeadOffice;//
private Guid mHeadOfficeID=Guid.Empty;//
private string mNotes="";
private Guid mDefaultServiceTemplateID;//
private Guid mRegionID;
private string mTechNotes=""; //
private string mAccountNumber="";
//Custom fields
private string mCustom1=null;
private string mCustom2=null;
private string mCustom3=null;
private string mCustom4=null;
private string mCustom5=null;
private string mCustom6=null;
private string mCustom7=null;
private string mCustom8=null;
private string mCustom9=null;
private string mCustom0=null;
//Contract / bank stuff
private bool mUsesBanking;
private Guid mContractID;
private SmartDate mContractExpires;
//Notification internal stuff
private bool mContractExpiryChanged=false;
//case 3701
private bool mActiveChanged = false;
private string mContactNotes = "";
private string mContact = "";
private string mPhone1 = "";
private string mPhone2 = "";
private string mPhone3 = "";
private string mPhone4 = "";
private string mPhone5 = "";
private string mEmail = "";
//case 53
private bool mSendNotifications = true;
#endregion
#region Constructor
/// <summary>
/// Private constructor to prevent direct instantiation
/// </summary>
private Client()
{
////case 1039 //log.Debug("Client()");
//Set to read / write initially so that properties
//can be set
bReadOnly=false;
//New ID
mID = Guid.NewGuid();
//prebreak the rule
Name="";
Active=true;
//Built-in "Default" region
mRegionID=Region.DefaultRegionID;//case 58
//Set record history to defaults
mCreated = new SmartDate(DBUtil.CurrentWorkingDateTime);
mModified=new SmartDate();
mCreator=Guid.Empty;
mModifier=Guid.Empty;
mUsesBanking=false;
mContractID=Guid.Empty;
mContractExpires=new SmartDate();
//mDocs=AssignedDocs.NewItems();
}
#endregion
#region Business properties
/// <summary>
/// Optional identifier for display and reporting purposes
/// </summary>
public string AccountNumber
{
get
{
return mAccountNumber;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mAccountNumber!=value)
{
mAccountNumber = value;
BrokenRules.Assert("AccountNumberLength",
"Error.Object.FieldLengthExceeded255,Client.Label.AccountNumber","AccountNumber",value.Length>255);
MarkDirty();
}
}
}
}
/// <summary>
/// <see cref="DispatchZone"/> ID
/// </summary>
public Guid DispatchZoneID
{
get
{
return mDispatchZoneID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mDispatchZoneID!=value)
{
mDispatchZoneID = value;
MarkDirty();
}
}
}
}
/// <summary>
/// <see cref="ClientGroup"/> ID
/// </summary>
public Guid ClientGroupID
{
get
{
return mClientGroupID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mClientGroupID!=value)
{
mClientGroupID = value;
MarkDirty();
}
}
}
}
/// <summary>
/// If Service created from Client screen itself, it defaults to a specific
/// workorder template
/// Note this doesn't apply if you make a workorder "out of the blue" as it doesn't
/// know who you are going to select until after the template is selected.
/// </summary>
public Guid DefaultServiceTemplateID
{
get
{
return mDefaultServiceTemplateID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mDefaultServiceTemplateID!=value)
{
mDefaultServiceTemplateID = value;
MarkDirty();
}
}
}
}
/// <summary>
/// <see cref="HeadOffice"/> ID
/// </summary>
public Guid HeadOfficeID
{
get
{
return mHeadOfficeID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mHeadOfficeID!=value)
{
mHeadOfficeID = value;
BrokenRules.Assert("HeadOfficeIDRequired",
"Error.Object.RequiredFieldEmpty,O.HeadOffice",
"BillHeadOffice",value==Guid.Empty && this.mBillHeadOffice==true);
MarkDirty();
}
}
}
}
/// <summary>
/// <see cref="Region"/> ID
/// </summary>
public Guid RegionID
{
get
{
return mRegionID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mRegionID!=value)
{
mRegionID = value;
BrokenRules.Assert("RegionIDRequired",
"Error.Object.RequiredFieldEmpty,O.Region",
"RegionID",value==Guid.Empty);
MarkDirty();
}
}
}
}
/// <summary>
/// Get internal id number Read only property because it's set internally, not
/// externally
/// </summary>
public Guid ID
{
get
{
return mID;
}
}
/// <summary>
/// Get created date
///
///
/// </summary>
public string Created
{
get
{
return mCreated.ToString();
}
}
/// <summary>
/// Get modified date
///
///
/// </summary>
public string Modified
{
get
{
return mModified.ToString();
}
}
/// <summary>
/// Get user record ID of person who created this record
///
///
/// </summary>
public Guid Creator
{
get
{
return mCreator;
}
}
/// <summary>
/// Get user ID of person who modified this record
///
///
/// </summary>
public Guid Modifier
{
get
{
return mModifier;
}
}
/// <summary>
/// Set/get client name
/// </summary>
public string Name
{
get
{
return mName;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mName!=value)
{
mName = value;
BrokenRules.Assert("NameRequired",
"Error.Object.RequiredFieldEmpty,Client.Label.Name",
"Name",value.Length==0);
BrokenRules.Assert("NameLength",
"Error.Object.FieldLengthExceeded255,Client.Label.Name",
"Name",value.Length>255);
MarkDirty();
}
}
}
}
/// <summary>
/// Get /set active status of client
/// If active = true then client is selectable for workorders etc
/// If active = false then client in not selectable, but history can be viewed
/// </summary>
public bool Active
{
get
{
return mActive;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mActive!=value)
{
mActive = value;
//case 3701
mActiveChanged = true;
MarkDirty();
}
}
}
}
/// <summary>
/// Get service address for this client
/// </summary>
public Address GoToAddress
{
get
{
return mGoToAddress;
}
}
/// <summary>
/// Get mailing address object for this client
/// Returns GoToAddress object if MailToAddress is empty
/// </summary>
public Address MailToAddress
{
get
{
return mMailToAddress;
}
}
///// <summary>
///// Get Contacts collection for this object
///// </summary>
//public Contacts Contacts
//{
// get
// {
// return mContacts;
// }
//}
/// <summary>
/// web address of client if applicable
/// can be null
/// ties into hyerlink to web browser
/// </summary>
public string WebAddress
{
get
{
return mWebAddress;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mWebAddress!=value)
{
mWebAddress = value;
BrokenRules.Assert("WebAddressLength",
"Error.Object.FieldLengthExceeded255,Common.Label.WebAddress",
"WebAddress",value.Length>255);
MarkDirty();
}
}
}
}
/// <summary>
/// popup notes - need a setting to indicate whether to popup only on new workorder,
/// or popup whenever a change too
/// Corresponds to clients.alert in AyaNova v1
/// </summary>
public string PopUpNotes
{
get
{
return mPopUpNotes;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mPopUpNotes!=value)
{
mPopUpNotes = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Default is false
///
/// </summary>
public bool BillHeadOffice
{
get
{
return mBillHeadOffice;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mBillHeadOffice!=value)
{
mBillHeadOffice = value;
BrokenRules.Assert("HeadOfficeIDRequired",
"Error.Object.RequiredFieldEmpty,O.HeadOffice",
"BillHeadOffice",value==true && this.mHeadOfficeID==System.Guid.Empty);
MarkDirty();
}
}
}
}
/// <summary>
/// General notes about client
/// </summary>
public string Notes
{
get
{
return mNotes;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mNotes!=value)
{
mNotes = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Collection of <see cref="AssignedDoc"/> objects tied to this Client object
/// </summary>
public AssignedDocs Docs
{
get
{
return mDocs;
}
}
/// <summary>
/// Corresponds to clients.technotes in AyaNova v1
/// These are notes to display on dispatch reports for tech etc
/// </summary>
public string TechNotes
{
get
{
return mTechNotes;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mTechNotes!=value)
{
mTechNotes = value;
MarkDirty();
}
}
}
}
#region Contact fields
/// <summary>
/// Set/get client Contact person's name
/// </summary>
public string Contact
{
get
{
return mContact;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mContact != value)
{
mContact = value;
BrokenRules.Assert("ContactLength",
"Error.Object.FieldLengthExceeded500,Client.Label.Contact",
"Contact", value.Length > 500);
MarkDirty();
}
}
}
}
/// <summary>
/// Set/get client Phone1
/// </summary>
public string Phone1
{
get
{
return mPhone1;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mPhone1 != value)
{
mPhone1 = value;
BrokenRules.Assert("Phone1Length",
"Error.Object.FieldLengthExceeded255,Client.Label.Phone1",
"Phone1", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Set/get client Phone2
/// </summary>
public string Phone2
{
get
{
return mPhone2;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mPhone2 != value)
{
mPhone2 = value;
BrokenRules.Assert("Phone2Length",
"Error.Object.FieldLengthExceeded255,Client.Label.Phone2",
"Phone2", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Set/get client Phone3
/// </summary>
public string Phone3
{
get
{
return mPhone3;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mPhone3 != value)
{
mPhone3 = value;
BrokenRules.Assert("Phone3Length",
"Error.Object.FieldLengthExceeded255,Client.Label.Phone3",
"Phone3", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Set/get client Phone4
/// </summary>
public string Phone4
{
get
{
return mPhone4;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mPhone4 != value)
{
mPhone4 = value;
BrokenRules.Assert("Phone4Length",
"Error.Object.FieldLengthExceeded255,Client.Label.Phone4",
"Phone4", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Set/get client Phone5
/// </summary>
public string Phone5
{
get
{
return mPhone5;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mPhone5 != value)
{
mPhone5 = value;
BrokenRules.Assert("Phone5Length",
"Error.Object.FieldLengthExceeded255,Client.Label.Phone5",
"Phone5", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Set/get client Email
/// </summary>
public string Email
{
get
{
return mEmail;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mEmail != value)
{
mEmail = value;
BrokenRules.Assert("EmailLength",
"Error.Object.FieldLengthExceeded255,Client.Label.Email",
"Email", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Contact Notes / Other contacts
/// </summary>
public string ContactNotes
{
get
{
return mContactNotes;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mContactNotes != value)
{
mContactNotes = value;
MarkDirty();
}
}
}
}
#endregion contact fields
#region CUSTOM FIELDS
/// <summary>
/// Custom1
/// </summary>
public string Custom1
{
get
{
return mCustom1;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom1!=value)
{
mCustom1 = value;
BrokenRules.Assert("Custom1Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom1",
"Custom1",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom2
/// </summary>
public string Custom2
{
get
{
return mCustom2;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom2!=value)
{
mCustom2 = value;
BrokenRules.Assert("Custom2Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom2","Custom2",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom3
/// </summary>
public string Custom3
{
get
{
return mCustom3;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom3!=value)
{
mCustom3 = value;
BrokenRules.Assert("Custom3Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom3",
"Custom3",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom4
/// </summary>
public string Custom4
{
get
{
return mCustom4;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom4!=value)
{
mCustom4 = value;
BrokenRules.Assert("Custom4Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom4","Custom4",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom5
/// </summary>
public string Custom5
{
get
{
return mCustom5;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom5!=value)
{
mCustom5 = value;
BrokenRules.Assert("Custom5Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom5","Custom5",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom6
/// </summary>
public string Custom6
{
get
{
return mCustom6;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom6!=value)
{
mCustom6 = value;
BrokenRules.Assert("Custom6Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom6","Custom6",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom7
/// </summary>
public string Custom7
{
get
{
return mCustom7;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom7!=value)
{
mCustom7 = value;
BrokenRules.Assert("Custom7Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom7","Custom7",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom8
/// </summary>
public string Custom8
{
get
{
return mCustom8;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom8!=value)
{
mCustom8 = value;
BrokenRules.Assert("Custom8Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom8","Custom8",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom9
/// </summary>
public string Custom9
{
get
{
return mCustom9;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom9!=value)
{
mCustom9 = value;
BrokenRules.Assert("Custom9Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom9","Custom9",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom0
/// </summary>
public string Custom0
{
get
{
return mCustom0;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom0!=value)
{
mCustom0 = value;
BrokenRules.Assert("Custom0Length",
"Error.Object.FieldLengthExceeded500,Client.Label.Custom0","Custom0",value.Length>500);
MarkDirty();
}
}
}
}
#endregion custom fields
/// <summary>
/// If true then banked service is tracked
/// for this object (hours / money / incidents)
/// </summary>
public bool UsesBanking
{
get
{
return mUsesBanking;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mUsesBanking!=value)
{
mUsesBanking = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Contract that applies to this object
/// or Guid.Empty if no contract
/// </summary>
public Guid ContractID
{
get
{
return mContractID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mContractID!=value)
{
mContractID = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Retrieves the name of the contract for this client
/// or an empty string if there is no contract set
/// </summary>
public string ContractName
{
get
{
if(mContractID==Guid.Empty) return "";
return NameFetcher.GetItem("aContract","aName",this.mContractID).RecordName;
}
}
/// <summary>
/// Date contract expires and no longer applies
/// or null if contract does not expire ever
/// </summary>
public object ContractExpires
{
get
{
return mContractExpires.DBValue;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if (!AyaBizUtils.SmartDateEquals(mContractExpires, value)) //Case 298
{
mContractExpires.DBValue = value;
this.mContractExpiryChanged=true;
MarkDirty();
}
}
}
}
/// <summary>
/// If there is a contract and it has not expired returns true
/// otherwise false
/// </summary>
public bool ContractInEffect
{ //Added for Case 231
get
{
if (mContractID == Guid.Empty) return false;
if (mContractExpires.IsEmpty) return true;
if (mContractExpires.Date > DBUtil.CurrentWorkingDateTime) return true;
return false;
}
}
//Case 518
/// <summary>
/// If one of the two addresses is empty
/// copy the contents from the filled in one
/// to the empty one
///
/// This method is used during import from QBI and PTI
/// </summary>
public void PopulateBothAddresses()
{
//short circuit if both the same
if (!mGoToAddress.IsEmpty && !mMailToAddress.IsEmpty) return;
if (mGoToAddress.IsEmpty && mMailToAddress.IsEmpty) return;
//ok, one of these things is empty, the other isn't
if (mGoToAddress.IsEmpty)
Address.Copy(mMailToAddress,mGoToAddress);//copy mailto to goto
else
Address.Copy(mGoToAddress, mMailToAddress); ;//copy goto to mailto
}
/// <summary>
/// Get all phone numbers and email address in one string
/// </summary>
/// <returns></returns>
public string GetPrimaryContactDefaultContactInfo()
{
System.Text.StringBuilder b = new System.Text.StringBuilder();
b.Append(AyaBizUtils.SS(LocalizedTextTable.GetLocalizedTextDirect("Client.Label.Phone1") + ": ", Phone1, "\r\n"));
b.Append(AyaBizUtils.SS(LocalizedTextTable.GetLocalizedTextDirect("Client.Label.Phone2") + ": ", Phone2, "\r\n"));
b.Append(AyaBizUtils.SS(LocalizedTextTable.GetLocalizedTextDirect("Client.Label.Phone3") + ": ", Phone3, "\r\n"));
b.Append(AyaBizUtils.SS(LocalizedTextTable.GetLocalizedTextDirect("Client.Label.Phone4") + ": ", Phone4, "\r\n"));
b.Append(AyaBizUtils.SS(LocalizedTextTable.GetLocalizedTextDirect("Client.Label.Phone5") + ": ", Phone5, "\r\n"));
b.Append(AyaBizUtils.SS(LocalizedTextTable.GetLocalizedTextDirect("Client.Label.Email") + ": ", Email, "\r\n"));
return b.ToString();
}
/// <summary>
/// Flag - indicates if current user can open the wiki page for this object
/// See <see cref="WikiPage.ShowWikiLink(RootObjectTypes, Guid)"/> method for details
///
/// This is cached for the lifetime of this object
/// </summary>
public bool CanWiki
{
get
{
if (!bCanWiki.HasValue)
bCanWiki = WikiPage.ShowWikiLink(RootObjectTypes.Client, mID);
return bCanWiki.Value;
}
}
//cache the result in case the UI calls this repeatedly
private bool? bCanWiki = null;
/// <summary>
/// If true then will receive any notifications
/// set up for this client's region
/// </summary>
public bool SendNotifications
{
get
{
return mSendNotifications;
}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mSendNotifications != value)
{
mSendNotifications = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Indicates if item can be duplicated or not
/// Item can be duplicated if the current user
/// has write rights to this item and this item
/// is not dirty or new and IsValid
/// </summary>
public bool CanDuplicate
{
get
{
if (!AyaBizUtils.CanWrite(RootObjectTypes.Client)) return false;
if (IsDirty || IsNew || (!IsValid)) return false;
return true;
}
}
/// <summary>
/// Generates a duplicate of this item
/// and returns it.
/// </summary>
/// <returns></returns>
public Client Duplicate()
{//case 840
Client dest = Client.NewItem();
dest.Name = DBUtil.CurrentWorkingDateTime.ToString();
dest.AccountNumber = AccountNumber;
dest.BillHeadOffice = BillHeadOffice;
dest.ClientGroupID = ClientGroupID;
dest.Contact = Contact;
dest.ContactNotes = ContactNotes;
dest.ContractExpires = ContractExpires;
dest.ContractID = ContractID;
dest.Custom0 = Custom0;
dest.Custom1 = Custom1;
dest.Custom2 = Custom2;
dest.Custom3 = Custom3;
dest.Custom4 = Custom4;
dest.Custom5 = Custom5;
dest.Custom6 = Custom6;
dest.Custom7 = Custom7;
dest.Custom8 = Custom8;
dest.Custom9 = Custom9;
dest.DefaultServiceTemplateID = DefaultServiceTemplateID;
dest.DispatchZoneID = DispatchZoneID;
dest.Email = Email;
dest.GoToAddress.City = GoToAddress.City;
dest.GoToAddress.Country = GoToAddress.Country;
dest.GoToAddress.CountryCode = GoToAddress.CountryCode;
dest.GoToAddress.DeliveryAddress = GoToAddress.DeliveryAddress;
dest.GoToAddress.LatHemisphere = GoToAddress.LatHemisphere;
dest.GoToAddress.Latitude = GoToAddress.Latitude;
dest.GoToAddress.LongHemisphere = GoToAddress.LongHemisphere;
dest.GoToAddress.Longitude = GoToAddress.Longitude;
dest.GoToAddress.Postal = GoToAddress.Postal;
dest.GoToAddress.StateProv = GoToAddress.StateProv;
dest.MailToAddress.City = MailToAddress.City;
dest.MailToAddress.Country = MailToAddress.Country;
dest.MailToAddress.CountryCode = MailToAddress.CountryCode;
dest.MailToAddress.DeliveryAddress = MailToAddress.DeliveryAddress;
dest.MailToAddress.LatHemisphere = MailToAddress.LatHemisphere;
dest.MailToAddress.Latitude = MailToAddress.Latitude;
dest.MailToAddress.LongHemisphere = MailToAddress.LongHemisphere;
dest.MailToAddress.Longitude = MailToAddress.Longitude;
dest.MailToAddress.Postal = MailToAddress.Postal;
dest.MailToAddress.StateProv = MailToAddress.StateProv;
dest.HeadOfficeID = HeadOfficeID;
dest.Notes = Notes;
dest.Phone1 = Phone1;
dest.Phone2 = Phone2;
dest.Phone3 = Phone3;
dest.Phone4 = Phone4;
dest.Phone5 = Phone5;
dest.PopUpNotes = PopUpNotes;
dest.RegionID = RegionID;
dest.SendNotifications = SendNotifications;
dest.TechNotes = TechNotes;
dest.UsesBanking = UsesBanking;
dest.WebAddress = WebAddress;
return dest;
}
/// <summary>
/// Read only UI convenience property
/// true if client has tech notes
/// </summary>
public bool uiHasTechNotes
{
get
{
return !string.IsNullOrWhiteSpace(mTechNotes);
}
}
/// <summary>
/// Throw an error when a read only user
/// tries to set a property
/// (this should normally never be called unless someone is using the developer api since the UI
/// should prevent it from happening initially)
/// </summary>
private void ThrowSetError()
{
throw new System.Security.SecurityException
(
string.Format
(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToChange"),
LocalizedTextTable.GetLocalizedTextDirect("O.Client")
)
);
}
#endregion
#region System.object overrides
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "Client" + mID.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(Object obj)
{
if ( obj == null || GetType ( ) != obj.GetType ( ) ) return false;
Client c=(Client)obj;
return mID==c.mID;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return ("Client"+mID).GetHashCode();
}
#endregion
#region Searching
/// <summary>
/// Returns a search result object based on search terms
/// for the ID specified
/// </summary>
/// <param name="ID"></param>
/// <param name="searchTerms"></param>
/// <returns></returns>
public static SearchResult GetSearchResult(Guid ID, string[]searchTerms)
{
if(AyaBizUtils.Right("Object.Client")<(int)SecurityLevelTypes.ReadOnly)
return new SearchResult();
SearchResult sr=new SearchResult();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
SafeDataReader dr = null;
try
{
dr=DBUtil.GetReaderFromSQLString(
"SELECT aRegionID, aCreated, aModified, aCreator, aModifier, aName, " + //case 58
"aWebAddress, aPopUpNotes, aNotes, aTechNotes, AACCOUNTNUMBER, " +
"aContactNotes,aContact,aPhone1,aPhone2,aPhone3,aPhone4,aPhone5,aEmail, " +
"aCustom1, aCustom2, aCustom3, aCustom4, aCustom5, " +
"aCustom6, aCustom7, aCustom8, aCustom9, aCustom0 FROM aClient WHERE (aID = @ID)"
,ID);
if(!dr.Read())
return new SearchResult();//DBUtil.ThrowFetchError("SearchResult for ClientID: " + ID.ToString());
if(!AyaBizUtils.InYourRegion(dr.GetGuid("aRegionID"))) return new SearchResult();//case 58
sr.Description=dr.GetString("aName");
sb.Append(sr.Description);
sb.Append(" ");
sb.Append(dr.GetString("aWebAddress"));
sb.Append(" ");
sb.Append(dr.GetString("aPopUpNotes"));
sb.Append(" ");
sb.Append(dr.GetString("aNotes"));
sb.Append(" ");
sb.Append(dr.GetString("aTechNotes"));
sb.Append(" ");
sb.Append(dr.GetString("aContactNotes"));
sb.Append(" ");
sb.Append(dr.GetString("aContact"));
sb.Append(" ");
sb.Append(dr.GetString("aPhone1"));
sb.Append(" ");
sb.Append(dr.GetString("aPhone2"));
sb.Append(" ");
sb.Append(dr.GetString("aPhone3"));
sb.Append(" ");
sb.Append(dr.GetString("aPhone4"));
sb.Append(" ");
sb.Append(dr.GetString("aPhone5"));
sb.Append(" ");
sb.Append(dr.GetString("aEmail"));
sb.Append(" ");
sb.Append(dr.GetString("AACCOUNTNUMBER"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom0"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom1"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom2"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom3"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom4"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom5"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom6"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom7"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom8"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom9"));
sr.Created=DBUtil.ToLocal(dr.GetSmartDate("aCreated"));
sr.Modified=DBUtil.ToLocal(dr.GetSmartDate("aModified"));
sr.Creator=dr.GetGuid("aCreator");
sr.Modifier=dr.GetGuid("aModifier");
}
finally
{
if(dr!=null) dr.Close();
}
//Added 02-Aug-2006 was not returning address search results :(
#region Address block
try
{
dr = DBUtil.GetReaderFromSQLString(
"SELECT adeliveryaddress, acity, astateprov, acountrycode, acountry, apostal " +
"from aaddress " +
"where " +
"arootobjectid=@ID "
, ID);
while (dr.Read())
{
sb.Append(" ");
sb.Append(dr.GetString("adeliveryaddress"));
sb.Append(" ");
sb.Append(dr.GetString("acity"));
sb.Append(" ");
sb.Append(dr.GetString("astateprov"));
sb.Append(" ");
sb.Append(dr.GetString("acountrycode"));
sb.Append(" ");
sb.Append(dr.GetString("acountry"));
sb.Append(" ");
sb.Append(dr.GetString("apostal"));
}
}
finally
{
if (dr != null) dr.Close();
}
#endregion
//Formulate results
ExtractAndRank er = new ExtractAndRank();
er.Process(sb.ToString().Trim(),searchTerms);
sr.Extract=er.Extract;
sr.Rank=er.Ranking;
sr.AncestorRootObjectID=ID;
sr.AncestorRootObjectType=RootObjectTypes.Client;
return sr;
}
#endregion
#region Static methods
//Key to identify which reports can be generated from this object
//public static string ReportKey {get{return "ClientList";}}
/// <summary>
/// Create new Client
/// </summary>
/// <returns>Client</returns>
public static Client NewItem()
{
Client c;
if(AyaBizUtils.Right("Object.Client")>(int)SecurityLevelTypes.ReadOnly)
{
c = new Client();
c.mGoToAddress=Address.NewItem();
c.mGoToAddress.RootObjectID=c.mID;
c.mGoToAddress.RootObjectType=RootObjectTypes.Client;
c.mGoToAddress.AddressType=AddressTypes.Physical;
c.mMailToAddress=Address.NewItem();
c.mMailToAddress.RootObjectID=c.mID;
c.mMailToAddress.RootObjectType=RootObjectTypes.Client;
c.mMailToAddress.AddressType=AddressTypes.Postal;
c.mDocs=AssignedDocs.NewItems();
return c;
}
else
throw new System.Security.SecurityException(
string.Format(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToCreate"),
LocalizedTextTable.GetLocalizedTextDirect("O.Client")));
}
/// <summary>
/// Fetch client internally without tracking in MRU list
///
/// </summary>
/// <param name="_ID"></param>
/// <returns></returns>
public static Client GetItemNoMRU(Guid _ID)
{
if (_ID == AyaBizUtils.NewObjectGuid)
return NewItem();
if (AyaBizUtils.Right("Object.Client") > (int)SecurityLevelTypes.NoAccess)
{
Client c = (Client)DataPortal.Fetch(new Criteria(_ID, false));
return c;
}
else
throw new System.Security.SecurityException(
string.Format(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToRetrieve"),
LocalizedTextTable.GetLocalizedTextDirect("O.Client")));
}
/// <summary>
/// Fetch existing Client
/// </summary>
/// <returns>Client</returns>
/// <param name="_ID">Client Guid</param>
public static Client GetItem(Guid _ID)
{
if (_ID == AyaBizUtils.NewObjectGuid)
return NewItem();
if (AyaBizUtils.Right("Object.Client") > (int)SecurityLevelTypes.NoAccess)
{
Client c=(Client)DataPortal.Fetch(new Criteria(_ID,true));
return c;
}
else
throw new System.Security.SecurityException(
string.Format(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToRetrieve"),
LocalizedTextTable.GetLocalizedTextDirect("O.Client")));
}
/// <summary>
/// Delete Client
/// </summary>
/// <param name="_ID">Client GUID</param>
public static void DeleteItem(Guid _ID)
{
if (AyaBizUtils.Right("Object.Client") > (int)SecurityLevelTypes.ReadWrite)
{
DataPortal.Delete(new Criteria(_ID,true));
}
else
throw new System.Security.SecurityException(
string.Format(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToDelete"),
LocalizedTextTable.GetLocalizedTextDirect("O.Client")));
}
/// <summary>
/// Delete all Workorders service, quote or PM for client
/// ** This is not reversable **
/// Can only be done by manager account
/// </summary>
/// <param name="_ID">Client GUID</param>
/// <returns>Text result of operation</returns>
public static string DeleteAllClientWorkorders(Guid _ID)
{
System.Text.StringBuilder sbRet = new System.Text.StringBuilder();
if (User.IsAdmin)
{
Guid clientId = _ID;
#region Delete all workorders
{
//Delete all service workorders
string serviceWorkorderListCriteria = "<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?> \r\n" +
"<GRIDCRITERIA> \r\n" +
" <COLUMNITEM CM=\"aWorkorderService.aServiceNumber\" UI=\"LT_O_Workorder\" PIN=\"0\" WIDTH=\"92\" SORT=\"DESC\" /> \r\n" +
" <WHEREITEMGROUP GROUPLOGICALOPERATOR=\"And\" UI=\"LT_O_Client\"> \r\n" +
" <WHEREITEM COMPAREOPERATOR=\"Equals\" CM=\"aClient.aID\" UICOMPAREVALUE=\"\" TYPE=\"System.Guid\" COMPAREVALUE=\"{" + clientId.ToString().ToUpper() + "}\" /> \r\n" +
" </WHEREITEMGROUP> \r\n" +
"</GRIDCRITERIA>";
//find all service workorders and then try to delete them
sbRet.AppendLine("Delete all service workorders...");
var woslist = WorkorderServiceList.GetList(serviceWorkorderListCriteria);
if (woslist.Count > 0)
{
foreach (WorkorderServiceList.WorkorderServiceListInfo i in woslist)
{
var w = Workorder.GetItemNoMRU(i.LT_O_Workorder.Value);
try
{
if (!w.IsDeleteable)
{
w.Closed = false;
w.Delete();
w.Save();
}
else
{
w.Delete();
w.Save();
}
}
catch (Exception ex)
{
while (ex.InnerException != null)
ex = ex.InnerException;
sbRet.AppendLine("Unable to delete workorder " + w.uiDisplayVisibleIDNumber + " due to: " + ex.Message);
}
}
}
//sbRet.AppendLine("completed deleting service workorders");
}
{
//Delete all quotes
string quoteListCriteria = "<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?> \r\n" +
"<GRIDCRITERIA> \r\n" +
"<COLUMNITEM CM=\"aWorkorderQuote.aQuoteNumber\" UI=\"LT_O_WorkorderQuote\" PIN=\"0\" WIDTH=\"78\" /> \r\n" +
"<WHEREITEMGROUP GROUPLOGICALOPERATOR=\"And\" UI=\"LT_O_Client\"> \r\n" +
"<WHEREITEM COMPAREOPERATOR=\"Equals\" CM=\"aClient.aID\" UICOMPAREVALUE=\"\" TYPE=\"System.Guid\" COMPAREVALUE=\"{" + clientId.ToString().ToUpper() + "}\" /> \r\n" +
"</WHEREITEMGROUP> \r\n" +
"</GRIDCRITERIA> \r\n";
//find all quotes and then try to delete them
sbRet.AppendLine("Delete all Quotes...");
var woq = WorkorderQuoteList.GetList(quoteListCriteria);
if (woq.Count > 0)
{
foreach (WorkorderQuoteList.WorkorderQuoteListInfo i in woq)
{
var w = Workorder.GetItemNoMRU(i.LT_O_WorkorderQuote.Value);
try
{
if (!w.IsDeleteable)
{
w.Closed = false;
w.Delete();
w.Save();
}
else
{
w.Delete();
w.Save();
}
}
catch (Exception ex)
{
while (ex.InnerException != null)
ex = ex.InnerException;
sbRet.AppendLine("Unable to delete Quote " + w.uiDisplayVisibleIDNumber + " due to: " + ex.Message);
}
}
}
//sbRet.AppendLine("completed deleting quotes");
}
{
//Delete all PM's
string pmListCriteria = "<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?> \r\n" +
"<GRIDCRITERIA> \r\n" +
" <COLUMNITEM CM=\"aWorkorderPreventiveMaintenance.aPreventiveMaintenanceNumber\" UI=\"LT_O_WorkorderPreventiveMaintenance\" PIN=\"0\" WIDTH=\"150\" SORT=\"DESC\" /> \r\n" +
" <WHEREITEMGROUP GROUPLOGICALOPERATOR=\"And\" UI=\"LT_O_Client\"> \r\n" +
" <WHEREITEM COMPAREOPERATOR=\"Equals\" CM=\"aClient.aID\" UICOMPAREVALUE=\"ABC Accounting\" TYPE=\"System.Guid\" COMPAREVALUE=\"{" + clientId.ToString().ToUpper() + "}\" /> \r\n" +
" </WHEREITEMGROUP> \r\n" +
"</GRIDCRITERIA> ";
//find all quotes and then try to delete them
sbRet.AppendLine("Delete all Preventive Maintenance records...");
var wopm = WorkorderPMList.GetList(pmListCriteria);
if (wopm.Count > 0)
{
foreach (WorkorderPMList.WorkorderPMListInfo i in wopm)
{
var w = Workorder.GetItemNoMRU(i.LT_O_WorkorderPreventiveMaintenance.Value);
try
{
if (!w.IsDeleteable)
{
w.Closed = false;
w.Delete();
w.Save();
}
else
{
w.Delete();
w.Save();
}
}
catch (Exception ex)
{
while (ex.InnerException != null)
ex = ex.InnerException;
sbRet.AppendLine("Unable to delete Preventive Maintenance " + w.uiDisplayVisibleIDNumber + " due to: " + ex.Message);
}
}
}
// sbRet.AppendLine("completed deleting Preventive Maintenance");
}
#endregion;
}
else
{
sbRet.AppendLine("Only the administrator account can delete all client workorders");
}
return sbRet.ToString();
}
/// <summary>
/// Delete all Units for client
/// ** This is not reversable **
/// Can only be done by manager account
/// </summary>
/// <param name="_ID">Client GUID</param>
/// <returns>Text result of operation</returns>
public static string DeleteAllClientUnits(Guid _ID)
{
System.Text.StringBuilder sbRet = new System.Text.StringBuilder();
if (User.IsAdmin)
{
Guid clientId = _ID;
#region Delete all units
{
sbRet.AppendLine("Delete all units...");
var upl = UnitPickList.GetListByClient(clientId);
if (upl.Count > 0)
{
foreach (UnitPickList.UnitPickListInfo i in upl)
{
try
{
Unit.DeleteItem(i.ID);
}
catch (Exception ex)
{
while (ex.InnerException != null)
ex = ex.InnerException;
sbRet.AppendLine("Unable to delete unit " + i.Serial + " due to: " + ex.Message);
}
}
}
// sbRet.AppendLine("completed deleting units");
}
#endregion;
}
else
{
sbRet.AppendLine("Only the administrator account can delete all client units");
}
return sbRet.ToString();
}
/// <summary>
/// Check for the existance of a Client
/// in the database by ID OR by Name
/// </summary>
/// <param name="ID">Guid of client or Guid.Empty if checking by name</param>
/// <param name="Name">Name of client (case sensitive) or empty string "" if checking by ID</param>
/// <returns></returns>
public static bool Exists(Guid ID, string Name)
{
// return ExistsHelper.GetExists(ID,Name);
//case 496
return ClientExistanceChecker.ClientExists(ID, Name);
}
//case 1404
/// <summary>
/// Get the ID of a client from it's name
/// </summary>
/// <param name="Name">Name of client (case sensitive) or empty string "" if checking by ID</param>
/// <returns>Guid empty if not found else the id of the client with matching name</returns>
public static Guid IDFromName( string Name)
{
return ClientExistanceChecker.ClientExists(Name).mClientID;
}
/// <summary>
/// Retrieve internal ID from AccountNumber.
///
/// </summary>
/// <param AccountNumber="AccountNumber">Text value</param>
/// <returns>Guid ID value or Guid.Empty if no match</returns>
public static Guid GetIDFromAccountNumber(string AccountNumber)
{
return GuidFetcher.GetItem("ACLIENT", "AACCOUNTNUMBER", AccountNumber);
}
#endregion
#region Shared Notification Message Processor
internal static NotifyMessage GetNotificationMessage(NotifyMessageRequestData d)
{
//string Language=User.GetUserLanguage(MessageForUserID);
Client c=Client.GetItemNoMRU(d.RootObjectID);
string sEventDescription=LocalizedTextTable.GetLocalizedTextDirect("Client.Label.Event.ContractExpire",d.Language);
string sMessage=sEventDescription;
string sSubject=sEventDescription;
NotifyMessage nm=null;
//case 1415
string sContractExpires = c.ContractExpires.ToString();
if (!Convert.IsDBNull(c.ContractExpires))
{//if it's not dbnull then it's a date object
DateTime dtExpires = (DateTime)c.ContractExpires;
if (d.TimeZoneOffset != 0)
{
dtExpires = dtExpires.ToUniversalTime().AddHours(d.TimeZoneOffset);
sContractExpires = dtExpires.ToString();
}
}
if(d.Format==NotifyDeliveryMessageFormats.Brief)
{
sMessage += "-" + c.Name + "-" + sContractExpires;//case 1415
if(d.MaxCharacters > 0 && sMessage.Length>d.MaxCharacters)
nm=new NotifyMessage("", sMessage.Substring(0,d.MaxCharacters));
else
nm=new NotifyMessage("", sMessage);
}
else
{
sSubject+=": " + c.Name;
sMessage += ": " + sContractExpires + "\r\n" + c.Name + "\r\n" + LocalizedTextTable.GetLocalizedTextDirect("O.Contract", d.Language) + ": " + c.ContractName;
nm=new NotifyMessage(sSubject,sMessage);
}
return nm;
}
#endregion
#region DAL Data Access
#region Fetch
///
/// <param name="Criteria"></param>
protected override void DataPortal_Fetch(object Criteria)
{
//set to false to load items initially
bReadOnly=false;
Criteria crit = (Criteria)Criteria;
SafeDataReader dr = null;
try
{
//original
dr=DBUtil.GetReaderFromSQLString("SELECT * FROM aClient WHERE aID=@ID;",crit.ID);
if(!dr.Read())
DBUtil.ThrowFetchError("Client ID: " + crit.ID.ToString());
//Standard fields
mID=dr.GetGuid("aID");
mCreated=DBUtil.ToLocal(dr.GetSmartDate("aCreated"));
mModified=DBUtil.ToLocal(dr.GetSmartDate("aModified"));
mCreator=dr.GetGuid("aCreator");
mModifier=dr.GetGuid("aModifier");
//Custom fields
mCustom1=dr.GetString("aCustom1");
mCustom2=dr.GetString("aCustom2");
mCustom3=dr.GetString("aCustom3");
mCustom4=dr.GetString("aCustom4");
mCustom5=dr.GetString("aCustom5");
mCustom6=dr.GetString("aCustom6");
mCustom7=dr.GetString("aCustom7");
mCustom8=dr.GetString("aCustom8");
mCustom9=dr.GetString("aCustom9");
mCustom0=dr.GetString("aCustom0");
//Client fields
mActive=dr.GetBoolean("AACTIVE");
//Use the property, NOT the private attribute
//because this is pre-broken in the constructor
//to ensure a name is chosen / loaded from db
//only way to unbreak it is to go through
//the property accessor to load from db
Name=dr.GetString("aName");
mDispatchZoneID=dr.GetGuid("aDispatchZoneID");
mWebAddress=dr.GetString("aWebAddress");
mPopUpNotes=dr.GetString("aPopUpNotes");
mClientGroupID=dr.GetGuid("aClientGroupID");
mBillHeadOffice=dr.GetBoolean("aBillHeadOffice");
mHeadOfficeID=dr.GetGuid("aHeadOfficeID");
mNotes=dr.GetString("aNotes");
mDefaultServiceTemplateID = dr.GetGuid("ADEFAULTSERVICETEMPLATEID");
mRegionID=dr.GetGuid("aRegionID");
mTechNotes=dr.GetString("aTechNotes");
mAccountNumber=dr.GetString("AACCOUNTNUMBER");
mUsesBanking=dr.GetBoolean("aUsesBanking");
mContractID=dr.GetGuid("aContractID");
mContractExpires=DBUtil.ToLocal(dr.GetSmartDate("aContractExpires"));
mContactNotes = dr.GetString("aContactNotes");
mContact = dr.GetString("aContact");
mPhone1 = dr.GetString("aPhone1");
mPhone2 = dr.GetString("aPhone2");
mPhone3 = dr.GetString("aPhone3");
mPhone4 = dr.GetString("aPhone4");
mPhone5 = dr.GetString("aPhone5");
mEmail = dr.GetString("aEmail");
mSendNotifications = dr.GetBoolean("ASENDNOTIFICATIONS");
if(dr!=null) dr.Close();
//Load children:
//GoToAddress
dr=DBUtil.GetReaderFromSQLString("SELECT * " +
"FROM AADDRESS WHERE aRootObjectID=@ID AND " +
"aRootObjectType=3 AND AADDRESSTYPE=2",crit.ID);
if(dr.Read())
mGoToAddress=Address.GetItem(dr);
if(dr!=null) dr.Close();
//MailToAddress
dr=DBUtil.GetReaderFromSQLString("SELECT * " +
"FROM AADDRESS WHERE aRootObjectID=@ID AND " +
"aRootObjectType=3 AND AADDRESSTYPE=1",crit.ID);
if(dr.Read())
mMailToAddress=Address.GetItem(dr);
if(dr!=null) dr.Close();
//Docs
dr=DBUtil.GetReaderFromSQLString("SELECT * FROM AASSIGNEDDOC WHERE (aRootObjectID=@ID AND aRootObjectType=3);",crit.ID);
mDocs = AssignedDocs.GetItems(dr, RootObjectTypes.Client, RootObjectTypes.Client);
if(dr!=null) dr.Close();
}
finally
{
if(dr!=null) dr.Close();
if(crit.TrackMRU)
if(AyaBizUtils.AllowAutomaticMRUOnUpdate) AyaBizUtils.MRU.Add(RootObjectTypes.Client, mID);
}
MarkOld();
//Get access rights level
bReadOnly=AyaBizUtils.Right("Object.Client")<(int)SecurityLevelTypes.ReadWrite;
}
#endregion
#region Update
/// <summary>
/// Called by DataPortal to delete/add/update data into the database
/// </summary>
protected override void DataPortal_Update()
{
// If not a new record, check if record was modified
//by another user since original retrieval:
if(!IsNew)
DBUtil.CheckSafeToUpdate(this.mModified.Date,this.mID,"aClient");
#region Delete
if(IsDeleted)
{
if(!IsNew)
{
//Delete object and child objects
DBCommandWrapper cmDelete = DBUtil.GetCommandFromSQL("DELETE FROM aClient WHERE aID = @ID;");
cmDelete.AddInParameter("@ID",DbType.Guid,this.mID);
//Delete all address record types with matching root object ID
DBCommandWrapper cmDeleteAddress = DBUtil.GetCommandFromSQL("DELETE FROM AADDRESS WHERE aRootObjectID = @ID;");
cmDeleteAddress.AddInParameter("@ID",DbType.Guid,this.mID);
//case 3598
//Delete all User records that are client type for this client
DBCommandWrapper cmDeleteUser = DBUtil.GetCommandFromSQL("DELETE FROM AUSER WHERE ACLIENTID = @ID;");
cmDeleteUser.AddInParameter("@ID", DbType.Guid, this.mID);
//case 3600
//Delete all User records that are client type for this client
DBCommandWrapper cmDeleteNotes = DBUtil.GetCommandFromSQL("DELETE FROM ACLIENTNOTE WHERE ACLIENTID = @ID;");
cmDeleteNotes.AddInParameter("@ID", DbType.Guid, this.mID);
//case 3601
//Delete all User records that are client type for this client
DBCommandWrapper cmDeleteCsr = DBUtil.GetCommandFromSQL("DELETE FROM ACLIENTSERVICEREQUEST WHERE ACLIENTID = @ID;");
cmDeleteCsr.AddInParameter("@ID", DbType.Guid, this.mID);
//case 3602
DBCommandWrapper cmClearDropShipOnPO = DBUtil.GetCommandFromSQL("UPDATE APURCHASEORDER SET ADROPSHIPTOCLIENTID = null WHERE ADROPSHIPTOCLIENTID = @ID");
cmClearDropShipOnPO.AddInParameter("@ID", DbType.Guid, this.mID);
using (IDbConnection connection = DBUtil.DB.GetConnection())
{
connection.Open();
IDbTransaction transaction = connection.BeginTransaction();
try
{
DBUtil.RemoveKeywords(transaction,RootObjectTypes.Client,this.mID);
DBUtil.RemoveDocs(transaction,RootObjectTypes.Client,this.mID);
DBUtil.DB.ExecuteNonQuery(cmDeleteAddress, transaction);
DBUtil.DB.ExecuteNonQuery(cmDeleteUser, transaction);//case 3598
DBUtil.DB.ExecuteNonQuery(cmDeleteNotes, transaction);//case 3600
DBUtil.DB.ExecuteNonQuery(cmDeleteCsr, transaction);//case 3601
DBUtil.DB.ExecuteNonQuery(cmClearDropShipOnPO, transaction);//case 3602
DBUtil.DB.ExecuteNonQuery(cmDelete, transaction);
// Commit the transaction
transaction.Commit();
}
catch
{
// Rollback transaction
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
}
//Remove any events for this object
if (AyaBizUtils.GlobalSettings.UseNotification)//Case 510
{
NotifyEvent.RemoveAllEventsForObject(this.mID);
}
//-----------------------------
}
MarkNew();
return;
}
#endregion
#region Add / Update
//get modification time temporarily, if update succeeds then
//set to this time
System.DateTime dtModified = DBUtil.CurrentWorkingDateTime;
DBCommandWrapper cm = null;
if(IsNew)//Add or update?
cm=DBUtil.GetCommandFromSQL(
"INSERT INTO aClient (aID, aName, AACTIVE, aDispatchZoneID, aWebAddress, aPopUpNotes, " +
"aClientGroupID, aBillHeadOffice, aHeadOfficeID, aNotes, ADEFAULTSERVICETEMPLATEID, " +
"aRegionID, aTechNotes, AACCOUNTNUMBER, aCreated, aModified,aCreator,aModifier, " +
"aCustom1, aCustom2, aCustom3, aCustom4, aCustom5, aCustom6, aCustom7, aCustom8, aCustom9, aCustom0, " +
"aUsesBanking, aContractID, aContractExpires, aContactNotes, aContact, aPhone1, aPhone2, aPhone3, aPhone4, aPhone5, aEmail, " +
"aSendNotifications) " +
"VALUES (@ID,@Name,@Active,@DispatchZoneID,@WebAddress,@PopUpNotes, " +
"@ClientGroupID,@BillHeadOffice,@HeadOfficeID,@Notes,@DefaultServiceTemplateID, " +
"@RegionID,@TechNotes,@AccountNumber,@Created, @Modified, @CurrentUserID,@CurrentUserID, " +
"@Custom1,@Custom2,@Custom3,@Custom4,@Custom5,@Custom6,@Custom7,@Custom8,@Custom9,@Custom0, " +
"@UsesBanking, @ContractID, " +
"@ContractExpires, @ContactNotes, @Contact, @Phone1, @Phone2, @Phone3, @Phone4, @Phone5, @Email, @SendNotifications);"
);
else
cm=DBUtil.GetCommandFromSQL(
"UPDATE aClient SET aID=@ID, aName=@Name, AACTIVE=@Active, " +
"aDispatchZoneID=@DispatchZoneID, aWebAddress=@WebAddress, " +
"aPopUpNotes=@PopUpNotes, aClientGroupID=@ClientGroupID, " +
"aBillHeadOffice=@BillHeadOffice, " +
"aHeadOfficeID=@HeadOfficeID, aNotes=@Notes, " +
"ADEFAULTSERVICETEMPLATEID=@DefaultServiceTemplateID, " +
"aRegionID=@RegionID, aTechNotes=@TechNotes, " +
"AACCOUNTNUMBER=@AccountNumber, aModifier=@CurrentUserID, " +
"aModified=@Modified, aCustom1=@Custom1, " +
"aCustom2=@Custom2, aCustom3=@Custom3, aCustom4=@Custom4, " +
"aCustom5=@Custom5, aCustom6=@Custom6, " +
"aCustom7=@Custom7, aCustom8=@Custom8, aCustom9=@Custom9, " +
"aCustom0=@Custom0, aUsesBanking=@UsesBanking, " +
"aContractID=@ContractID, aContractExpires=@ContractExpires, " +
"aContactNotes=@ContactNotes, " +
"aContact=@Contact, aPhone1=@Phone1, aPhone2=@Phone2, aPhone3=@Phone3, aPhone4=@Phone4, aPhone5=@Phone5, aEmail=@Email, " +
"aSendNotifications=@SendNotifications " +
"WHERE aID=@ID;"
);
cm.AddInParameter("@ID",DbType.Guid,mID);
cm.AddInParameter("@Active",DbType.Boolean, mActive);
cm.AddLargeStringInParameter("@Notes", mNotes);
cm.AddInParameter("@DispatchZoneID",DbType.Guid, mDispatchZoneID);
cm.AddInParameter("@RegionID",DbType.Guid, mRegionID);
cm.AddInParameter("@Name",DbType.String, mName);
cm.AddInParameter("@WebAddress",DbType.String, mWebAddress);
cm.AddLargeStringInParameter("@PopUpNotes", mPopUpNotes);
cm.AddInParameter("@ClientGroupID",DbType.Guid,mClientGroupID);
cm.AddInParameter("@BillHeadOffice",DbType.Boolean, mBillHeadOffice);
cm.AddInParameter("@HeadOfficeID",DbType.Guid,mHeadOfficeID);
cm.AddInParameter("@DefaultServiceTemplateID",DbType.Guid,mDefaultServiceTemplateID);
cm.AddLargeStringInParameter("@TechNotes", mTechNotes);
cm.AddInParameter("@AccountNumber",DbType.String, mAccountNumber);
cm.AddInParameter("@UsesBanking",DbType.Boolean, mUsesBanking);
cm.AddInParameter("@ContractID",DbType.Guid,mContractID);
//case 763
if(mContractExpires.IsEmpty)
mContractExpires.Date = new DateTime(2100, 1, 1);
cm.AddInParameter("@ContractExpires",DbType.DateTime, DBUtil.ToUTC(mContractExpires).DBValue);//case 863 was not converting to utc before saving
cm.AddLargeStringInParameter("@ContactNotes", mContactNotes);
cm.AddInParameter("@Contact", DbType.String, mContact);
cm.AddInParameter("@Phone1", DbType.String, mPhone1);
cm.AddInParameter("@Phone2", DbType.String, mPhone2);
cm.AddInParameter("@Phone3", DbType.String, mPhone3);
cm.AddInParameter("@Phone4", DbType.String, mPhone4);
cm.AddInParameter("@Phone5", DbType.String, mPhone5);
cm.AddInParameter("@Email", DbType.String, mEmail);
cm.AddInParameter("@SendNotifications", DbType.Boolean, mSendNotifications);
//Standard fields
cm.AddInParameter("@CurrentUserID",DbType.Guid, CurrentUserID);
cm.AddInParameter("@Created",DbType.DateTime, DBUtil.ToUTC(mCreated).DBValue);
cm.AddInParameter("@Modified",DbType.DateTime, DBUtil.ToUTC(dtModified));
//Custom fields
cm.AddLargeStringInParameter("@Custom1", mCustom1);
cm.AddLargeStringInParameter("@Custom2", mCustom2);
cm.AddLargeStringInParameter("@Custom3", mCustom3);
cm.AddLargeStringInParameter("@Custom4", mCustom4);
cm.AddLargeStringInParameter("@Custom5", mCustom5);
cm.AddLargeStringInParameter("@Custom6", mCustom6);
cm.AddLargeStringInParameter("@Custom7", mCustom7);
cm.AddLargeStringInParameter("@Custom8", mCustom8);
cm.AddLargeStringInParameter("@Custom9", mCustom9);
cm.AddLargeStringInParameter("@Custom0", mCustom0);
using (IDbConnection connection = DBUtil.DB.GetConnection())
{
connection.Open();
IDbTransaction transaction = connection.BeginTransaction();
try
{
DBUtil.DB.ExecuteNonQuery(cm, transaction);
//Update child objects
//GoToAddress
mGoToAddress.Update(RootObjectTypes.Client,mID,AddressTypes.Physical,transaction);
//MailToAddress
mMailToAddress.Update(RootObjectTypes.Client,mID,AddressTypes.Postal,transaction);
//Docs
mDocs.Update(transaction);
//Process keywords
DBUtil.ProcessKeywords(transaction,this.mID,RootObjectTypes.Client,IsNew,AyaBizUtils.Break(false,
mAccountNumber,mGoToAddress.FullAddress,mMailToAddress.FullAddress,
mName,mNotes,mPopUpNotes,mTechNotes,mWebAddress, mContactNotes,
mContact, mPhone1, mPhone2, mPhone3, mPhone4, mPhone5, mEmail,
/*Custom fields*/
mCustom1,mCustom2,mCustom3,mCustom4,mCustom5,mCustom6,mCustom7,mCustom8,mCustom9,mCustom0));
MarkOld();//db is now synched with object
// Commit the transaction
transaction.Commit();
}
catch
{
// Rollback transaction
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
//Successful update so
//change modification time to match
this.mModified.Date=dtModified;
if (AyaBizUtils.AllowAutomaticMRUOnUpdate)
{
AyaBizUtils.MRU.Add(RootObjectTypes.Client, mID);
//Test with DP:
//calling save here *does* save it for a dp connection
//so need to call save inside dp if using dp every transaction
// And AyaNova needs to use fresh MRU every time so
//Ayabizutils should always provide fresh no caching if it's a dp
//in use AyaBizUtils.MRU.Save();
}
//Process events as necessary
if (AyaBizUtils.GlobalSettings.UseNotification)//Case 510
{
//Contract expires event changed?
if(this.mContractExpiryChanged)
{
if(this.mContractExpires.IsEmpty)
NotifyEvent.RemoveSpecificEventForObject(this.mID,(int)ClientEvent.ContractExpire);
else
NotifyEvent.AddOrUpdateEvent(RootObjectTypes.Client,this.mID,(int)ClientEvent.ContractExpire,Guid.Empty,this.mContractExpires,Guid.Empty);
}
}
//case 3701 set pm's inactive if client is now inactive
if (this.mActiveChanged && this.mActive == false)
{
//because firebird doesn't support updating through a join statement
//Need to fetch as a list object first then update them all...
//Find all PM's for this client
string pmListCriteria = "<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?> \r\n" +
"<GRIDCRITERIA> \r\n" +
" <COLUMNITEM CM=\"aWorkorderPreventiveMaintenance.aPreventiveMaintenanceNumber\" UI=\"LT_O_WorkorderPreventiveMaintenance\" PIN=\"0\" WIDTH=\"150\" SORT=\"DESC\" /> \r\n" +
" <WHEREITEMGROUP GROUPLOGICALOPERATOR=\"And\" UI=\"LT_O_Client\"> \r\n" +
" <WHEREITEM COMPAREOPERATOR=\"Equals\" CM=\"aClient.aID\" UICOMPAREVALUE=\"ABC Accounting\" TYPE=\"System.Guid\" COMPAREVALUE=\"{" + mID.ToString().ToUpper() + "}\" /> \r\n" +
" </WHEREITEMGROUP> \r\n" +
"</GRIDCRITERIA> ";
var wopm = WorkorderPMList.GetList(pmListCriteria);
if (wopm.Count > 0)
{
foreach (WorkorderPMList.WorkorderPMListInfo i in wopm)
{
if (i.LT_O_WorkorderPreventiveMaintenance.Value != Guid.Empty)
{
DBCommandWrapper cmPM = DBUtil.GetCommandFromSQL(
"UPDATE " +
" AWORKORDERPREVENTIVEMAINTENANCE " +
" SET " +
" AACTIVE=0 " +
" WHERE AWORKORDERID=@PMID "
);
cmPM.AddInParameter("@PMID", DbType.Guid, i.LT_O_WorkorderPreventiveMaintenance.Value);
DBUtil.DB.ExecuteNonQuery(cmPM);
}
}
}
}
}
#endregion
}
#endregion
#region Delete
/// <summary>
/// Remove a Client record .
/// </summary>
/// <param name="Criteria"></param>
protected override void DataPortal_Delete(object Criteria)
{
Criteria crit = (Criteria)Criteria;
//Delete object and child objects
DBCommandWrapper cmDelete = DBUtil.GetCommandFromSQL("DELETE FROM aClient WHERE aID = @ID;");
cmDelete.AddInParameter("@ID",DbType.Guid,crit.ID);
//Delete all address record types with matching root object ID
DBCommandWrapper cmDeleteAddress = DBUtil.GetCommandFromSQL("DELETE FROM AADDRESS WHERE aRootObjectID = @ID;");
cmDeleteAddress.AddInParameter("@ID",DbType.Guid,crit.ID);
//case 3598
//Delete all User records that are client type for this client
DBCommandWrapper cmDeleteUser = DBUtil.GetCommandFromSQL("DELETE FROM AUSER WHERE ACLIENTID = @ID;");
cmDeleteUser.AddInParameter("@ID", DbType.Guid, crit.ID);
//case 3600
//Delete all User records that are client type for this client
DBCommandWrapper cmDeleteNotes = DBUtil.GetCommandFromSQL("DELETE FROM ACLIENTNOTE WHERE ACLIENTID = @ID;");
cmDeleteNotes.AddInParameter("@ID", DbType.Guid, crit.ID);
//case 3601
//Delete all User records that are client type for this client
DBCommandWrapper cmDeleteCsr = DBUtil.GetCommandFromSQL("DELETE FROM ACLIENTSERVICEREQUEST WHERE ACLIENTID = @ID;");
cmDeleteCsr.AddInParameter("@ID", DbType.Guid, crit.ID);
//case 3602
DBCommandWrapper cmClearDropShipOnPO = DBUtil.GetCommandFromSQL("UPDATE APURCHASEORDER SET ADROPSHIPTOCLIENTID = null WHERE ADROPSHIPTOCLIENTID = @ID");
cmClearDropShipOnPO.AddInParameter("@ID", DbType.Guid, crit.ID);
using (IDbConnection connection = DBUtil.DB.GetConnection())
{
connection.Open();
IDbTransaction transaction = connection.BeginTransaction();
try
{
DBUtil.RemoveKeywords(transaction,RootObjectTypes.Client,crit.ID);
DBUtil.RemoveDocs(transaction,RootObjectTypes.Client,crit.ID);
DBUtil.DB.ExecuteNonQuery(cmDeleteAddress, transaction);
DBUtil.DB.ExecuteNonQuery(cmDeleteUser, transaction);//case 3598
DBUtil.DB.ExecuteNonQuery(cmDeleteNotes, transaction);//case 3600
DBUtil.DB.ExecuteNonQuery(cmDeleteCsr, transaction);//case 3601
DBUtil.DB.ExecuteNonQuery(cmClearDropShipOnPO, transaction);//case 3602
DBUtil.DB.ExecuteNonQuery(cmDelete, transaction);
// Commit the transaction
transaction.Commit();
}
catch
{
// Rollback transaction
transaction.Rollback();
throw;
}
finally
{
connection.Close();
AyaBizUtils.MRU.Remove(RootObjectTypes.Client, crit.ID);
}
//Remove any events for this object
if (AyaBizUtils.GlobalSettings.UseNotification)//Case 510
{
NotifyEvent.RemoveAllEventsForObject(crit.ID);
}
}
}
#endregion
#endregion
#region Override IsValid / IsDirty
//Override base class version if there are child objects
/// <summary>
///
/// </summary>
public override bool IsValid
{
get
{
return base.IsValid &&
mGoToAddress.IsValid && mMailToAddress.IsValid &&
mDocs.IsValid;
}
}
/// <summary>
///
/// </summary>
public override bool IsDirty
{
get
{
return base.IsDirty ||
mGoToAddress.IsDirty || mMailToAddress.IsDirty
|| mDocs.IsDirty;
}
}
#endregion
#region criteria
/// <summary>
/// Criteria for identifying existing object
/// </summary>
[Serializable]
private class Criteria
{
public Guid ID;
public bool TrackMRU;
public Criteria(Guid _ID, bool _TrackMRU)
{
ID = _ID;
TrackMRU = _TrackMRU;
}
}
#endregion
#region Exists
//case 496
//[Serializable(), System.ComponentModel.Browsable(false)]
// public class ExistsHelper
//{
// bool _Exists = false;
// Guid _ID;
// string _Name;
// public ExistsHelper(Guid ID, string Name)
// {
// _ID=ID;
// _Name=Name;
// }
// public static bool GetExists(Guid ID, string Name)
// {
// ExistsHelper e=new ExistsHelper(ID,Name);
// DataPortal.Update(e);
// return e._Exists;
// }
// public void DataPortal_Update()
// {
// if(_Name!=null && _Name!="")
// {
// DBCommandWrapper dbCommandWrapper = DBUtil.DB.GetSqlStringCommandWrapper(
// "SELECT aID FROM aClient WHERE " +
// "(aName = @ANAME)"
// );
// dbCommandWrapper.AddInParameter("@ANAME",DbType.String,_Name);
// if(DBUtil.ToGuid(DBUtil.DB.ExecuteScalar(dbCommandWrapper))==Guid.Empty)
// this._Exists=false;
// else
// this._Exists=true;
// }
// else
// {
// if(DBUtil.ToGuid(DBUtil.GetScalarFromSQLString(
// "SELECT aID FROM aClient WHERE " +
// "(aID = @ID)",_ID
// ))==Guid.Empty)
// this._Exists=false;
// else
// this._Exists=true;
// }
// }
//}
#endregion
}//end Client
#region Notification events
/// <summary>
///
/// </summary>
public enum ClientEvent : int
{
/// <summary>
///
/// </summary>
[Description("LT:Client.Label.Event.ContractExpire")] ContractExpire=256
}
#endregion
}//end namespace GZTW.AyaNova.BLL