PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/CmsData/Person.cs

https://bitbucket.org/mahalowe/bvcms
C# | 1188 lines | 1125 code | 25 blank | 38 comment | 371 complexity | febd0f15229b05f3f0445a5883123e87 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, Apache-2.0, BSD-3-Clause, LGPL-2.1, MPL-2.0-no-copyleft-exception, AGPL-3.0
  1. /* Author: David Carroll
  2. * Copyright (c) 2008, 2009 Bellevue Baptist Church
  3. * Licensed under the GNU General Public License (GPL v2)
  4. * you may not use this code except in compliance with the License.
  5. * You may obtain a copy of the License at http://bvcms.codeplex.com/license
  6. */
  7. using System;
  8. using System.Linq;
  9. using UtilityExtensions;
  10. using System.Text;
  11. using System.Data.Linq;
  12. using System.Data.Linq.Mapping;
  13. using System.Data;
  14. using System.Collections.Generic;
  15. using System.Reflection;
  16. using System.Linq.Expressions;
  17. using System.ComponentModel;
  18. using System.Transactions;
  19. using System.Text.RegularExpressions;
  20. using System.Threading;
  21. using System.Data.Linq.SqlClient;
  22. using System.Web;
  23. using CmsData.Codes;
  24. namespace CmsData
  25. {
  26. public partial class Person
  27. {
  28. public static int[] DiscClassStatusCompletedCodes = new int[]
  29. {
  30. NewMemberClassStatusCode.AdminApproval,
  31. NewMemberClassStatusCode.Attended,
  32. NewMemberClassStatusCode.ExemptedChild
  33. };
  34. public static int[] DropCodesThatDrop = new int[]
  35. {
  36. DropTypeCode.Administrative,
  37. DropTypeCode.AnotherDenomination,
  38. DropTypeCode.LetteredOut,
  39. DropTypeCode.Requested,
  40. DropTypeCode.Other,
  41. };
  42. public DateTime Now()
  43. {
  44. return Util.Now;
  45. }
  46. /* Origins
  47. 10 Visit Worship or BFClass Visit
  48. 30 Referral see Request
  49. 40 Request Task, use this for Referral too
  50. 50 Deacon Telephone Contact, type = phoned in
  51. 60 Survey (EE) Contact, EE
  52. 70 Enrollment Member of org
  53. 80 Membership Decision Contact, Type=Worship Visit
  54. 90 Contribution -1 peopleid in Excel with Name?
  55. 98 Other Task, use task description
  56. */
  57. public string CityStateZip
  58. {
  59. get { return Util.FormatCSZ4(PrimaryCity, PrimaryState, PrimaryZip); }
  60. }
  61. public string CityStateZip5
  62. {
  63. get { return Util.FormatCSZ(PrimaryCity, PrimaryState, PrimaryZip); }
  64. }
  65. public string AddrCityStateZip
  66. {
  67. get { return PrimaryAddress + " " + CityStateZip; }
  68. }
  69. public string Addr2CityStateZip
  70. {
  71. get { return PrimaryAddress2 + " " + CityStateZip; }
  72. }
  73. public string FullAddress
  74. {
  75. get
  76. {
  77. var sb = new StringBuilder(PrimaryAddress + "\n");
  78. if (PrimaryAddress2.HasValue())
  79. sb.AppendLine(PrimaryAddress2);
  80. sb.Append(CityStateZip);
  81. return sb.ToString();
  82. }
  83. }
  84. public string SpouseName(CMSDataContext Db)
  85. {
  86. if (SpouseId.HasValue)
  87. {
  88. var q = from p in Db.People
  89. where p.PeopleId == SpouseId
  90. select p.Name;
  91. return q.SingleOrDefault();
  92. }
  93. return "";
  94. }
  95. public DateTime? BirthDate
  96. {
  97. get
  98. {
  99. DateTime dt;
  100. if (DateTime.TryParse(DOB, out dt))
  101. return dt;
  102. return null;
  103. }
  104. }
  105. public string DOB
  106. {
  107. get
  108. { return Util.FormatBirthday(BirthYear, BirthMonth, BirthDay); }
  109. set
  110. {
  111. // reset all values before replacing b/c replacement may be partial
  112. BirthDay = null;
  113. BirthMonth = null;
  114. BirthYear = null;
  115. DateTime dt;
  116. if (DateTime.TryParse(value, out dt))
  117. {
  118. BirthDay = dt.Day;
  119. BirthMonth = dt.Month;
  120. if (Regex.IsMatch(value, @"\d+/\d+/\d+"))
  121. BirthYear = dt.Year;
  122. }
  123. else
  124. {
  125. int n;
  126. if (int.TryParse(value, out n))
  127. if (n >= 1 && n <= 12)
  128. BirthMonth = n;
  129. else
  130. BirthYear = n;
  131. }
  132. }
  133. }
  134. public DateTime? GetBirthdate()
  135. {
  136. DateTime dt;
  137. if (DateTime.TryParse(DOB, out dt))
  138. return dt;
  139. return null;
  140. }
  141. public int GetAge()
  142. {
  143. int years;
  144. var dt0 = GetBirthdate();
  145. if (!dt0.HasValue)
  146. return -1;
  147. var dt = dt0.Value;
  148. years = Util.Now.Year - dt.Year;
  149. if (Util.Now.Month < dt.Month || (Util.Now.Month == dt.Month && Util.Now.Day < dt.Day))
  150. years--;
  151. return years;
  152. }
  153. public void MovePersonStuff(CMSDataContext Db, int otherid)
  154. {
  155. var toperson = Db.People.Single(p => p.PeopleId == otherid);
  156. foreach (var om in this.OrganizationMembers)
  157. {
  158. var om2 = OrganizationMember.InsertOrgMembers(Db, om.OrganizationId, otherid, om.MemberTypeId, om.EnrollmentDate.Value, om.InactiveDate, om.Pending ?? false);
  159. Db.UpdateMainFellowship(om.OrganizationId);
  160. om2.CreatedBy = om.CreatedBy;
  161. om2.CreatedDate = om.CreatedDate;
  162. om2.AttendPct = om.AttendPct;
  163. om2.AttendStr = om.AttendStr;
  164. om2.LastAttended = om.LastAttended;
  165. om2.Request = om.Request;
  166. om2.Grade = om.Grade;
  167. om2.Amount = om.Amount;
  168. om2.RegisterEmail = om.RegisterEmail;
  169. om2.ShirtSize = om.ShirtSize;
  170. om2.Tickets = om.Tickets;
  171. om2.UserData = om.UserData;
  172. Db.SubmitChanges();
  173. foreach (var m in om.OrgMemMemTags)
  174. if (!om2.OrgMemMemTags.Any(mm => mm.MemberTagId == m.MemberTagId))
  175. om2.OrgMemMemTags.Add(new OrgMemMemTag { MemberTagId = m.MemberTagId });
  176. Db.SubmitChanges();
  177. Db.OrgMemMemTags.DeleteAllOnSubmit(om.OrgMemMemTags);
  178. Db.SubmitChanges();
  179. }
  180. Db.OrganizationMembers.DeleteAllOnSubmit(this.OrganizationMembers);
  181. Db.SubmitChanges();
  182. foreach (var et in this.EnrollmentTransactions)
  183. et.PeopleId = otherid;
  184. Db.SubmitChanges();
  185. var q = from a in Db.Attends
  186. where a.PeopleId == this.PeopleId
  187. let oa = Db.Attends.SingleOrDefault(a2 => a2.MeetingId == a.MeetingId && a2.PeopleId == otherid)
  188. where oa == null
  189. select a;
  190. var list = q.ToList();
  191. foreach (var a in list)
  192. {
  193. a.PeopleId = otherid;
  194. Db.SubmitChanges();
  195. }
  196. foreach (var c in this.Contributions)
  197. c.PeopleId = otherid;
  198. foreach (var u in this.Users)
  199. u.PeopleId = otherid;
  200. if (this.Volunteers.Any() && !toperson.Volunteers.Any())
  201. foreach (var v in this.Volunteers)
  202. {
  203. var vv = new Volunteer
  204. {
  205. PeopleId = otherid,
  206. Children = v.Children,
  207. Comments = v.Comments,
  208. Leader = v.Leader,
  209. ProcessedDate = v.ProcessedDate,
  210. Standard = v.Standard,
  211. StatusId = v.StatusId,
  212. };
  213. Db.Volunteers.InsertOnSubmit(vv);
  214. }
  215. foreach (var v in this.VolunteerForms)
  216. v.PeopleId = otherid;
  217. foreach (var c in this.contactsMade)
  218. {
  219. var cp = Db.Contactors.SingleOrDefault(c2 => c2.PeopleId == otherid && c.ContactId == c2.ContactId);
  220. if (cp == null)
  221. c.contact.contactsMakers.Add(new Contactor { PeopleId = otherid });
  222. Db.Contactors.DeleteOnSubmit(c);
  223. }
  224. foreach (var c in this.contactsHad)
  225. {
  226. var cp = Db.Contactees.SingleOrDefault(c2 => c2.PeopleId == otherid && c.ContactId == c2.ContactId);
  227. if (cp == null)
  228. c.contact.contactees.Add(new Contactee { PeopleId = otherid });
  229. Db.Contactees.DeleteOnSubmit(c);
  230. }
  231. foreach (var e in this.PeopleExtras)
  232. {
  233. var cp = Db.PeopleExtras.FirstOrDefault(c2 => c2.PeopleId == otherid && c2.Field == e.Field);
  234. var e2 = new PeopleExtra
  235. {
  236. PeopleId = otherid,
  237. Field = e.Field,
  238. Data = e.Data,
  239. StrValue = e.StrValue,
  240. DateValue = e.DateValue,
  241. IntValue = e.IntValue,
  242. IntValue2 = e.IntValue2,
  243. TransactionTime = e.TransactionTime
  244. };
  245. if (cp != null)
  246. e2.Field = e.Field + "_mv";
  247. Db.PeopleExtras.InsertOnSubmit(e2);
  248. Db.PeopleExtras.DeleteOnSubmit(e);
  249. }
  250. var torecreg = toperson.RecRegs.SingleOrDefault();
  251. var frrecreg = RecRegs.SingleOrDefault();
  252. if (torecreg == null && frrecreg != null)
  253. frrecreg.PeopleId = otherid;
  254. if (torecreg != null && frrecreg != null)
  255. {
  256. torecreg.Comments = frrecreg.Comments + "\n" + torecreg.Comments;
  257. if (frrecreg.ShirtSize.HasValue())
  258. torecreg.ShirtSize = frrecreg.ShirtSize;
  259. if (frrecreg.MedicalDescription.HasValue())
  260. torecreg.MedicalDescription = frrecreg.MedicalDescription;
  261. if (frrecreg.Doctor.HasValue())
  262. torecreg.Doctor = frrecreg.Doctor;
  263. if (frrecreg.Docphone.HasValue())
  264. torecreg.Docphone = frrecreg.Docphone;
  265. if (frrecreg.MedAllergy.HasValue)
  266. torecreg.MedAllergy = frrecreg.MedAllergy;
  267. if (frrecreg.Tylenol.HasValue)
  268. torecreg.Tylenol = frrecreg.Tylenol;
  269. if (frrecreg.Robitussin.HasValue)
  270. torecreg.Robitussin = frrecreg.Robitussin;
  271. if (frrecreg.Advil.HasValue)
  272. torecreg.Advil = frrecreg.Advil;
  273. if (frrecreg.Maalox.HasValue)
  274. torecreg.Maalox = frrecreg.Maalox;
  275. if (frrecreg.Insurance.HasValue())
  276. torecreg.Insurance = frrecreg.Insurance;
  277. if (frrecreg.Policy.HasValue())
  278. torecreg.Policy = frrecreg.Policy;
  279. if (frrecreg.Mname.HasValue())
  280. torecreg.Mname = frrecreg.Mname;
  281. if (frrecreg.Fname.HasValue())
  282. torecreg.Fname = frrecreg.Fname;
  283. if (frrecreg.Emcontact.HasValue())
  284. torecreg.Emcontact = frrecreg.Emcontact;
  285. if (frrecreg.Emphone.HasValue())
  286. torecreg.Emphone = frrecreg.Emphone;
  287. if (frrecreg.ActiveInAnotherChurch.HasValue)
  288. torecreg.ActiveInAnotherChurch = frrecreg.ActiveInAnotherChurch;
  289. }
  290. var mg = Db.ManagedGivings.FirstOrDefault(mm => mm.PeopleId == otherid);
  291. if (mg != null)
  292. foreach (var v in this.ManagedGivings)
  293. {
  294. var qq = from ra in Db.RecurringAmounts
  295. where ra.PeopleId == PeopleId
  296. select ra;
  297. foreach (var ra in qq)
  298. ra.PeopleId = otherid;
  299. v.PeopleId = otherid;
  300. }
  301. var pi = Db.PaymentInfos.FirstOrDefault(mm => mm.PeopleId == otherid);
  302. if (pi != null)
  303. foreach (var i in PaymentInfos)
  304. i.PeopleId = otherid;
  305. Db.SubmitChanges();
  306. }
  307. public bool PurgePerson(CMSDataContext Db)
  308. {
  309. try
  310. {
  311. Db.PurgePerson(PeopleId);
  312. }
  313. catch
  314. {
  315. return false;
  316. }
  317. return true;
  318. }
  319. public bool Deceased
  320. {
  321. get { return DeceasedDate.HasValue; }
  322. }
  323. public string FromEmail
  324. {
  325. get { return Util.FullEmail(EmailAddress, Name); }
  326. }
  327. public string FromEmail2
  328. {
  329. get { return Util.FullEmail(EmailAddress2, Name); }
  330. }
  331. public static void NameSplit(string name, out string First, out string Last)
  332. {
  333. First = "";
  334. Last = "";
  335. if (!name.HasValue())
  336. return;
  337. var a = name.Trim().Split(' ');
  338. if (a.Length > 1)
  339. {
  340. First = a[0];
  341. Last = a[1];
  342. }
  343. else
  344. Last = a[0];
  345. }
  346. public static Person Add(Family fam, int position, Tag tag, string name, string dob, bool Married, int gender, int originId, int? EntryPointId)
  347. {
  348. string First, Last;
  349. NameSplit(name, out First, out Last);
  350. if (!First.HasValue() || Married)
  351. switch (gender)
  352. {
  353. case 0: First = "A"; break;
  354. case 1: if (!First.HasValue()) First = "Husbander"; break;
  355. case 2: First = "Wifey"; break;
  356. }
  357. return Add(fam, position, tag, First, null, Last, dob, Married, gender, originId, EntryPointId);
  358. }
  359. public static Person Add(Family fam,
  360. int position,
  361. Tag tag,
  362. string firstname,
  363. string nickname,
  364. string lastname,
  365. string dob,
  366. int MarriedCode,
  367. int gender,
  368. int originId,
  369. int? EntryPointId)
  370. {
  371. return Person.Add(DbUtil.Db, true, fam, position, tag, firstname, nickname, lastname, dob, MarriedCode, gender, originId, EntryPointId);
  372. }
  373. public static Person Add(CMSDataContext Db, Family fam, string firstname, string nickname, string lastname, DateTime? dob)
  374. {
  375. return Person.Add(Db, false, fam, 20, null, firstname, nickname, lastname, dob.FormatDate(), 0, 0, 0, 0);
  376. }
  377. public static Person Add(CMSDataContext Db, bool SendNotices, Family fam, int position, Tag tag, string firstname, string nickname, string lastname, string dob, int MarriedCode, int gender, int originId, int? EntryPointId, bool testing = false)
  378. {
  379. var p = new Person();
  380. p.CreatedDate = Util.Now;
  381. p.CreatedBy = Util.UserId;
  382. Db.People.InsertOnSubmit(p);
  383. p.PositionInFamilyId = position;
  384. p.AddressTypeId = 10;
  385. if (firstname.HasValue())
  386. p.FirstName = firstname.Trim().ToProper().Truncate(25);
  387. else
  388. p.FirstName = "";
  389. if (nickname.HasValue())
  390. p.NickName = nickname.Trim().ToProper().Truncate(15);
  391. if (lastname.HasValue())
  392. p.LastName = lastname.Trim().ToProper().Truncate(30);
  393. else
  394. p.LastName = "?";
  395. p.GenderId = gender;
  396. if (p.GenderId == 99)
  397. p.GenderId = 0;
  398. p.MaritalStatusId = MarriedCode;
  399. DateTime dt;
  400. if (Util.DateValid(dob, out dt))
  401. {
  402. while (dt.Year < 1900)
  403. dt = dt.AddYears(100);
  404. if (dt > Util.Now)
  405. dt = dt.AddYears(-100);
  406. p.BirthDay = dt.Day;
  407. p.BirthMonth = dt.Month;
  408. p.BirthYear = dt.Year;
  409. if (p.GetAge() < 18 && MarriedCode == 0)
  410. p.MaritalStatusId = MaritalStatusCode.Single;
  411. }
  412. else if (DateTime.TryParse(dob, out dt))
  413. {
  414. p.BirthDay = dt.Day;
  415. p.BirthMonth = dt.Month;
  416. if (Regex.IsMatch(dob, @"\d+[-/]\d+[-/]\d+"))
  417. {
  418. p.BirthYear = dt.Year;
  419. while (p.BirthYear < 1900)
  420. p.BirthYear += 100;
  421. if (p.GetAge() < 18 && MarriedCode == 0)
  422. p.MaritalStatusId = MaritalStatusCode.Single;
  423. }
  424. }
  425. p.MemberStatusId = MemberStatusCode.JustAdded;
  426. if (fam == null)
  427. {
  428. fam = new Family();
  429. Db.Families.InsertOnSubmit(fam);
  430. p.Family = fam;
  431. }
  432. else
  433. fam.People.Add(p);
  434. var PrimaryCount = fam.People.Where(c => c.PositionInFamilyId == PositionInFamily.PrimaryAdult).Count();
  435. if (PrimaryCount > 2 && p.PositionInFamilyId == PositionInFamily.PrimaryAdult)
  436. p.PositionInFamilyId = PositionInFamily.SecondaryAdult;
  437. if (tag != null)
  438. tag.PersonTags.Add(new TagPerson { Person = p });
  439. p.OriginId = originId;
  440. p.EntryPointId = EntryPointId;
  441. p.FixTitle();
  442. if (!testing)
  443. Db.SubmitChanges();
  444. if (SendNotices)
  445. {
  446. if (Util.UserPeopleId.HasValue
  447. && Util.UserPeopleId.Value != Db.NewPeopleManagerId
  448. && !HttpContext.Current.User.IsInRole("OrgMembersOnly")
  449. && HttpContext.Current.User.IsInRole("Access"))
  450. Task.AddNewPerson(p.PeopleId);
  451. else
  452. Db.Email(Util.SysFromEmail, Db.GetNewPeopleManagers(),
  453. "Just Added Person on " + Db.Host, "{0} ({1})".Fmt(p.Name, p.PeopleId));
  454. }
  455. return p;
  456. }
  457. public static Person Add(Family fam, int position, Tag tag, string firstname, string nickname, string lastname, string dob, bool Married, int gender, int originId, int? EntryPointId)
  458. {
  459. return Add(fam, position, tag, firstname, nickname, lastname, dob, Married ? 20 : 10, gender, originId, EntryPointId);
  460. }
  461. public List<Duplicate> PossibleDuplicates()
  462. {
  463. var fone = Util.GetDigits(Util.PickFirst(CellPhone, HomePhone));
  464. using (var ctx = new CMSDataContext(Util.ConnectionString))
  465. {
  466. ctx.SetNoLock();
  467. string street = GetStreet(ctx) ?? "--";
  468. var nick = NickName ?? "--";
  469. var maid = MaidenName ?? "--";
  470. var em = EmailAddress ?? "--";
  471. if (!em.HasValue())
  472. em = "--";
  473. var bd = BirthDay ?? -1;
  474. var bm = BirthMonth ?? -1;
  475. var byr = BirthYear ?? -1;
  476. var q = from p in ctx.People
  477. let firstmatch = p.FirstName == FirstName || (p.NickName ?? "") == FirstName || (p.MiddleName ?? "") == FirstName
  478. || p.FirstName == nick || (p.NickName ?? "") == nick || (p.MiddleName ?? "") == nick
  479. let lastmatch = p.LastName == LastName || (p.MaidenName ?? "") == LastName
  480. || (p.MaidenName ?? "") == maid || p.LastName == maid
  481. let nobday = (p.BirthMonth == null && p.BirthYear == null && p.BirthDay == null)
  482. || (BirthMonth == null && BirthYear == null && BirthDay == null)
  483. let bdmatch = (p.BirthDay ?? -2) == bd && (p.BirthMonth ?? -2) == bm && (p.BirthYear ?? -2) == byr
  484. let bdmatchpart = (p.BirthDay ?? -2) == bd && (p.BirthMonth ?? -2) == bm
  485. let emailmatch = p.EmailAddress != null && p.EmailAddress == em
  486. let addrmatch = (p.AddressLineOne ?? "").Contains(street) || (p.Family.AddressLineOne ?? "").Contains(street)
  487. let phonematch = (p.CellPhoneLU == CellPhoneLU
  488. || p.CellPhoneLU == Family.HomePhoneLU
  489. || p.CellPhone == WorkPhoneLU
  490. || p.Family.HomePhoneLU == CellPhoneLU
  491. || p.Family.HomePhoneLU == Family.HomePhoneLU
  492. || p.Family.HomePhoneLU == WorkPhoneLU
  493. || p.WorkPhoneLU == CellPhoneLU
  494. || p.WorkPhoneLU == Family.HomePhoneLU
  495. || p.WorkPhoneLU == WorkPhoneLU)
  496. let samefamily = p.FamilyId == FamilyId
  497. let nmatches = samefamily ? 0 :
  498. (firstmatch ? 1 : 0)
  499. + (bdmatch ? 1 : 0)
  500. + (emailmatch ? 1 : 0)
  501. + (phonematch ? 1 : 0)
  502. + (addrmatch ? 1 : 0)
  503. where (lastmatch && nmatches >= 3)
  504. || ((firstmatch && lastmatch && bdmatchpart) && p.PeopleId != PeopleId)
  505. select new Duplicate
  506. {
  507. PeopleId = p.PeopleId,
  508. First = p.FirstName,
  509. Last = p.LastName,
  510. Nick = p.NickName,
  511. Middle = p.MiddleName,
  512. BMon = p.BirthMonth,
  513. BDay = p.BirthDay,
  514. BYear = p.BirthYear,
  515. Email = p.EmailAddress,
  516. FamAddr = p.Family.AddressLineOne,
  517. PerAddr = p.AddressLineOne,
  518. Member = p.MemberStatus.Description
  519. };
  520. var list = q.ToList();
  521. return list;
  522. }
  523. }
  524. public class Duplicate
  525. {
  526. public bool s0 { get; set; }
  527. public bool s1 { get; set; }
  528. public bool s2 { get; set; }
  529. public bool s3 { get; set; }
  530. public bool s4 { get; set; }
  531. public bool s5 { get; set; }
  532. public bool s6 { get; set; }
  533. public int PeopleId { get; set; }
  534. public string First { get; set; }
  535. public string Last { get; set; }
  536. public string Nick { get; set; }
  537. public string Middle { get; set; }
  538. public string Maiden { get; set; }
  539. public int? BMon { get; set; }
  540. public int? BDay { get; set; }
  541. public int? BYear { get; set; }
  542. public string Email { get; set; }
  543. public string FamAddr { get; set; }
  544. public string PerAddr { get; set; }
  545. public string Member { get; set; }
  546. }
  547. public List<Duplicate> PossibleDuplicates2()
  548. {
  549. using (var ctx = new CMSDataContext(Util.ConnectionString))
  550. {
  551. ctx.SetNoLock();
  552. string street = GetStreet(ctx) ?? "--";
  553. var nick = NickName ?? "--";
  554. var maid = MaidenName ?? "--";
  555. var em = EmailAddress ?? "--";
  556. if (!em.HasValue())
  557. em = "--";
  558. var bd = BirthDay ?? -1;
  559. var bm = BirthMonth ?? -1;
  560. var byr = BirthYear ?? -1;
  561. var q = from p in ctx.People
  562. let firstmatch = p.FirstName == FirstName || (p.NickName ?? "") == FirstName || (p.MiddleName ?? "") == FirstName
  563. || p.FirstName == nick || (p.NickName ?? "") == nick || (p.MiddleName ?? "") == nick
  564. let lastmatch = p.LastName == LastName || (p.MaidenName ?? "") == LastName
  565. || (p.MaidenName ?? "") == maid || p.LastName == maid
  566. let nobday = (p.BirthMonth == null && p.BirthYear == null && p.BirthDay == null)
  567. || (BirthMonth == null && BirthYear == null && BirthDay == null)
  568. let bdmatch = (p.BirthDay ?? -2) == bd && (p.BirthMonth ?? -2) == bm && (p.BirthYear ?? -2) == byr
  569. let bdmatchpart = (p.BirthDay ?? -2) == bd && (p.BirthMonth ?? -2) == bm
  570. let emailmatch = p.EmailAddress != null && p.EmailAddress == em
  571. let addrmatch = (p.AddressLineOne ?? "").Contains(street) || (p.Family.AddressLineOne ?? "").Contains(street)
  572. let s1 = firstmatch && bdmatchpart
  573. let s2 = firstmatch && bdmatch
  574. let s3 = firstmatch && lastmatch && nobday
  575. let s4 = firstmatch && addrmatch
  576. let s5 = firstmatch && emailmatch
  577. let s6 = lastmatch && bdmatch
  578. where p.FamilyId != FamilyId && (s1 || s2 || s3 || s4 || s5 || s6)
  579. select new Duplicate
  580. {
  581. s1 = s1,
  582. s2 = s2,
  583. s3 = s3,
  584. s4 = s4,
  585. s5 = s5,
  586. s6 = s6,
  587. PeopleId = p.PeopleId,
  588. First = p.FirstName,
  589. Last = p.LastName,
  590. Nick = p.NickName,
  591. Middle = p.MiddleName,
  592. BMon = p.BirthMonth,
  593. BDay = p.BirthDay,
  594. BYear = p.BirthYear,
  595. Email = p.EmailAddress,
  596. FamAddr = p.Family.AddressLineOne,
  597. PerAddr = p.AddressLineOne,
  598. Member = p.MemberStatus.Description
  599. };
  600. try
  601. {
  602. var list = q.ToList();
  603. var t = new Duplicate
  604. {
  605. s0 = true,
  606. PeopleId = PeopleId,
  607. First = FirstName,
  608. Last = LastName,
  609. Nick = NickName,
  610. Middle = MiddleName,
  611. BMon = BirthMonth,
  612. BDay = BirthDay,
  613. BYear = BirthYear,
  614. Email = EmailAddress,
  615. FamAddr = Family.AddressLineOne,
  616. PerAddr = AddressLineOne,
  617. Member = MemberStatus.Description
  618. };
  619. list.Insert(0, t);
  620. return list;
  621. }
  622. catch (Exception)
  623. {
  624. throw;
  625. }
  626. }
  627. }
  628. private string GetStreet(CMSDataContext db)
  629. {
  630. if (!PrimaryAddress.HasValue())
  631. return null;
  632. try
  633. {
  634. var s = PrimaryAddress.Replace(".", "");
  635. var a = s.SplitStr(" ");
  636. var la = a.ToList();
  637. if (la[0].AllDigits())
  638. la.RemoveAt(0);
  639. var quadrants = new string[] { "N", "NORTH", "S", "SOUTH", "E", "EAST", "W", "WEST", "NE", "NORTHEAST", "NW", "NORTHWEST", "SE", "SOUTHEAST", "SW", "SOUTHWEST" };
  640. if (quadrants.Contains(a[0].ToUpper()))
  641. la.RemoveAt(0);
  642. la.Reverse();
  643. if (la[0].AllDigits())
  644. la.RemoveAt(0);
  645. if (la[0].StartsWith("#"))
  646. la.RemoveAt(0);
  647. var apt = new string[] { "APARTMENT", "APT", "BUILDING", "BLDG", "DEPARTMENT", "DEPT", "FLOOR", "FL", "HANGAR", "HNGR", "LOT", "LOT", "PIER", "PIER", "ROOM", "RM", "SLIP", "SLIP", "SPACE", "SPC", "STOP", "STOP", "SUITE", "STE", "TRAILER", "TRLR", "UNIT", "UNIT", "UPPER", "UPPR",
  648. "BASEMENT","BSMT", "FRONT","FRNT", "LOBBY","LBBY", "LOWER","LOWR", "OFFICE","OFC", "PENTHOUSE","PH", "REAR", "SIDE" };
  649. if (apt.Contains(la[0].ToUpper()))
  650. la.RemoveAt(0);
  651. if (db.StreetTypes.Any(t => t.Type == la[0]))
  652. la.RemoveAt(0);
  653. la.Reverse();
  654. var street = string.Join(" ", la);
  655. return street;
  656. }
  657. catch (Exception)
  658. {
  659. return null;
  660. }
  661. }
  662. public void FixTitle()
  663. {
  664. if (GenderId == 1)
  665. TitleCode = "Mr.";
  666. else if (GenderId == 2)
  667. if (MaritalStatusId == 20 || MaritalStatusId == 50)
  668. TitleCode = "Mrs.";
  669. else
  670. TitleCode = "Ms.";
  671. }
  672. public string OptOutKey(string FromEmail)
  673. {
  674. return Util.EncryptForUrl("{0}|{1}".Fmt(PeopleId, FromEmail));
  675. }
  676. public static bool ToggleTag(int PeopleId, string TagName, int? OwnerId, int TagTypeId)
  677. {
  678. var Db = DbUtil.Db;
  679. var tag = Db.FetchOrCreateTag(TagName, OwnerId, TagTypeId);
  680. if (tag == null)
  681. throw new Exception("ToggleTag, tag '{0}' not found");
  682. var tp = Db.TagPeople.SingleOrDefault(t => t.Id == tag.Id && t.PeopleId == PeopleId);
  683. if (tp == null)
  684. {
  685. tag.PersonTags.Add(new TagPerson { PeopleId = PeopleId });
  686. return true;
  687. }
  688. Db.TagPeople.DeleteOnSubmit(tp);
  689. return false;
  690. }
  691. public static void Tag(CMSDataContext Db, int PeopleId, string TagName, int? OwnerId, int TagTypeId)
  692. {
  693. var tag = Db.FetchOrCreateTag(TagName, OwnerId, TagTypeId);
  694. var tp = Db.TagPeople.SingleOrDefault(t => t.Id == tag.Id && t.PeopleId == PeopleId);
  695. var isperson = Db.People.Count(p => p.PeopleId == PeopleId) > 0;
  696. if (tp == null && isperson)
  697. tag.PersonTags.Add(new TagPerson { PeopleId = PeopleId });
  698. }
  699. public static void UnTag(int PeopleId, string TagName, int? OwnerId, int TagTypeId)
  700. {
  701. var Db = DbUtil.Db;
  702. var tag = Db.FetchOrCreateTag(TagName, OwnerId, TagTypeId);
  703. var tp = Db.TagPeople.SingleOrDefault(t => t.Id == tag.Id && t.PeopleId == PeopleId);
  704. if (tp != null)
  705. Db.TagPeople.DeleteOnSubmit(tp);
  706. }
  707. partial void OnNickNameChanged()
  708. {
  709. if (NickName != null && NickName.Trim() == String.Empty)
  710. NickName = null;
  711. }
  712. private bool _DecisionTypeIdChanged;
  713. public bool DecisionTypeIdChanged
  714. {
  715. get { return _DecisionTypeIdChanged; }
  716. }
  717. partial void OnDecisionTypeIdChanged()
  718. {
  719. _DecisionTypeIdChanged = true;
  720. }
  721. private bool _NewMemberClassStatusIdChanged;
  722. public bool NewMemberClassStatusIdChanged
  723. {
  724. get { return _NewMemberClassStatusIdChanged; }
  725. }
  726. partial void OnNewMemberClassStatusIdChanged()
  727. {
  728. _NewMemberClassStatusIdChanged = true;
  729. }
  730. private bool _BaptismStatusIdChanged;
  731. public bool BaptismStatusIdChanged
  732. {
  733. get { return _BaptismStatusIdChanged; }
  734. }
  735. partial void OnBaptismStatusIdChanged()
  736. {
  737. _BaptismStatusIdChanged = true;
  738. }
  739. private bool _DeceasedDateChanged;
  740. public bool DeceasedDateChanged
  741. {
  742. get { return _DeceasedDateChanged; }
  743. }
  744. partial void OnDeceasedDateChanged()
  745. {
  746. _DeceasedDateChanged = true;
  747. }
  748. private bool _DropCodeIdChanged;
  749. public bool DropCodeIdChanged
  750. {
  751. get { return _DropCodeIdChanged; }
  752. }
  753. partial void OnDropCodeIdChanged()
  754. {
  755. _DropCodeIdChanged = true;
  756. }
  757. //internal static int FindResCode(string zipcode)
  758. //{
  759. // if (zipcode.HasValue() && zipcode.Length >= 5)
  760. // {
  761. // var z5 = zipcode.Substring(0, 5);
  762. // var z = DbUtil.Db.Zips.SingleOrDefault(zip => z5 == zip.ZipCode);
  763. // if (z == null)
  764. // return 30;
  765. // return z.MetroMarginalCode ?? 30;
  766. // }
  767. // return 30;
  768. //}
  769. private bool? _CanUserEditAll;
  770. public bool CanUserEditAll
  771. {
  772. get
  773. {
  774. if (!_CanUserEditAll.HasValue)
  775. _CanUserEditAll = HttpContext.Current.User.IsInRole("Edit");
  776. return _CanUserEditAll.Value;
  777. }
  778. }
  779. private bool? _CanUserEditFamilyAddress;
  780. public bool CanUserEditFamilyAddress
  781. {
  782. get
  783. {
  784. if (!_CanUserEditFamilyAddress.HasValue)
  785. _CanUserEditFamilyAddress = CanUserEditAll
  786. || Util.UserPeopleId == Family.HeadOfHouseholdId
  787. || Util.UserPeopleId == Family.HeadOfHouseholdSpouseId;
  788. return _CanUserEditFamilyAddress.Value;
  789. }
  790. }
  791. private bool? _CanUserEditBasic;
  792. public bool CanUserEditBasic
  793. {
  794. get
  795. {
  796. if (!_CanUserEditBasic.HasValue)
  797. _CanUserEditBasic = CanUserEditFamilyAddress
  798. || Util.UserPeopleId == PeopleId;
  799. return _CanUserEditBasic.Value;
  800. }
  801. }
  802. private bool? _CanUserSee;
  803. public bool CanUserSee
  804. {
  805. get
  806. {
  807. if (!_CanUserSee.HasValue)
  808. _CanUserSee = CanUserEditBasic
  809. || Family.People.Any(m => m.PeopleId == Util.UserPeopleId);
  810. return _CanUserSee.Value;
  811. }
  812. }
  813. //partial void OnZipCodeChanged()
  814. //{
  815. // ResCodeId = FindResCode(Db, ZipCode);
  816. //}
  817. //partial void OnAltZipCodeChanged()
  818. //{
  819. // AltResCodeId = FindResCode(Db, AltZipCode);
  820. //}
  821. public RecReg GetRecReg()
  822. {
  823. var rr = RecRegs.SingleOrDefault();
  824. if (rr == null)
  825. return new RecReg();
  826. return rr;
  827. }
  828. public RecReg SetRecReg()
  829. {
  830. var rr = RecRegs.SingleOrDefault();
  831. if (rr == null)
  832. {
  833. rr = new RecReg();
  834. RecRegs.Add(rr);
  835. }
  836. return rr;
  837. }
  838. public Contact AddContactReceived(CMSDataContext Db, DateTime dt, int type, int reason, string notes)
  839. {
  840. var c = new Contact
  841. {
  842. CreatedDate = Util.Now,
  843. CreatedBy = Util.UserId1,
  844. ContactDate = dt,
  845. ContactTypeId = type,
  846. ContactReasonId = reason,
  847. Comments = notes
  848. };
  849. Db.Contacts.InsertOnSubmit(c);
  850. c.contactees.Add(new Contactee { PeopleId = PeopleId });
  851. Db.SubmitChanges();
  852. return c;
  853. }
  854. private StringBuilder psbDefault;
  855. public void UpdateValue(string field, object value)
  856. {
  857. if (psbDefault == null)
  858. psbDefault = new StringBuilder();
  859. UpdateValue(psbDefault, field, value);
  860. }
  861. public void UpdateValue(StringBuilder psb, string field, object value)
  862. {
  863. if (value is string)
  864. value = ((string)value).TrimEnd();
  865. var o = Util.GetProperty(this, field);
  866. if (o is string)
  867. o = ((string)o).TrimEnd();
  868. if (o == null && value == null)
  869. return;
  870. if (o != null && o.Equals(value))
  871. return;
  872. if (o == null && value is string && !((string)value).HasValue())
  873. return;
  874. if (value == null && o is string && !((string)o).HasValue())
  875. return;
  876. psb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>\n", field, o, value ?? "(null)");
  877. Util.SetProperty(this, field, value);
  878. }
  879. public void UpdateValueFromText(StringBuilder psb, string field, string value)
  880. {
  881. value = value.TrimEnd();
  882. var o = Util.GetProperty(this, field);
  883. if (o is string)
  884. o = ((string)o).TrimEnd();
  885. if (o == null && value == null)
  886. return;
  887. if (o != null && o.Equals(value))
  888. return;
  889. if (o == null && value is string && !((string)value).HasValue())
  890. return;
  891. if (value == null && o is string && !((string)o).HasValue())
  892. return;
  893. psb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>\n", field, o, value ?? "(null)");
  894. Util.SetPropertyFromText(this, field, value);
  895. }
  896. public void LogChanges(CMSDataContext Db, int UserPeopleId)
  897. {
  898. if (psbDefault != null)
  899. LogChanges(Db, psbDefault, UserPeopleId);
  900. }
  901. public void LogChanges(CMSDataContext Db, StringBuilder psb, int UserPeopleId)
  902. {
  903. if (psb.Length > 0)
  904. {
  905. var c = new ChangeLog
  906. {
  907. UserPeopleId = UserPeopleId,
  908. PeopleId = PeopleId,
  909. Field = "Basic Info",
  910. Data = "<table>\n" + psb.ToString() + "</table>",
  911. Created = Util.Now
  912. };
  913. Db.ChangeLogs.InsertOnSubmit(c);
  914. }
  915. }
  916. public void LogPictureUpload(CMSDataContext Db, int UserPeopleId)
  917. {
  918. var c = new ChangeLog
  919. {
  920. UserPeopleId = UserPeopleId,
  921. PeopleId = PeopleId,
  922. Field = "Basic Info",
  923. Data = "<table>\n<tr><td>Picture</td><td></td><td>(new upload)</td></tr>\n</table>",
  924. Created = Util.Now
  925. };
  926. Db.ChangeLogs.InsertOnSubmit(c);
  927. }
  928. public override string ToString()
  929. {
  930. return Name + "(" + PeopleId + ")";
  931. }
  932. public void SetExtra(string field, string value)
  933. {
  934. var e = PeopleExtras.FirstOrDefault(ee => ee.Field == field);
  935. if (e == null)
  936. {
  937. e = new PeopleExtra { Field = field, PeopleId = PeopleId, TransactionTime = DateTime.Now };
  938. this.PeopleExtras.Add(e);
  939. }
  940. e.StrValue = value;
  941. }
  942. public string GetExtra(string field)
  943. {
  944. var e = PeopleExtras.SingleOrDefault(ee => ee.Field == field);
  945. if (e == null)
  946. return "";
  947. if (e.StrValue.HasValue())
  948. return e.StrValue;
  949. if (e.Data.HasValue())
  950. return e.Data;
  951. if (e.DateValue.HasValue)
  952. return e.DateValue.FormatDate();
  953. if (e.IntValue.HasValue)
  954. return e.IntValue.ToString();
  955. return e.BitValue.ToString();
  956. }
  957. public PeopleExtra GetExtraValue(string field)
  958. {
  959. if (!field.HasValue())
  960. field = "blank";
  961. field = field.Replace(",", "_");
  962. var ev = PeopleExtras.AsEnumerable().FirstOrDefault(ee => string.Compare(ee.Field, field, ignoreCase: true) == 0);
  963. if (ev == null)
  964. {
  965. ev = new PeopleExtra
  966. {
  967. Field = field,
  968. TransactionTime = DateTime.Now
  969. };
  970. PeopleExtras.Add(ev);
  971. }
  972. return ev;
  973. }
  974. public void RemoveExtraValue(CMSDataContext Db, string field)
  975. {
  976. var ev = PeopleExtras.AsEnumerable().FirstOrDefault(ee => string.Compare(ee.Field, field, ignoreCase: true) == 0);
  977. if (ev != null)
  978. Db.PeopleExtras.DeleteOnSubmit(ev);
  979. }
  980. public void AddEditExtraValue(string field, string value)
  981. {
  982. if (!field.HasValue())
  983. return;
  984. if (!value.HasValue())
  985. return;
  986. var ev = GetExtraValue(field);
  987. ev.StrValue = value;
  988. }
  989. public void AddEditExtraDate(string field, DateTime? value)
  990. {
  991. if (!value.HasValue)
  992. return;
  993. var ev = GetExtraValue(field);
  994. ev.DateValue = value;
  995. }
  996. public void AddEditExtraData(string field, string value)
  997. {
  998. if (!value.HasValue())
  999. return;
  1000. var ev = GetExtraValue(field);
  1001. ev.Data = value;
  1002. }
  1003. public void AddToExtraData(string field, string value)
  1004. {
  1005. if (!value.HasValue())
  1006. return;
  1007. var ev = GetExtraValue(field);
  1008. if (ev.Data.HasValue())
  1009. ev.Data = value + "\n" + ev.Data;
  1010. else
  1011. ev.Data = value;
  1012. }
  1013. public void AddEditExtraInt(string field, int value)
  1014. {
  1015. var ev = GetExtraValue(field);
  1016. ev.IntValue = value;
  1017. }
  1018. public void AddEditExtraBool(string field, bool tf)
  1019. {
  1020. if (!field.HasValue())
  1021. return;
  1022. var ev = GetExtraValue(field);
  1023. ev.BitValue = tf;
  1024. }
  1025. public void AddEditExtraInts(string field, int value, int value2)
  1026. {
  1027. var ev = GetExtraValue(field);
  1028. ev.IntValue = value;
  1029. ev.IntValue2 = value2;
  1030. }
  1031. public ManagedGiving ManagedGiving()
  1032. {
  1033. var mg = ManagedGivings.SingleOrDefault();
  1034. return mg;
  1035. }
  1036. public PaymentInfo PaymentInfo()
  1037. {
  1038. var pi = PaymentInfos.SingleOrDefault();
  1039. return pi;
  1040. }
  1041. public Contribution PostUnattendedContribution(CMSDataContext Db, decimal Amt, int? Fund, string Description, bool pledge = false)
  1042. {
  1043. var typecode = BundleTypeCode.Online;
  1044. if (pledge)
  1045. typecode = BundleTypeCode.OnlinePledge;
  1046. var d = Util.Now.Date;
  1047. d = d.AddDays(-(int)d.DayOfWeek); // prev sunday
  1048. var q = from b in Db.BundleHeaders
  1049. where b.BundleHeaderTypeId == typecode
  1050. where b.BundleStatusId == BundleStatusCode.Open
  1051. where b.ContributionDate >= d
  1052. where b.ContributionDate < Util.Now
  1053. orderby b.ContributionDate descending
  1054. select b;
  1055. var bundle = q.FirstOrDefault();
  1056. if (bundle == null)
  1057. {
  1058. bundle = new BundleHeader
  1059. {
  1060. BundleHeaderTypeId = typecode,
  1061. BundleStatusId = BundleStatusCode.Open,
  1062. CreatedBy = Util.UserId1,
  1063. ContributionDate = d,
  1064. CreatedDate = DateTime.Now,
  1065. DepositDate = DateTime.Now,
  1066. FundId = Db.Setting("DefaultFundId", "1").ToInt(),
  1067. RecordStatus = false,
  1068. TotalCash = 0,
  1069. TotalChecks = 0,
  1070. TotalEnvelopes = 0,
  1071. BundleTotal = 0
  1072. };
  1073. Db.BundleHeaders.InsertOnSubmit(bundle);
  1074. }
  1075. if (!Fund.HasValue)
  1076. Fund = (from f in Db.ContributionFunds
  1077. where f.FundStatusId == 1
  1078. orderby f.FundId
  1079. select f.FundId).First();
  1080. var FinanceManagerId = Db.Setting("FinanceManagerId", "").ToInt2();
  1081. if (!FinanceManagerId.HasValue)
  1082. {
  1083. var qu = from u in Db.Users
  1084. where u.UserRoles.Any(ur => ur.Role.RoleName == "Finance")
  1085. orderby u.Person.LastName
  1086. select u.UserId;
  1087. FinanceManagerId = qu.FirstOrDefault();
  1088. if (!FinanceManagerId.HasValue)
  1089. FinanceManagerId = 1;
  1090. }
  1091. var bd = new CmsData.BundleDetail
  1092. {
  1093. BundleHeaderId = bundle.BundleHeaderId,
  1094. CreatedBy = FinanceManagerId.Value,
  1095. CreatedDate = DateTime.Now,
  1096. };
  1097. var typid = ContributionTypeCode.CheckCash;
  1098. if (pledge)
  1099. typid = ContributionTypeCode.Pledge;
  1100. bd.Contribution = new Contribution
  1101. {
  1102. CreatedBy = FinanceManagerId.Value,
  1103. CreatedDate = bd.CreatedDate,
  1104. FundId = Fund.Value,
  1105. PeopleId = PeopleId,
  1106. ContributionDate = bd.CreatedDate,
  1107. ContributionAmount = Amt,
  1108. ContributionStatusId = 0,
  1109. ContributionTypeId = typid,
  1110. ContributionDesc = Description,
  1111. };
  1112. bundle.BundleDetails.Add(bd);
  1113. Db.SubmitChanges();
  1114. return bd.Contribution;
  1115. }
  1116. public static int FetchOrCreateMemberStatus(CMSDataContext Db, string type)
  1117. {
  1118. var ms = Db.MemberStatuses.SingleOrDefault(m => m.Description == type);
  1119. if (ms == null)
  1120. {
  1121. var max = Db.MemberStatuses.Max(mm => mm.Id) + 1;
  1122. ms = new MemberStatus() { Id = max, Code = "M" + max, Description = type };
  1123. Db.MemberStatuses.InsertOnSubmit(ms);
  1124. Db.SubmitChanges();
  1125. }
  1126. return ms.Id;
  1127. }
  1128. public static Campu FetchOrCreateCampus(CMSDataContext Db, string campus)
  1129. {
  1130. if (!campus.HasValue())
  1131. return null;
  1132. var cam = Db.Campus.SingleOrDefault(pp => pp.Description == campus);
  1133. if (cam == null)
  1134. {
  1135. int max = 10;
  1136. if (Db.Campus.Any())
  1137. max = Db.Campus.Max(mm => mm.Id) + 10;
  1138. cam = new Campu() { Id = max, Description = campus, Code = campus.Truncate(20) };
  1139. Db.Campus.InsertOnSubmit(cam);
  1140. Db.SubmitChanges();
  1141. }
  1142. else if (!cam.Code.HasValue())
  1143. {
  1144. cam.Code = campus.Truncate(20);
  1145. Db.SubmitChanges();
  1146. }
  1147. return cam;
  1148. }
  1149. public Task AddTaskAbout(CMSDataContext Db, int AssignTo, string description)
  1150. {
  1151. var t = new Task
  1152. {
  1153. OwnerId = AssignTo,
  1154. Description = description,
  1155. ForceCompleteWContact = true,
  1156. ListId = Task.GetRequiredTaskList("InBox", AssignTo).Id,
  1157. StatusId = TaskStatusCode.Active,
  1158. };
  1159. TasksAboutPerson.Add(t);
  1160. return t;
  1161. }
  1162. }
  1163. }