Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

817 lines
29KB

  1. <% Option Explicit %>
  2. <!--#include file="../../include_all.asp"-->
  3. <!--#include file="../../ViewModels/JurisdictionViewModels.asp"-->
  4. <%
  5. Class JurisdictionController
  6. Public Model
  7. Public Sub Index
  8. dim page_size : page_size = 10
  9. dim page_num : page_num = Choice(Len(Request.Querystring("page_num")) > 0, Request.Querystring("page_num"), 1)
  10. dim page_count, record_count
  11. set Model = new PagedIndex_ViewModel_Class
  12. Model.Title = "Jurisdiction"
  13. set Model.Jurisdiction = JurisdictionRepository.FindPaged(empty, "JCode", page_size, page_num, page_count, record_count)
  14. Model.CurrentPageNumber = page_num
  15. Model.PageSize = page_size
  16. Model.PageCount = page_count
  17. Model.RecordCount = record_count
  18. %> <!--#include file="../../Views/Jurisdiction/Index.asp"--> <%
  19. End Sub
  20. Public Sub Search
  21. dim searchValue:searchValue = Choice(Request.Form.Count = 0,Request.QueryString("q"),Request.Form("q"))
  22. dim page_size : page_size = 10
  23. dim page_num : page_num = Choice(Len(Request.Querystring("page_num")) > 0, Request.Querystring("page_num"), 1)
  24. dim page_count, record_count
  25. set Model = new PagedIndex_ViewModel_Class
  26. Model.Title = "Jurisdiction"
  27. set Model.Jurisdiction = JurisdictionRepository.SearchTablePaged(Array("JCode","%" & searchValue & "%","Name","%" & searchValue & "%","Mailing_Address","%" & searchValue & "%","CSZ","%" & searchValue & "%","IMB","%" & searchValue & "%","IMB_Digits","%" & searchValue & "%"),"JCode", page_size, page_num, page_count, record_count)
  28. Model.CurrentPageNumber = page_num
  29. Model.PageSize = page_size
  30. Model.PageCount = page_count
  31. Model.RecordCount = record_count
  32. %> <!--#include file="../../Views/Jurisdiction/Index.asp"--> <%
  33. End Sub
  34. Public Sub Edit
  35. dim id : id = Request.QueryString("Id")
  36. set Model = new Edit_ViewModel_Class
  37. set Model.Jurisdiction = JurisdictionRepository.FindByJCode(id)
  38. set Model.Contacts = ContactsRepository.Find(Array("JURISCODE = ?",id),empty)
  39. Model.Title = "Edit Jurisdiction"
  40. HTMLSecurity.SetAntiCSRFToken "JurisdictionEditForm"
  41. %> <!--#include file="../../Views/Jurisdiction/Edit.asp"--> <%
  42. Flash.Success = "Jurisdiction Updated."
  43. End Sub
  44. Public Sub EditPost
  45. MVC.RequirePost
  46. HTMLSecurity.OnInvalidAntiCsrfTokenRedirectToActionExt "JurisdictionEditForm", Request.Form("nonce"), "Edit", Array("Id", Request.Form("Id"))
  47. dim JCode : JCode = Request.Form("Id")
  48. dim model : set model = JurisdictionRepository.FindByJCode(JCode)
  49. set model = Automapper.AutoMap(Request.Form, model)
  50. 'model.Validate
  51. 'If model.Validator.HasErrors then
  52. FormCache.SerializeForm "EditJurisdiction", Request.Form
  53. ' Flash.Errors = model.Validator.Errors
  54. ' MVC.RedirectToActionExt "Edit", Array("Id",JCode)
  55. 'Else
  56. JurisdictionRepository.Update model
  57. FormCache.ClearForm "EditJurisdiction"
  58. Flash.Success = "Jurisdiction updated."
  59. MVC.RedirectToAction "Index"
  60. 'End If
  61. End Sub
  62. Public Sub Create
  63. dim form_params : set form_params = FormCache.DeserializeForm("NewJurisdiction")
  64. If Not form_params Is Nothing then
  65. set Model = Automapper.AutoMap(form_params, New Create_ViewModel_Class)
  66. Else
  67. set Model = new Create_ViewModel_Class
  68. End If
  69. HTMLSecurity.SetAntiCSRFToken "JurisdictionCreateForm"
  70. %> <!--#include file="../../Views/Jurisdiction/Create.asp"--> <%
  71. End Sub
  72. Public Sub CreatePost
  73. MVC.RequirePost
  74. HtmlSecurity.OnInvalidAntiCSRFTokenRedirectToAction "JurisdictionCreateForm", Request.Form("nonce"), "Create"
  75. dim new_Jurisdiction_model : set new_Jurisdiction_model = Automapper.AutoMap(Request.Form, new JurisdictionModel_Class)
  76. 'new_Jurisdiction_model.Validator.Validate
  77. 'If new_Jurisdiction_model.Validator.HasErrors then
  78. ' FormCache.SerializeForm "NewJurisdiction", Request.Form
  79. ' Flash.Errors = new_Jurisdiction_model.Validator.Errors
  80. ' MVC.RedirectToAction "Create"
  81. 'Else
  82. JurisdictionRepository.AddNew new_Jurisdiction_model
  83. ' FormCache.ClearForm "NewJurisdiction"
  84. Flash.Success = "Jurisdiction added."
  85. MVC.RedirectToAction "Index"
  86. 'End If
  87. End Sub
  88. Public Sub Delete
  89. dim id : id = Request.QueryString("Id")
  90. set Model = new Delete_ViewModel_Class
  91. set Model.Jurisdiction = JurisdictionRepository.FindByJCode(id)
  92. Model.Title = "Delete Jurisdiction"
  93. HTMLSecurity.SetAntiCSRFToken "JurisdictionDeleteForm"
  94. %> <!--#include file="../../Views/Jurisdiction/Delete.asp"--> <%
  95. End Sub
  96. Public Sub DeletePost
  97. MVC.RequirePost
  98. HtmlSecurity.OnInvalidAntiCSRFTokenRedirectToAction "JurisdictionDeleteForm", Request.Form("nonce"), "Create"
  99. dim id : id = Request.Form("Id")
  100. JurisdictionRepository.Delete id
  101. Flash.Success = "Jurisdiction deleted."
  102. MVC.RedirectToAction "Index"
  103. End Sub
  104. Public Sub Createkit
  105. dim id : id = Request.QueryString("Id")
  106. set Model = new Delete_ViewModel_Class
  107. set Model.Jurisdiction = JurisdictionRepository.FindByJCode(id)
  108. Model.Title = "Create Kit"
  109. HTMLSecurity.SetAntiCSRFToken "JurisdictionDeleteForm"
  110. %> <!--#include file="../../Views/Jurisdiction/createkit.asp"--> <%
  111. End sub
  112. Public Sub CreateKitPost
  113. MVC.RequirePost
  114. HtmlSecurity.OnInvalidAntiCSRFTokenRedirectToAction "CreateKitForm", Request.Form("nonce"), "Index"
  115. dim id : id = Request.QueryString("Id")
  116. set Model = new Delete_ViewModel_Class
  117. set Model.Jurisdiction = JurisdictionRepository.FindByJCode(id)
  118. Model.Title = "Create Kit"
  119. HTMLSecurity.SetAntiCSRFToken "JurisdictionDeleteForm"
  120. %> <!--#include file="../../Views/Jurisdiction/createkit.asp"--> <%
  121. End sub
  122. Public Sub Import
  123. dim page_size : page_size = 10
  124. dim page_num : page_num = Choice(Len(Request.Querystring("page_num")) > 0, Request.Querystring("page_num"), 1)
  125. dim page_count, record_count
  126. set Model = new PagedIndex_ViewModel_Class
  127. Model.Title = "Jurisdiction"
  128. set Model.Jurisdiction = JurisdictionRepository.FindPaged(empty, "JCode", page_size, page_num, page_count, record_count)
  129. Model.CurrentPageNumber = page_num
  130. Model.PageSize = page_size
  131. Model.PageCount = page_count
  132. 'Model.RecordCount = record_count
  133. HTMLSecurity.SetAntiCSRFToken "JurisdictionImportForm"
  134. %> <!--#include file="../../Views/Jurisdiction/import.asp"--> <%
  135. End Sub
  136. Public Sub ImportPost
  137. If UCase(Request.ServerVariables("REQUEST_METHOD") & "") <> "POST" Then
  138. Err.Raise 1, "JurisdictionController:ImportPost", "Action only responds to POST requests."
  139. End If
  140. Dim Upload : Set Upload = New FreeASPUpload
  141. Dim uploadPath, uploadedFile, fileName, fileExt, fileSize
  142. Dim maxFileSize, dotPos, nonce
  143. Dim savedFileName, savedLocalFileName, savedPath
  144. Dim workbookData, worksheetName, headerIndex, missingHeaders
  145. Dim importToken, totalRows, duplicateCount
  146. maxFileSize = 10485760 '10 MB in bytes
  147. uploadPath = Server.MapPath("/uploads")
  148. Upload.Upload
  149. nonce = Upload.Form("nonce")
  150. If Not HTMLSecurity.IsValidAntiCSRFToken("JurisdictionImportForm", nonce) Then
  151. HTMLSecurity.ClearAntiCSRFToken "JurisdictionImportForm"
  152. HTMLSecurity.SetAntiCSRFToken "JurisdictionImportForm"
  153. SendImportJsonError "Invalid form state. Please refresh and try again."
  154. Exit Sub
  155. End If
  156. HTMLSecurity.ClearAntiCSRFToken "JurisdictionImportForm"
  157. HTMLSecurity.SetAntiCSRFToken "JurisdictionImportForm"
  158. If Upload.FileExists("filename") = False Then
  159. SendImportJsonError "No file selected for upload."
  160. Exit Sub
  161. End If
  162. Set uploadedFile = Upload.UploadedFiles("filename")
  163. fileName = uploadedFile.FileName
  164. fileSize = uploadedFile.Length
  165. dotPos = InStrRev(fileName, ".")
  166. If dotPos > 0 Then
  167. fileExt = LCase(Mid(fileName, dotPos))
  168. Else
  169. fileExt = ""
  170. End If
  171. If fileExt <> ".xlsx" Then
  172. SendImportJsonError "Only .xlsx files are allowed."
  173. Exit Sub
  174. End If
  175. If fileSize > maxFileSize Then
  176. SendImportJsonError "File size exceeds 10 MB limit."
  177. Exit Sub
  178. End If
  179. EnsureFolderExists uploadPath
  180. Upload.SaveOne uploadPath, 0, savedFileName, savedLocalFileName
  181. savedPath = uploadPath & "\" & savedLocalFileName
  182. On Error Resume Next
  183. workbookData = ReadWorkbookData(savedPath, worksheetName)
  184. If Err.Number <> 0 Then
  185. Dim workbookErr : workbookErr = Err.Description
  186. Err.Clear
  187. On Error GoTo 0
  188. DeleteFileIfExists savedPath
  189. SendImportJsonError "Unable to read the XLSX workbook. Verify Microsoft ACE OLEDB is installed and the workbook is valid. " & workbookErr
  190. Exit Sub
  191. End If
  192. On Error GoTo 0
  193. If Not WorkbookHasHeaderRows(workbookData) Then
  194. DeleteFileIfExists savedPath
  195. SendImportJsonError "The uploaded workbook must contain an information row and a header row."
  196. Exit Sub
  197. End If
  198. Set headerIndex = BuildHeaderIndex(workbookData, 1)
  199. missingHeaders = MissingRequiredHeaders(headerIndex)
  200. If Len(missingHeaders) > 0 Then
  201. DeleteFileIfExists savedPath
  202. SendImportJsonError "Missing required header(s): " & missingHeaders
  203. Exit Sub
  204. End If
  205. totalRows = CountImportRows(workbookData)
  206. duplicateCount = CountDuplicateJCodes(workbookData, CLng(headerIndex.Item("JURISDICTION")))
  207. importToken = CreateImportToken()
  208. InitializeImportSession importToken, workbookData, worksheetName, fileName, savedPath, totalRows, duplicateCount, headerIndex
  209. SendImportJsonSuccess importToken, fileName, totalRows, duplicateCount
  210. End Sub
  211. Public Sub ImportProgress
  212. Dim importToken : importToken = Trim(Request.QueryString("token") & "")
  213. If Len(importToken) = 0 Then
  214. SendImportJsonError "Missing import token."
  215. Exit Sub
  216. End If
  217. If Not ImportExists(importToken) Then
  218. SendImportJsonError "The requested import session was not found. Please upload the workbook again."
  219. Exit Sub
  220. End If
  221. Dim phase : phase = GetImportValue(importToken, "Phase")
  222. If phase <> "complete" And phase <> "error" Then
  223. ProcessImportChunk importToken, 25
  224. End If
  225. SendImportProgressJson importToken
  226. End Sub
  227. Private Sub ProcessImportChunk(importToken, maxRowsPerRequest)
  228. Dim sessionKey : sessionKey = ImportSessionKey(importToken)
  229. Dim workbookData : workbookData = Session(sessionKey & "Data")
  230. Dim currentRow, lastRow, rowsProcessed
  231. If Not IsArray(workbookData) Then
  232. SetImportValue importToken, "Phase", "error"
  233. SetImportValue importToken, "StatusMessage", "Workbook data is no longer available in session."
  234. AppendImportError importToken, 0, "Workbook data is no longer available in session.", ""
  235. Exit Sub
  236. End If
  237. currentRow = CLng(GetImportValue(importToken, "CurrentRow"))
  238. lastRow = UBound(workbookData, 2)
  239. rowsProcessed = 0
  240. If currentRow < 2 Then currentRow = 2
  241. SetImportValue importToken, "Phase", "processing"
  242. Do While currentRow <= lastRow And rowsProcessed < maxRowsPerRequest
  243. ProcessImportRow importToken, workbookData, currentRow
  244. currentRow = currentRow + 1
  245. rowsProcessed = rowsProcessed + 1
  246. SetImportValue importToken, "CurrentRow", currentRow
  247. SetImportValue importToken, "ProcessedRows", CLng(GetImportValue(importToken, "ProcessedRows")) + 1
  248. Loop
  249. If currentRow > lastRow Then
  250. SetImportValue importToken, "Phase", "complete"
  251. SetImportValue importToken, "StatusMessage", "Import complete."
  252. Session.Contents.Remove sessionKey & "Data"
  253. DeleteFileIfExists GetImportValue(importToken, "FilePath")
  254. Session.Contents.Remove sessionKey & "FilePath"
  255. Else
  256. SetImportValue importToken, "StatusMessage", "Processed " & GetImportValue(importToken, "ProcessedRows") & " of " & GetImportValue(importToken, "TotalRows") & " row(s)."
  257. End If
  258. End Sub
  259. Private Sub ProcessImportRow(importToken, workbookData, rowIndex)
  260. Dim county, jurisdictionText, jCode, jurisdictionName, mailingAddress, cityTownship, zipPlusFour, mailerId
  261. Dim csz, imbDigits, imb, jurisdictionModel, recordSummary
  262. county = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "CountyIndex"), rowIndex))
  263. jurisdictionText = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "JurisdictionIndex"), rowIndex))
  264. mailingAddress = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "MailingAddressIndex"), rowIndex))
  265. cityTownship = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "CityTownshipIndex"), rowIndex))
  266. zipPlusFour = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "ZipPlusFourIndex"), rowIndex))
  267. mailerId = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "MailerIdIndex"), rowIndex))
  268. recordSummary = BuildImportRecordSummary(county, jurisdictionText, mailingAddress, cityTownship, zipPlusFour, mailerId)
  269. If Len(Trim(county & jurisdictionText & mailingAddress & cityTownship & zipPlusFour & mailerId)) = 0 Then
  270. IncrementImportCounter importToken, "InvalidCount"
  271. AppendImportError importToken, rowIndex + 1, "Row is empty.", recordSummary
  272. Exit Sub
  273. End If
  274. jCode = ExtractJurisdictionCode(jurisdictionText)
  275. If Len(jCode) = 0 Then
  276. IncrementImportCounter importToken, "InvalidCount"
  277. AppendImportError importToken, rowIndex + 1, "Jurisdiction field is missing a code in parentheses.", recordSummary
  278. Exit Sub
  279. End If
  280. jurisdictionName = NormalizeJurisdictionName(ExtractJurisdictionName(jurisdictionText))
  281. If Len(jurisdictionName) = 0 Then
  282. IncrementImportCounter importToken, "InvalidCount"
  283. AppendImportError importToken, rowIndex + 1, "Jurisdiction name could not be parsed.", recordSummary
  284. Exit Sub
  285. End If
  286. csz = BuildCSZ(cityTownship, zipPlusFour)
  287. imbDigits = BuildIMBDigits(mailerId, zipPlusFour)
  288. If Len(imbDigits) = 0 Then
  289. IncrementImportCounter importToken, "InvalidCount"
  290. AppendImportError importToken, rowIndex + 1, "Unable to build IMB digits from Mailer ID Option 1 and ZIP + 4.", recordSummary
  291. Exit Sub
  292. End If
  293. On Error Resume Next
  294. imb = GetIMBCodec.EncodeDigits(imbDigits)
  295. If Err.Number <> 0 Then
  296. Dim imbErr : imbErr = Err.Description
  297. Err.Clear
  298. On Error GoTo 0
  299. IncrementImportCounter importToken, "FailedCount"
  300. AppendImportError importToken, rowIndex + 1, "IMB generation failed for JCode " & jCode & ". " & imbErr, recordSummary
  301. Exit Sub
  302. End If
  303. On Error GoTo 0
  304. On Error Resume Next
  305. Set jurisdictionModel = JurisdictionRepository.FindByJCode(jCode)
  306. If Err.Number <> 0 Then
  307. Err.Clear
  308. On Error GoTo 0
  309. Set jurisdictionModel = New JurisdictionModel_Class
  310. jurisdictionModel.JCode = jCode
  311. jurisdictionModel.Name = jurisdictionName
  312. jurisdictionModel.Mailing_Address = mailingAddress
  313. jurisdictionModel.CSZ = csz
  314. jurisdictionModel.IMB_Digits = imbDigits
  315. jurisdictionModel.IMB = imb
  316. On Error Resume Next
  317. JurisdictionRepository.AddNewWithJCode jurisdictionModel
  318. If Err.Number <> 0 Then
  319. Dim insertErr : insertErr = Err.Description
  320. Err.Clear
  321. On Error GoTo 0
  322. IncrementImportCounter importToken, "FailedCount"
  323. AppendImportError importToken, rowIndex + 1, "Failed to insert new JCode " & jCode & ". " & insertErr, recordSummary
  324. Exit Sub
  325. End If
  326. On Error GoTo 0
  327. IncrementImportCounter importToken, "InsertedCount"
  328. Exit Sub
  329. End If
  330. On Error GoTo 0
  331. jurisdictionModel.Name = jurisdictionName
  332. jurisdictionModel.Mailing_Address = mailingAddress
  333. jurisdictionModel.CSZ = csz
  334. jurisdictionModel.IMB_Digits = imbDigits
  335. jurisdictionModel.IMB = imb
  336. On Error Resume Next
  337. JurisdictionRepository.Update jurisdictionModel
  338. If Err.Number <> 0 Then
  339. Dim updateErr : updateErr = Err.Description
  340. Err.Clear
  341. On Error GoTo 0
  342. IncrementImportCounter importToken, "FailedCount"
  343. AppendImportError importToken, rowIndex + 1, "Failed to update JCode " & jCode & ". " & updateErr, recordSummary
  344. Exit Sub
  345. End If
  346. On Error GoTo 0
  347. IncrementImportCounter importToken, "UpdatedCount"
  348. End Sub
  349. Private Function ReadWorkbookData(filePath, ByRef worksheetName)
  350. Dim conn, rs, connString, sql
  351. connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"";"
  352. Set conn = Server.CreateObject("ADODB.Connection")
  353. conn.Open connString
  354. worksheetName = FirstWorksheetName(conn)
  355. If Len(worksheetName) = 0 Then
  356. conn.Close
  357. Set conn = Nothing
  358. Err.Raise vbObjectError + 2010, "JurisdictionController", "No worksheet was found in the uploaded workbook."
  359. End If
  360. sql = "SELECT * FROM [" & worksheetName & "]"
  361. Set rs = Server.CreateObject("ADODB.Recordset")
  362. rs.Open sql, conn, 3, 1
  363. If rs.EOF And rs.BOF Then
  364. rs.Close
  365. conn.Close
  366. Set rs = Nothing
  367. Set conn = Nothing
  368. Err.Raise vbObjectError + 2011, "JurisdictionController", "The worksheet does not contain any rows."
  369. End If
  370. ReadWorkbookData = rs.GetRows()
  371. rs.Close
  372. conn.Close
  373. Set rs = Nothing
  374. Set conn = Nothing
  375. End Function
  376. Private Function FirstWorksheetName(conn)
  377. Dim schema, tableName
  378. Set schema = conn.OpenSchema(20)
  379. Do Until schema.EOF
  380. tableName = Trim(schema("TABLE_NAME") & "")
  381. If InStr(tableName, "$") > 0 And InStr(tableName, "_xlnm") = 0 Then
  382. FirstWorksheetName = tableName
  383. schema.Close
  384. Set schema = Nothing
  385. Exit Function
  386. End If
  387. schema.MoveNext
  388. Loop
  389. If Not schema Is Nothing Then
  390. schema.Close
  391. Set schema = Nothing
  392. End If
  393. FirstWorksheetName = ""
  394. End Function
  395. Private Function BuildHeaderIndex(workbookData, headerRowIndex)
  396. Dim headerMap, colIndex, headerName
  397. Set headerMap = Server.CreateObject("Scripting.Dictionary")
  398. For colIndex = 0 To UBound(workbookData, 1)
  399. headerName = UCase(Trim(SafeWorkbookValue(workbookData(colIndex, headerRowIndex))))
  400. If Len(headerName) > 0 Then
  401. If Not headerMap.Exists(headerName) Then
  402. headerMap.Add headerName, colIndex
  403. End If
  404. End If
  405. Next
  406. Set BuildHeaderIndex = headerMap
  407. End Function
  408. Private Function WorkbookHasHeaderRows(workbookData)
  409. On Error Resume Next
  410. WorkbookHasHeaderRows = (IsArray(workbookData) And UBound(workbookData, 2) >= 1)
  411. If Err.Number <> 0 Then
  412. Err.Clear
  413. WorkbookHasHeaderRows = False
  414. End If
  415. On Error GoTo 0
  416. End Function
  417. Private Function MissingRequiredHeaders(headerIndex)
  418. Dim requiredHeaders, missingHeaders, i
  419. requiredHeaders = Array("County", "Jurisdiction", "Mailing Address", "City & Township", "ZIP + 4", "Mailer ID Option 1")
  420. missingHeaders = ""
  421. For i = 0 To UBound(requiredHeaders)
  422. If Not headerIndex.Exists(UCase(requiredHeaders(i))) Then
  423. If Len(missingHeaders) > 0 Then missingHeaders = missingHeaders & ", "
  424. missingHeaders = missingHeaders & requiredHeaders(i)
  425. End If
  426. Next
  427. MissingRequiredHeaders = missingHeaders
  428. End Function
  429. Private Function CountImportRows(workbookData)
  430. If Not WorkbookHasHeaderRows(workbookData) Then
  431. CountImportRows = 0
  432. ElseIf UBound(workbookData, 2) < 2 Then
  433. CountImportRows = 0
  434. Else
  435. CountImportRows = UBound(workbookData, 2) - 1
  436. End If
  437. End Function
  438. Private Function CountDuplicateJCodes(workbookData, jurisdictionColumnIndex)
  439. Dim seenCodes, rowIndex, jCode
  440. Set seenCodes = Server.CreateObject("Scripting.Dictionary")
  441. CountDuplicateJCodes = 0
  442. If Not WorkbookHasHeaderRows(workbookData) Then Exit Function
  443. If UBound(workbookData, 2) < 2 Then Exit Function
  444. For rowIndex = 2 To UBound(workbookData, 2)
  445. jCode = ExtractJurisdictionCode(SafeWorkbookValue(workbookData(jurisdictionColumnIndex, rowIndex)))
  446. If Len(jCode) > 0 Then
  447. If seenCodes.Exists(jCode) Then
  448. CountDuplicateJCodes = CountDuplicateJCodes + 1
  449. Else
  450. seenCodes.Add jCode, True
  451. End If
  452. End If
  453. Next
  454. End Function
  455. Private Sub InitializeImportSession(importToken, workbookData, worksheetName, fileName, filePath, totalRows, duplicateCount, headerIndex)
  456. Dim sessionKey : sessionKey = ImportSessionKey(importToken)
  457. Session(sessionKey & "Data") = workbookData
  458. Session(sessionKey & "WorksheetName") = worksheetName
  459. Session(sessionKey & "FileName") = fileName
  460. Session(sessionKey & "FilePath") = filePath
  461. Session(sessionKey & "CurrentRow") = 2
  462. Session(sessionKey & "ProcessedRows") = 0
  463. Session(sessionKey & "TotalRows") = totalRows
  464. Session(sessionKey & "UpdatedCount") = 0
  465. Session(sessionKey & "InsertedCount") = 0
  466. Session(sessionKey & "UnmatchedCount") = 0
  467. Session(sessionKey & "InvalidCount") = 0
  468. Session(sessionKey & "FailedCount") = 0
  469. Session(sessionKey & "DuplicateCount") = duplicateCount
  470. Session(sessionKey & "Phase") = "staged"
  471. Session(sessionKey & "StatusMessage") = "Workbook uploaded. Processing will begin shortly."
  472. Session(sessionKey & "Errors") = ""
  473. Session(sessionKey & "CountyIndex") = CLng(headerIndex.Item("COUNTY"))
  474. Session(sessionKey & "JurisdictionIndex") = CLng(headerIndex.Item("JURISDICTION"))
  475. Session(sessionKey & "MailingAddressIndex") = CLng(headerIndex.Item("MAILING ADDRESS"))
  476. Session(sessionKey & "CityTownshipIndex") = CLng(headerIndex.Item("CITY & TOWNSHIP"))
  477. Session(sessionKey & "ZipPlusFourIndex") = CLng(headerIndex.Item("ZIP + 4"))
  478. Session(sessionKey & "MailerIdIndex") = CLng(headerIndex.Item("MAILER ID OPTION 1"))
  479. End Sub
  480. Private Function CreateImportToken()
  481. Dim token : token = HTMLSecurity.Nonce()
  482. token = Replace(token, "{", "")
  483. token = Replace(token, "}", "")
  484. CreateImportToken = token
  485. End Function
  486. Private Function ImportSessionKey(importToken)
  487. ImportSessionKey = "JurisdictionImport." & importToken & "."
  488. End Function
  489. Private Function ImportExists(importToken)
  490. ImportExists = (Len(GetImportValue(importToken, "Phase")) > 0)
  491. End Function
  492. Private Function GetImportValue(importToken, name)
  493. GetImportValue = Session(ImportSessionKey(importToken) & name)
  494. End Function
  495. Private Sub SetImportValue(importToken, name, value)
  496. Session(ImportSessionKey(importToken) & name) = value
  497. End Sub
  498. Private Function GetImportColumnIndex(importToken, name)
  499. GetImportColumnIndex = CLng(GetImportValue(importToken, name))
  500. End Function
  501. Private Sub IncrementImportCounter(importToken, counterName)
  502. SetImportValue importToken, counterName, CLng(GetImportValue(importToken, counterName)) + 1
  503. End Sub
  504. Private Function ExtractJurisdictionCode(jurisdictionText)
  505. Dim openPos, closePos
  506. openPos = InStrRev(jurisdictionText, "(")
  507. closePos = InStrRev(jurisdictionText, ")")
  508. If openPos > 0 And closePos > openPos Then
  509. ExtractJurisdictionCode = Trim(Mid(jurisdictionText, openPos + 1, closePos - openPos - 1))
  510. Else
  511. ExtractJurisdictionCode = ""
  512. End If
  513. End Function
  514. Private Function ExtractJurisdictionName(jurisdictionText)
  515. Dim openPos
  516. openPos = InStrRev(jurisdictionText, "(")
  517. If openPos > 0 Then
  518. ExtractJurisdictionName = Trim(Left(jurisdictionText, openPos - 1))
  519. Else
  520. ExtractJurisdictionName = Trim(jurisdictionText)
  521. End If
  522. End Function
  523. Private Function NormalizeJurisdictionName(jurisdictionName)
  524. Dim normalizedName
  525. normalizedName = Trim(jurisdictionName)
  526. If Len(normalizedName) >= 5 Then
  527. If UCase(Right(normalizedName, 5)) = " CITY" Then
  528. normalizedName = "CITY OF " & Trim(Left(normalizedName, Len(normalizedName) - 5))
  529. End If
  530. End If
  531. NormalizeJurisdictionName = normalizedName
  532. End Function
  533. Private Function BuildCSZ(cityTownship, zipPlusFour)
  534. BuildCSZ = Trim(Trim(cityTownship) & " " & Trim(zipPlusFour))
  535. End Function
  536. Private Function BuildIMBDigits(mailerId, zipPlusFour)
  537. Dim cleanMailerId, cleanZip, inboundStid
  538. cleanMailerId = DigitsOnly(mailerId)
  539. cleanZip = DigitsOnly(zipPlusFour)
  540. If Len(cleanMailerId) = 0 Or Len(cleanZip) = 0 Then
  541. BuildIMBDigits = ""
  542. Else
  543. inboundStid = SettingsRepository.FindByName("Inbound STID")
  544. BuildIMBDigits = inboundStid & cleanMailerId & "000000" & cleanZip
  545. End If
  546. End Function
  547. Private Function DigitsOnly(inputValue)
  548. Dim i, ch
  549. DigitsOnly = ""
  550. For i = 1 To Len(inputValue)
  551. ch = Mid(inputValue, i, 1)
  552. If ch >= "0" And ch <= "9" Then
  553. DigitsOnly = DigitsOnly & ch
  554. End If
  555. Next
  556. End Function
  557. Private Function SafeWorkbookValue(value)
  558. If IsNull(value) Or IsEmpty(value) Then
  559. SafeWorkbookValue = ""
  560. Else
  561. SafeWorkbookValue = Trim(CStr(value))
  562. End If
  563. End Function
  564. Private Function BuildImportRecordSummary(county, jurisdictionText, mailingAddress, cityTownship, zipPlusFour, mailerId)
  565. BuildImportRecordSummary = "County=" & DisplayImportField(county) & _
  566. "; Jurisdiction=" & DisplayImportField(jurisdictionText) & _
  567. "; Mailing Address=" & DisplayImportField(mailingAddress) & _
  568. "; City & Township=" & DisplayImportField(cityTownship) & _
  569. "; ZIP + 4=" & DisplayImportField(zipPlusFour) & _
  570. "; Mailer ID Option 1=" & DisplayImportField(mailerId)
  571. End Function
  572. Private Function DisplayImportField(value)
  573. If Len(Trim(value & "")) = 0 Then
  574. DisplayImportField = "<blank>"
  575. Else
  576. DisplayImportField = value & ""
  577. End If
  578. End Function
  579. Private Sub AppendImportError(importToken, rowNumber, errorMessage, recordSummary)
  580. Dim sessionKey, currentErrors, fullMessage
  581. sessionKey = ImportSessionKey(importToken)
  582. currentErrors = Session(sessionKey & "Errors") & ""
  583. If rowNumber > 0 Then
  584. fullMessage = "Row " & rowNumber & ": " & errorMessage
  585. Else
  586. fullMessage = errorMessage
  587. End If
  588. If Len(Trim(recordSummary & "")) > 0 Then
  589. fullMessage = fullMessage & " Record: " & recordSummary
  590. End If
  591. If Len(currentErrors) > 0 Then
  592. currentErrors = currentErrors & Chr(30)
  593. End If
  594. currentErrors = currentErrors & fullMessage
  595. Session(sessionKey & "Errors") = currentErrors
  596. End Sub
  597. Private Sub SendImportJsonSuccess(importToken, fileName, totalRows, duplicateCount)
  598. Response.ContentType = "application/json"
  599. Response.Write "{""ok"":true,""token"":""" & JsonEscape(importToken) & """,""fileName"":""" & JsonEscape(fileName) & """,""phase"":""staged"",""totalRows"":" & totalRows & ",""processedRows"":0,""updatedCount"":0,""insertedCount"":0,""invalidCount"":0,""failedCount"":0,""duplicateCount"":" & duplicateCount & ",""percentComplete"":0,""statusMessage"":""Workbook uploaded. Processing will begin shortly."",""nextNonce"":""" & JsonEscape(HTMLSecurity.GetAntiCSRFToken("JurisdictionImportForm")) & """,""errors"":[]}"
  600. Response.End
  601. End Sub
  602. Private Sub SendImportProgressJson(importToken)
  603. Dim phase, totalRows, processedRows, updatedCount, insertedCount, invalidCount, failedCount, duplicateCount
  604. Dim percentComplete, statusMessage, errorsJson
  605. phase = GetImportValue(importToken, "Phase")
  606. totalRows = CLng(GetImportValue(importToken, "TotalRows"))
  607. processedRows = CLng(GetImportValue(importToken, "ProcessedRows"))
  608. updatedCount = CLng(GetImportValue(importToken, "UpdatedCount"))
  609. insertedCount = CLng(GetImportValue(importToken, "InsertedCount"))
  610. invalidCount = CLng(GetImportValue(importToken, "InvalidCount"))
  611. failedCount = CLng(GetImportValue(importToken, "FailedCount"))
  612. duplicateCount = CLng(GetImportValue(importToken, "DuplicateCount"))
  613. statusMessage = GetImportValue(importToken, "StatusMessage") & ""
  614. errorsJson = JsonArrayFromDelimitedString(GetImportValue(importToken, "Errors") & "")
  615. If totalRows > 0 Then
  616. percentComplete = Int((processedRows / totalRows) * 100)
  617. Else
  618. percentComplete = 100
  619. End If
  620. If phase = "complete" Then percentComplete = 100
  621. Response.ContentType = "application/json"
  622. Response.Write "{""ok"":true,""token"":""" & JsonEscape(importToken) & """,""phase"":""" & JsonEscape(phase) & """,""totalRows"":" & totalRows & ",""processedRows"":" & processedRows & ",""updatedCount"":" & updatedCount & ",""insertedCount"":" & insertedCount & ",""invalidCount"":" & invalidCount & ",""failedCount"":" & failedCount & ",""duplicateCount"":" & duplicateCount & ",""percentComplete"":" & percentComplete & ",""statusMessage"":""" & JsonEscape(statusMessage) & """,""errors"":" & errorsJson & "}"
  623. Response.End
  624. End Sub
  625. Private Sub SendImportJsonError(errorMessage)
  626. Response.ContentType = "application/json"
  627. Response.Status = "400 Bad Request"
  628. Response.Write "{""ok"":false,""message"":""" & JsonEscape(errorMessage) & """,""nextNonce"":""" & JsonEscape(HTMLSecurity.GetAntiCSRFToken("JurisdictionImportForm")) & """}"
  629. Response.End
  630. End Sub
  631. Private Function JsonArrayFromDelimitedString(delimitedValue)
  632. Dim items, i, result
  633. If Len(delimitedValue) = 0 Then
  634. JsonArrayFromDelimitedString = "[]"
  635. Exit Function
  636. End If
  637. items = Split(delimitedValue, Chr(30))
  638. result = "["
  639. For i = 0 To UBound(items)
  640. If i > 0 Then result = result & ","
  641. result = result & """" & JsonEscape(items(i)) & """"
  642. Next
  643. result = result & "]"
  644. JsonArrayFromDelimitedString = result
  645. End Function
  646. Private Function JsonEscape(value)
  647. value = Replace(value & "", "\", "\\")
  648. value = Replace(value, """", "\""")
  649. value = Replace(value, vbCrLf, "\n")
  650. value = Replace(value, vbCr, "\n")
  651. value = Replace(value, vbLf, "\n")
  652. JsonEscape = value
  653. End Function
  654. Private Sub EnsureFolderExists(folderPath)
  655. Dim fso : Set fso = Server.CreateObject("Scripting.FileSystemObject")
  656. If Not fso.FolderExists(folderPath) Then
  657. fso.CreateFolder folderPath
  658. End If
  659. Set fso = Nothing
  660. End Sub
  661. Private Sub DeleteFileIfExists(filePath)
  662. Dim fso
  663. If Len(Trim(filePath & "")) = 0 Then Exit Sub
  664. Set fso = Server.CreateObject("Scripting.FileSystemObject")
  665. If fso.FileExists(filePath) Then
  666. On Error Resume Next
  667. fso.DeleteFile filePath, True
  668. On Error GoTo 0
  669. End If
  670. Set fso = Nothing
  671. End Sub
  672. End Class
  673. MVC.Dispatch
  674. %>

Powered by TurnKey Linux.