Skouter mortgage estimates. Web application with view written in PHP and Vue, but controller and models in Go.
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.
 
 
 
 
 
 

1555 lines
33 KiB

  1. package main
  2. import (
  3. "net/http"
  4. "net/mail"
  5. "log"
  6. "sync"
  7. "regexp"
  8. "html/template"
  9. "database/sql"
  10. _ "github.com/go-sql-driver/mysql"
  11. "fmt"
  12. "encoding/json"
  13. "strconv"
  14. "bytes"
  15. "time"
  16. "errors"
  17. "strings"
  18. "math"
  19. // pdf "github.com/SebastiaanKlippert/go-wkhtmltopdf"
  20. "github.com/golang-jwt/jwt/v4"
  21. )
  22. type User struct {
  23. Id int `json:"id"`
  24. Email string `json:"email"`
  25. FirstName string `json:"firstName"`
  26. LastName string `json:"lastName"`
  27. BranchId int `json:"branchId"`
  28. Status string `json:"status"`
  29. Country string `json:"country"`
  30. Title string `json:"title"`
  31. Verified bool `json:"verified"`
  32. Role string `json:"role"`
  33. Password string `json:"password,omitempty"`
  34. }
  35. type UserClaims struct {
  36. Id int `json:"id"`
  37. Role string `json:"role"`
  38. Exp string `json:"exp"`
  39. }
  40. type Page struct {
  41. tpl *template.Template
  42. Title string
  43. Name string
  44. }
  45. type Borrower struct {
  46. Id int `json:"id"`
  47. Credit int `json:"credit"`
  48. Income int `json:"income"`
  49. Num int `json:"num"`
  50. }
  51. type FeeTemplate struct {
  52. Id int `json:"id"`
  53. User int `json:"user"`
  54. Branch int `json:"branch"`
  55. Amount int `json:"amount"`
  56. Perc int `json:"perc"`
  57. Type string `json:"type"`
  58. Notes string `json:"notes"`
  59. Name string `json:"name"`
  60. Category string `json:"category"`
  61. Auto bool `json:"auto"`
  62. }
  63. type Fee struct {
  64. Id int `json:"id"`
  65. LoanId int `json:"loan_id"`
  66. Amount int `json:"amount"`
  67. Perc float32 `json:"perc"`
  68. Type string `json:"type"`
  69. Notes string `json:"notes"`
  70. Name string `json:"name"`
  71. Category string `json:"category"`
  72. }
  73. type LoanType struct {
  74. Id int `json:"id"`
  75. User int `json:"user"`
  76. Branch int `json:"branch"`
  77. Name string `json:"name"`
  78. }
  79. type Loan struct {
  80. Id int `json:"id"`
  81. EstimateId int `json:"estimateId"`
  82. Type LoanType `json:"type"`
  83. Amount int `json:"amount"`
  84. Amortization string `json:"amortization"`
  85. Term int `json:"term"`
  86. Ltv float32 `json:"ltv"`
  87. Dti float32 `json:"dti"`
  88. Hoi int `json:"hoi"`
  89. Hazard int `json:"hazard"`
  90. Tax int `json:"tax"`
  91. Interest float32 `json:"interest"`
  92. Mi MI `json:"mi"`
  93. Fees []Fee `json:"fees"`
  94. Name string `json:"title"`
  95. }
  96. type MI struct {
  97. Type string `json:"user"`
  98. Label string `json:"label"`
  99. Lender string `json:"lender"`
  100. Rate float32 `json:"rate"`
  101. Premium float32 `json:"premium"`
  102. Upfront float32 `json:"upfront"`
  103. Monthly bool `json:"monthly"`
  104. FiveYearTotal float32 `json:"fiveYearTotal"`
  105. InitialAllInPremium float32 `json:"initialAllInPremium"`
  106. InitialAllInRate float32 `json:"initialAllInRate"`
  107. InitialAmount float32 `json:"initialAmount"`
  108. }
  109. type Result struct {
  110. Id int `json:"id"`
  111. LoanId int `json:"loanId"`
  112. LoanPayment int `json:"loanPayment"`
  113. TotalMonthly int `json:"totalMonthly"`
  114. TotalFees int `json:"totalFees"`
  115. TotalCredits int `json:"totalCredits"`
  116. CashToClose int `json:"cashToClose"`
  117. }
  118. type Estimate struct {
  119. Id int `json:"id"`
  120. User int `json:"user"`
  121. Borrower Borrower `json:"borrower"`
  122. Transaction string `json:"transaction"`
  123. Price int `json:"price"`
  124. Property string `json:"property"`
  125. Occupancy string `json:"occupancy"`
  126. Zip string `json:"zip"`
  127. Pud bool `json:"pud"`
  128. Loans []Loan `json:"loans"`
  129. Results []Result `json:"results"`
  130. }
  131. var (
  132. regexen = make(map[string]*regexp.Regexp)
  133. relock sync.Mutex
  134. address = "127.0.0.1:8001"
  135. )
  136. var paths = map[string]string {
  137. "home": "home.tpl",
  138. "terms": "terms.tpl",
  139. "app": "app.tpl",
  140. }
  141. var pages = map[string]Page {
  142. "home": cache("home", "Home"),
  143. "terms": cache("terms", "Terms and Conditions"),
  144. "app": cache("app", "App"),
  145. }
  146. var roles = map[string]int{
  147. "User": 1,
  148. "Manager": 2,
  149. "Admin": 3,
  150. }
  151. // Used to validate claim in JWT token body. Checks if user id is greater than
  152. // zero and time format is valid
  153. func (c UserClaims) Valid() error {
  154. if c.Id < 1 { return errors.New("Invalid id") }
  155. t, err := time.Parse(time.UnixDate, c.Exp)
  156. if err != nil { return err }
  157. if t.Before(time.Now()) { return errors.New("Token expired.") }
  158. return err
  159. }
  160. func cache(name string, title string) Page {
  161. var p = []string{"master.tpl", paths[name]}
  162. tpl := template.Must(template.ParseFiles(p...))
  163. return Page{tpl: tpl,
  164. Title: title,
  165. Name: name,
  166. }
  167. }
  168. func (page Page) Render(w http.ResponseWriter) {
  169. err := page.tpl.Execute(w, page)
  170. if err != nil {
  171. log.Print(err)
  172. }
  173. }
  174. func match(path, pattern string, args *[]string) bool {
  175. relock.Lock()
  176. defer relock.Unlock()
  177. regex := regexen[pattern]
  178. if regex == nil {
  179. regex = regexp.MustCompile("^" + pattern + "$")
  180. regexen[pattern] = regex
  181. }
  182. matches := regex.FindStringSubmatch(path)
  183. if len(matches) <= 0 {
  184. return false
  185. }
  186. *args = matches[1:]
  187. return true
  188. }
  189. func makeResults(estimate Estimate) ([]Result) {
  190. var results []Result
  191. amortize := func(principle float64, rate float64, periods float64) int {
  192. exp := math.Pow(1+rate, periods)
  193. return int(principle * rate * exp / (exp - 1))
  194. }
  195. for _, loan := range estimate.Loans {
  196. var result Result
  197. // Monthly payments use amortized loan payment formula plus monthly MI,
  198. // plus all other recurring fees
  199. result.LoanPayment = amortize(float64(loan.Amount),
  200. float64(loan.Interest / 100 / 12),
  201. float64(loan.Term * 12))
  202. result.TotalMonthly = result.LoanPayment + loan.Hoi + loan.Tax + loan.Hazard
  203. if loan.Mi.Monthly {
  204. result.TotalMonthly = result.TotalMonthly +
  205. int(loan.Mi.Rate/100*float32(loan.Amount))
  206. }
  207. for i := range loan.Fees {
  208. if loan.Fees[i].Amount > 0 {
  209. result.TotalFees = result.TotalFees + loan.Fees[i].Amount
  210. } else {
  211. result.TotalCredits = result.TotalCredits + loan.Fees[i].Amount
  212. }
  213. }
  214. result.CashToClose =
  215. result.TotalFees + result.TotalCredits + (estimate.Price - loan.Amount)
  216. result.LoanId = loan.Id
  217. results = append(results, result)
  218. }
  219. return results
  220. }
  221. func summarize(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  222. var estimate Estimate
  223. err := json.NewDecoder(r.Body).Decode(&estimate)
  224. if err != nil { http.Error(w, "Invalid estimate.", 422); return }
  225. results := makeResults(estimate)
  226. json.NewEncoder(w).Encode(results)
  227. }
  228. func getLoanType( db *sql.DB, id int) (LoanType, error) {
  229. types, err := getLoanTypes(db, id, 0, 0)
  230. if err != nil { return LoanType{Id: id}, err }
  231. if len(types) == 0 {
  232. return LoanType{Id: id}, errors.New("No type with that id")
  233. }
  234. return types[0], nil
  235. }
  236. func getLoanTypes( db *sql.DB, id int, user int, branch int ) (
  237. []LoanType, error) {
  238. var loans []LoanType
  239. var query = `SELECT
  240. id,
  241. user_id,
  242. branch_id,
  243. name
  244. FROM loan_type WHERE loan_type.id = CASE @e := ? WHEN 0 THEN id ELSE @e END
  245. OR
  246. loan_type.user_id = CASE @e := ? WHEN 0 THEN id ELSE @e END
  247. OR
  248. loan_type.branch_id = CASE @e := ? WHEN 0 THEN id ELSE @e END`
  249. // Should be changed to specify user
  250. rows, err := db.Query(query, id, user, branch)
  251. if err != nil {
  252. return nil, fmt.Errorf("loan_type error: %v", err)
  253. }
  254. defer rows.Close()
  255. for rows.Next() {
  256. var loan LoanType
  257. if err := rows.Scan(
  258. &loan.Id,
  259. &loan.User,
  260. &loan.Branch,
  261. &loan.Name)
  262. err != nil {
  263. log.Printf("Error occured fetching loan: %v", err)
  264. return nil, fmt.Errorf("Error occured fetching loan: %v", err)
  265. }
  266. loans = append(loans, loan)
  267. }
  268. return loans, nil
  269. }
  270. func getFees(db *sql.DB, loan int) ([]Fee, error) {
  271. var fees []Fee
  272. query := `SELECT id, loan_id, amount, perc, type, notes, name, category
  273. FROM fee
  274. WHERE loan_id = ?`
  275. rows, err := db.Query(query, loan)
  276. if err != nil {
  277. return nil, fmt.Errorf("Fee query error %v", err)
  278. }
  279. defer rows.Close()
  280. for rows.Next() {
  281. var fee Fee
  282. if err := rows.Scan(
  283. &fee.Id,
  284. &fee.LoanId,
  285. &fee.Amount,
  286. &fee.Perc,
  287. &fee.Type,
  288. &fee.Notes,
  289. &fee.Name,
  290. &fee.Category,
  291. )
  292. err != nil {
  293. return nil, fmt.Errorf("Fees scanning error: %v", err)
  294. }
  295. fees = append(fees, fee)
  296. }
  297. return fees, nil
  298. }
  299. func fetchFeesTemp(db *sql.DB, user int, branch int) ([]FeeTemplate, error) {
  300. var fees []FeeTemplate
  301. rows, err := db.Query(
  302. "SELECT * FROM fee_template " +
  303. "WHERE user_id = ? OR branch_id = ?",
  304. user, branch)
  305. if err != nil {
  306. return nil, fmt.Errorf("Fee template query error %v", err)
  307. }
  308. defer rows.Close()
  309. for rows.Next() {
  310. var fee FeeTemplate
  311. if err := rows.Scan(
  312. &fee.Id,
  313. &fee.User,
  314. &fee.Branch,
  315. &fee.Amount,
  316. &fee.Perc,
  317. &fee.Type,
  318. &fee.Notes,
  319. &fee.Name,
  320. &fee.Category,
  321. &fee.Auto)
  322. err != nil {
  323. return nil, fmt.Errorf("FeesTemplate scanning error: %v", err)
  324. }
  325. fees = append(fees, fee)
  326. }
  327. return fees, nil
  328. }
  329. // Fetch fees from the database
  330. func getFeesTemp(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  331. var fees []FeeTemplate
  332. claims, err := getClaims(r)
  333. if err != nil { w.WriteHeader(500); return }
  334. users, err := queryUsers(db, claims.Id)
  335. if err != nil { w.WriteHeader(422); return }
  336. fees, err = fetchFeesTemp(db, claims.Id, users[0].BranchId)
  337. json.NewEncoder(w).Encode(fees)
  338. }
  339. func getMi(db *sql.DB, loan int) (MI, error) {
  340. var mi MI
  341. query := `SELECT
  342. type, label, lender, rate, premium, upfront, five_year_total,
  343. initial_premium, initial_rate, initial_amount
  344. FROM mi WHERE loan_id = ?`
  345. rows, err := db.Query(query, loan)
  346. if err != nil { return mi, err }
  347. defer rows.Close()
  348. if (!rows.Next()) { return mi, nil }
  349. if err := rows.Scan(
  350. &mi.Type,
  351. &mi.Label,
  352. &mi.Lender,
  353. &mi.Rate,
  354. &mi.Premium,
  355. &mi.Upfront,
  356. &mi.FiveYearTotal,
  357. &mi.InitialAllInPremium,
  358. &mi.InitialAllInRate,
  359. &mi.InitialAmount,
  360. )
  361. err != nil {
  362. return mi, err
  363. }
  364. return mi, nil
  365. }
  366. func getBorrower(db *sql.DB, id int) (Borrower, error) {
  367. var borrower Borrower
  368. row := db.QueryRow(
  369. "SELECT * FROM borrower " +
  370. "WHERE id = ? LIMIT 1",
  371. id)
  372. if err := row.Scan(
  373. &borrower.Id,
  374. &borrower.Credit,
  375. &borrower.Income,
  376. &borrower.Num,
  377. )
  378. err != nil {
  379. return borrower, fmt.Errorf("Borrower scanning error: %v", err)
  380. }
  381. return borrower, nil
  382. }
  383. // Query Lender APIs and parse responses into MI structs
  384. func fetchMi(db *sql.DB, estimate *Estimate, pos int) []MI {
  385. var err error
  386. var loan Loan = estimate.Loans[pos]
  387. var ltv = func(l float32) string {
  388. switch {
  389. case l > 95: return "LTV97"
  390. case l > 90: return "LTV95"
  391. case l > 85: return "LTV90"
  392. default: return "LTV85"
  393. }
  394. }
  395. var term = func(t int) string {
  396. switch {
  397. case t <= 10: return "A10"
  398. case t <= 15: return "A15"
  399. case t <= 20: return "A20"
  400. case t <= 25: return "A25"
  401. case t <= 30: return "A30"
  402. default: return "A40"
  403. }
  404. }
  405. var propertyCodes = map[string]string {
  406. "Single Attached": "SFO",
  407. "Single Detached": "SFO",
  408. "Condo Lo-rise": "CON",
  409. "Condo Hi-rise": "CON",
  410. }
  411. var purposeCodes = map[string]string {
  412. "Purchase": "PUR",
  413. "Refinance": "RRT",
  414. }
  415. body, err := json.Marshal(map[string]any{
  416. "zipCode": estimate.Zip,
  417. "stateCode": "CA",
  418. "address": "",
  419. "propertyTypeCode": propertyCodes[estimate.Property],
  420. "occupancyTypeCode": "PRS",
  421. "loanPurposeCode": purposeCodes[estimate.Transaction],
  422. "loanAmount": loan.Amount,
  423. "loanToValue": ltv(loan.Ltv),
  424. "amortizationTerm": term(loan.Term),
  425. "loanTypeCode": "FXD",
  426. "duLpDecisionCode": "DAE",
  427. "loanProgramCodes": []any{},
  428. "debtToIncome": loan.Dti,
  429. "wholesaleLoan": 0,
  430. "coveragePercentageCode": "L30",
  431. "productCode": "BPM",
  432. "renewalTypeCode": "CON",
  433. "numberOfBorrowers": 1,
  434. "coBorrowerCreditScores": []any{},
  435. "borrowerCreditScore": strconv.Itoa(estimate.Borrower.Credit),
  436. "masterPolicy": nil,
  437. "selfEmployedIndicator": false,
  438. "armType": "",
  439. "userId": 44504,
  440. })
  441. if err != nil {
  442. log.Printf("Could not marshal NationalMI body: \n%v\n%v\n",
  443. bytes.NewBuffer(body), err)
  444. }
  445. req, err := http.NewRequest("POST",
  446. "https://rate-gps.nationalmi.com/rates/productRateQuote",
  447. bytes.NewBuffer(body))
  448. req.Header.Add("Content-Type", "application/json")
  449. req.AddCookie(&http.Cookie{
  450. Name: "nmirategps_email",
  451. Value: config["NationalMIEmail"]})
  452. resp, err := http.DefaultClient.Do(req)
  453. var res map[string]interface{}
  454. var result []MI
  455. if resp.StatusCode != 200 {
  456. log.Printf("the status: %v\nthe resp: %v\n the req: %v\n the body: %v\n",
  457. resp.Status, resp, req.Body, bytes.NewBuffer(body))
  458. } else {
  459. json.NewDecoder(resp.Body).Decode(&res)
  460. // estimate.Loans[pos].Mi = res
  461. // Parse res into result here
  462. }
  463. return result
  464. }
  465. // Make comparison PDF
  466. func generatePDF(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  467. }
  468. func login(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  469. var id int
  470. var role string
  471. var err error
  472. var user User
  473. json.NewDecoder(r.Body).Decode(&user)
  474. row := db.QueryRow(
  475. `SELECT id, role FROM user WHERE email = ? AND password = sha2(?, 256)`,
  476. user.Email, user.Password,
  477. )
  478. err = row.Scan(&id, &role)
  479. if err != nil {
  480. http.Error(w, "Invalid Credentials.", http.StatusUnauthorized)
  481. return
  482. }
  483. token := jwt.NewWithClaims(jwt.SigningMethodHS256,
  484. UserClaims{ Id: id, Role: role,
  485. Exp: time.Now().Add(time.Minute * 30).Format(time.UnixDate)})
  486. tokenStr, err := token.SignedString([]byte(config["JWT_SECRET"]))
  487. if err != nil {
  488. log.Println("Token could not be signed: ", err, tokenStr)
  489. http.Error(w, "Token generation error.", http.StatusInternalServerError)
  490. return
  491. }
  492. cookie := http.Cookie{Name: "skouter",
  493. Value: tokenStr,
  494. Path: "/",
  495. Expires: time.Now().Add(time.Hour * 24)}
  496. http.SetCookie(w, &cookie)
  497. _, err = w.Write([]byte(tokenStr))
  498. if err != nil {
  499. http.Error(w,
  500. "Could not complete token write.",
  501. http.StatusInternalServerError)}
  502. }
  503. func getToken(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  504. claims, err := getClaims(r)
  505. // Will verify existing signature and expiry time
  506. token := jwt.NewWithClaims(jwt.SigningMethodHS256,
  507. UserClaims{ Id: claims.Id, Role: claims.Role,
  508. Exp: time.Now().Add(time.Minute * 30).Format(time.UnixDate)})
  509. tokenStr, err := token.SignedString([]byte(config["JWT_SECRET"]))
  510. if err != nil {
  511. log.Println("Token could not be signed: ", err, tokenStr)
  512. http.Error(w, "Token generation error.", http.StatusInternalServerError)
  513. return
  514. }
  515. cookie := http.Cookie{Name: "skouter",
  516. Value: tokenStr,
  517. Path: "/",
  518. Expires: time.Now().Add(time.Hour * 24)}
  519. http.SetCookie(w, &cookie)
  520. _, err = w.Write([]byte(tokenStr))
  521. if err != nil {
  522. http.Error(w,
  523. "Could not complete token write.",
  524. http.StatusInternalServerError)}
  525. }
  526. func getClaims(r *http.Request) (UserClaims, error) {
  527. claims := new(UserClaims)
  528. _, tokenStr, found := strings.Cut(r.Header.Get("Authorization"), " ")
  529. if !found {
  530. return *claims, errors.New("Token not found")
  531. }
  532. // Pull token payload into UserClaims
  533. _, err := jwt.ParseWithClaims(tokenStr, claims,
  534. func(token *jwt.Token) (any, error) {
  535. return []byte(config["JWT_SECRET"]), nil
  536. })
  537. if err != nil {
  538. return *claims, err
  539. }
  540. if err = claims.Valid(); err != nil {
  541. return *claims, err
  542. }
  543. return *claims, nil
  544. }
  545. func guard(r *http.Request, required int) bool {
  546. claims, err := getClaims(r)
  547. if err != nil { return false }
  548. if roles[claims.Role] < required { return false }
  549. return true
  550. }
  551. func queryUsers(db *sql.DB, id int) ( []User, error ) {
  552. var users []User
  553. var query string
  554. var rows *sql.Rows
  555. var err error
  556. query = `SELECT
  557. u.id,
  558. u.email,
  559. u.first_name,
  560. u.last_name,
  561. u.branch_id,
  562. u.country,
  563. u.title,
  564. u.status,
  565. u.verified,
  566. u.role
  567. FROM user u WHERE u.id = CASE @e := ? WHEN 0 THEN u.id ELSE @e END
  568. `
  569. rows, err = db.Query(query, id)
  570. if err != nil {
  571. return users, err
  572. }
  573. defer rows.Close()
  574. for rows.Next() {
  575. var user User
  576. if err := rows.Scan(
  577. &user.Id,
  578. &user.Email,
  579. &user.FirstName,
  580. &user.LastName,
  581. &user.BranchId,
  582. &user.Country,
  583. &user.Title,
  584. &user.Status,
  585. &user.Verified,
  586. &user.Role,
  587. )
  588. err != nil {
  589. return users, err
  590. }
  591. users = append(users, user)
  592. }
  593. // Prevents runtime panics
  594. if len(users) == 0 { return users, errors.New("User not found.") }
  595. return users, nil
  596. }
  597. func insertResults(db *sql.DB, results []Result) (error){
  598. var query string
  599. var row *sql.Row
  600. var err error
  601. query = `INSERT INTO estimate_result
  602. (
  603. loan_id,
  604. loan_payment,
  605. total_monthly,
  606. total_fees,
  607. total_credits,
  608. cash_to_close
  609. )
  610. VALUES (?, ?, ?, ?, ?, ?, ?)
  611. RETURNING id
  612. `
  613. for i := range results {
  614. db.QueryRow(query,
  615. results[i].LoanId,
  616. results[i].LoanPayment,
  617. results[i].TotalMonthly,
  618. results[i].TotalFees,
  619. results[i].TotalCredits,
  620. results[i].CashToClose,
  621. )
  622. err = row.Scan(&results[i].Id)
  623. if err != nil { return err }
  624. }
  625. return nil
  626. }
  627. func insertUser(db *sql.DB, user User) (User, error){
  628. var query string
  629. var row *sql.Row
  630. var err error
  631. var id int // Inserted user's id
  632. query = `INSERT INTO user
  633. (
  634. email,
  635. first_name,
  636. last_name,
  637. password,
  638. created,
  639. role,
  640. verified,
  641. last_login
  642. )
  643. VALUES (?, ?, ?, sha2(?, 256), NOW(), ?, ?, NOW())
  644. RETURNING id
  645. `
  646. row = db.QueryRow(query,
  647. user.Email,
  648. user.FirstName,
  649. user.LastName,
  650. user.Password,
  651. user.Role,
  652. user.Verified,
  653. )
  654. err = row.Scan(&id)
  655. if err != nil { return User{}, err }
  656. users, err := queryUsers(db, id)
  657. if err != nil { return User{}, err }
  658. return users[0], nil
  659. }
  660. func updateUser(user User, db *sql.DB) error {
  661. query := `
  662. UPDATE user
  663. SET
  664. email = CASE @e := ? WHEN '' THEN email ELSE @e END,
  665. first_name = CASE @fn := ? WHEN '' THEN first_name ELSE @fn END,
  666. last_name = CASE @ln := ? WHEN '' THEN last_name ELSE @ln END,
  667. role = CASE @r := ? WHEN '' THEN role ELSE @r END,
  668. password = CASE @p := ? WHEN '' THEN password ELSE sha2(@p, 256) END
  669. WHERE id = ?
  670. `
  671. _, err := db.Exec(query,
  672. user.Email,
  673. user.FirstName,
  674. user.LastName,
  675. user.Role,
  676. user.Password,
  677. user.Id,
  678. )
  679. return err
  680. }
  681. func getUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  682. claims, err := getClaims(r)
  683. if err != nil { w.WriteHeader(500); return }
  684. users, err := queryUsers(db, claims.Id)
  685. if err != nil { w.WriteHeader(422); log.Println(err); return }
  686. json.NewEncoder(w).Encode(users)
  687. }
  688. func getUsers(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  689. users, err := queryUsers(db, 0)
  690. if err != nil {
  691. w.WriteHeader(http.StatusInternalServerError)
  692. return
  693. }
  694. json.NewEncoder(w).Encode(users)
  695. }
  696. // Updates a user using only specified values in the JSON body
  697. func patchUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  698. var user User
  699. err := json.NewDecoder(r.Body).Decode(&user)
  700. _, err = mail.ParseAddress(user.Email)
  701. if err != nil { http.Error(w, "Invalid email.", 422); return }
  702. if roles[user.Role] == 0 {
  703. http.Error(w, "Invalid role.", 422)
  704. return
  705. }
  706. err = updateUser(user, db)
  707. if err != nil { http.Error(w, "Bad form values.", 422); return }
  708. users, err := queryUsers(db, user.Id)
  709. if err != nil { http.Error(w, "Bad form values.", 422); return }
  710. json.NewEncoder(w).Encode(users[0])
  711. }
  712. // Update specified fields of the user specified in the claim
  713. func patchSelf(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  714. claim, err := getClaims(r)
  715. var user User
  716. json.NewDecoder(r.Body).Decode(&user)
  717. // First check that the target user to be updated is the same as the claim id, and
  718. // their role is unchanged.
  719. if err != nil || claim.Id != user.Id {
  720. http.Error(w, "Target user's id does not match claim.", 401)
  721. return
  722. }
  723. if claim.Role != user.Role && user.Role != "" {
  724. http.Error(w, "Administrator required to escalate role.", 401)
  725. return
  726. }
  727. patchUser(w, db, r)
  728. }
  729. func deleteUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  730. var user User
  731. err := json.NewDecoder(r.Body).Decode(&user)
  732. if err != nil {
  733. http.Error(w, "Invalid fields.", 422)
  734. return
  735. }
  736. query := `DELETE FROM user WHERE id = ?`
  737. _, err = db.Exec(query, user.Id)
  738. if err != nil {
  739. http.Error(w, "Could not delete.", 500)
  740. }
  741. }
  742. func createUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  743. var user User
  744. err := json.NewDecoder(r.Body).Decode(&user)
  745. if err != nil { http.Error(w, "Invalid fields.", 422); return }
  746. _, err = mail.ParseAddress(user.Email)
  747. if err != nil { http.Error(w, "Invalid email.", 422); return }
  748. if roles[user.Role] == 0 {
  749. http.Error(w, "Invalid role.", 422)
  750. }
  751. user, err = insertUser(db, user)
  752. if err != nil { http.Error(w, "Error creating user.", 422); return }
  753. json.NewEncoder(w).Encode(user)
  754. }
  755. func queryBorrower(db *sql.DB, id int) ( Borrower, error ) {
  756. var borrower Borrower
  757. var query string
  758. var err error
  759. query = `SELECT
  760. l.id,
  761. l.credit_score,
  762. l.num,
  763. l.monthly_income
  764. FROM borrower l WHERE l.id = ?
  765. `
  766. row := db.QueryRow(query, id)
  767. err = row.Scan(
  768. borrower.Id,
  769. borrower.Credit,
  770. borrower.Num,
  771. borrower.Income,
  772. )
  773. if err != nil {
  774. return borrower, err
  775. }
  776. return borrower, nil
  777. }
  778. // Must have an estimate ID 'e', but not necessarily a loan id 'id'
  779. func getResults(db *sql.DB, e int, id int) ( []Result, error ) {
  780. var results []Result
  781. var query string
  782. var rows *sql.Rows
  783. var err error
  784. query = `SELECT
  785. r.id,
  786. loan_id,
  787. loan_payment,
  788. total_monthly,
  789. total_fees,
  790. total_credits,
  791. cash_to_close
  792. FROM estimate_result r
  793. INNER JOIN loan
  794. ON r.loan_id = loan.id
  795. WHERE r.id = CASE @e := ? WHEN 0 THEN r.id ELSE @e END
  796. AND loan.estimate_id = ?
  797. `
  798. rows, err = db.Query(query, id, e)
  799. if err != nil {
  800. return results, err
  801. }
  802. defer rows.Close()
  803. for rows.Next() {
  804. var result Result
  805. if err := rows.Scan(
  806. &result.Id,
  807. &result.LoanId,
  808. &result.LoanPayment,
  809. &result.TotalMonthly,
  810. &result.TotalFees,
  811. &result.TotalCredits,
  812. &result.CashToClose,
  813. )
  814. err != nil {
  815. return results, err
  816. }
  817. results = append(results, result)
  818. }
  819. // Prevents runtime panics
  820. // if len(results) == 0 { return results, errors.New("Result not found.") }
  821. return results, nil
  822. }
  823. // Must have an estimate ID 'e', but not necessarily a loan id 'id'
  824. func getLoans(db *sql.DB, e int, id int) ( []Loan, error ) {
  825. var loans []Loan
  826. var query string
  827. var rows *sql.Rows
  828. var err error
  829. query = `SELECT
  830. l.id,
  831. l.type_id,
  832. l.estimate_id,
  833. l.amount,
  834. l.term,
  835. l.interest,
  836. l.ltv,
  837. l.dti,
  838. l.hoi,
  839. l.tax,
  840. l.name
  841. FROM loan l WHERE l.id = CASE @e := ? WHEN 0 THEN l.id ELSE @e END AND
  842. l.estimate_id = ?
  843. `
  844. rows, err = db.Query(query, id, e)
  845. if err != nil {
  846. return loans, err
  847. }
  848. defer rows.Close()
  849. for rows.Next() {
  850. var loan Loan
  851. if err := rows.Scan(
  852. &loan.Id,
  853. &loan.Type.Id,
  854. &loan.EstimateId,
  855. &loan.Amount,
  856. &loan.Term,
  857. &loan.Interest,
  858. &loan.Ltv,
  859. &loan.Dti,
  860. &loan.Hoi,
  861. &loan.Tax,
  862. &loan.Name,
  863. )
  864. err != nil {
  865. return loans, err
  866. }
  867. mi, err := getMi(db, loan.Id)
  868. if err != nil {
  869. return loans, err
  870. }
  871. loan.Mi = mi
  872. fees, err := getFees(db, loan.Id)
  873. if err != nil {
  874. return loans, err
  875. }
  876. loan.Fees = fees
  877. loan.Type, err = getLoanType(db, loan.Type.Id)
  878. if err != nil {
  879. return loans, err
  880. }
  881. loans = append(loans, loan)
  882. }
  883. // Prevents runtime panics
  884. if len(loans) == 0 { return loans, errors.New("Loan not found.") }
  885. return loans, nil
  886. }
  887. func getEstimates(db *sql.DB, id int, user int) ( []Estimate, error ) {
  888. var estimates []Estimate
  889. var query string
  890. var rows *sql.Rows
  891. var err error
  892. query = `SELECT
  893. id,
  894. user_id,
  895. borrower_id,
  896. transaction,
  897. price,
  898. property,
  899. occupancy,
  900. zip,
  901. pud
  902. FROM estimate WHERE id = CASE @e := ? WHEN 0 THEN id ELSE @e END AND
  903. user_id = CASE @e := ? WHEN 0 THEN user_id ELSE @e END
  904. `
  905. rows, err = db.Query(query, id, user)
  906. if err != nil {
  907. return estimates, err
  908. }
  909. defer rows.Close()
  910. for rows.Next() {
  911. var estimate Estimate
  912. if err := rows.Scan(
  913. &estimate.Id,
  914. &estimate.User,
  915. &estimate.Borrower.Id,
  916. &estimate.Transaction,
  917. &estimate.Price,
  918. &estimate.Property,
  919. &estimate.Occupancy,
  920. &estimate.Zip,
  921. &estimate.Pud,
  922. )
  923. err != nil {
  924. return estimates, err
  925. }
  926. borrower, err := getBorrower(db, estimate.Borrower.Id)
  927. if err != nil {
  928. return estimates, err
  929. }
  930. estimate.Borrower = borrower
  931. estimate.Results, err = getResults(db, estimate.Id, 0)
  932. if err != nil {
  933. return estimates, err
  934. }
  935. estimates = append(estimates, estimate)
  936. }
  937. // Prevents runtime panics
  938. if len(estimates) == 0 { return estimates, errors.New("Estimate not found.") }
  939. for i := range estimates {
  940. estimates[i].Loans, err = getLoans(db, estimates[i].Id, 0)
  941. if err != nil { return estimates, err }
  942. }
  943. return estimates, nil
  944. }
  945. // Accepts a borrower struct and returns the id of the inserted borrower and
  946. // any related error.
  947. func insertBorrower(db *sql.DB, borrower Borrower) (int, error) {
  948. var query string
  949. var row *sql.Row
  950. var err error
  951. var id int // Inserted loan's id
  952. query = `INSERT INTO borrower
  953. (
  954. credit_score,
  955. monthly_income,
  956. num
  957. )
  958. VALUES (?, ?, ?)
  959. RETURNING id
  960. `
  961. row = db.QueryRow(query,
  962. borrower.Credit,
  963. borrower.Income,
  964. borrower.Num,
  965. )
  966. err = row.Scan(&id)
  967. if err != nil { return 0, err }
  968. return id, nil
  969. }
  970. func insertMi(db *sql.DB, mi MI) (int, error) {
  971. var id int
  972. query := `INSERT INTO mi
  973. (
  974. type,
  975. label,
  976. lender,
  977. rate,
  978. premium,
  979. upfront,
  980. five_year_total,
  981. initial_premium,
  982. initial_rate,
  983. initial_amount
  984. )
  985. VALUES (?, ?, ?, ?, ?, ?, ?)
  986. RETURNING id`
  987. row := db.QueryRow(query,
  988. &mi.Type,
  989. &mi.Label,
  990. &mi.Lender,
  991. &mi.Rate,
  992. &mi.Premium,
  993. &mi.Upfront,
  994. &mi.FiveYearTotal,
  995. &mi.InitialAllInPremium,
  996. &mi.InitialAllInRate,
  997. &mi.InitialAmount,
  998. )
  999. err := row.Scan(&id)
  1000. if err != nil { return 0, err }
  1001. return id, nil
  1002. }
  1003. func insertFee(db *sql.DB, fee Fee) (int, error) {
  1004. var id int
  1005. query := `INSERT INTO fee
  1006. (loan_id, amount, perc, type, notes, name, category)
  1007. VALUES (?, ?, ?, ?, ?, ?, ?)
  1008. RETURNING id`
  1009. row := db.QueryRow(query,
  1010. fee.LoanId,
  1011. fee.Amount,
  1012. fee.Perc,
  1013. fee.Type,
  1014. fee.Notes,
  1015. fee.Name,
  1016. fee.Category,
  1017. )
  1018. err := row.Scan(&id)
  1019. if err != nil { return 0, err }
  1020. return id, nil
  1021. }
  1022. func insertLoan(db *sql.DB, loan Loan) (Loan, error){
  1023. var query string
  1024. var row *sql.Row
  1025. var err error
  1026. var id int // Inserted loan's id
  1027. query = `INSERT INTO loan
  1028. (
  1029. estimate_id,
  1030. type_id,
  1031. amount,
  1032. term,
  1033. interest,
  1034. ltv,
  1035. dti,
  1036. hoi,
  1037. tax,
  1038. name
  1039. )
  1040. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1041. RETURNING id
  1042. `
  1043. row = db.QueryRow(query,
  1044. loan.EstimateId,
  1045. loan.Type.Id,
  1046. loan.Amount,
  1047. loan.Term,
  1048. loan.Interest,
  1049. loan.Ltv,
  1050. loan.Dti,
  1051. loan.Hoi,
  1052. loan.Tax,
  1053. loan.Name,
  1054. )
  1055. err = row.Scan(&id)
  1056. if err != nil { return loan, err }
  1057. _, err = insertMi(db, loan.Mi)
  1058. if err != nil { return loan, err }
  1059. for i := range loan.Fees {
  1060. _, err := insertFee(db, loan.Fees[i])
  1061. if err != nil { return loan, err }
  1062. }
  1063. loans, err := getLoans(db, id, 0)
  1064. if err != nil { return Loan{}, err }
  1065. return loans[0], nil
  1066. }
  1067. func insertEstimate(db *sql.DB, estimate Estimate) (Estimate, error){
  1068. var query string
  1069. var row *sql.Row
  1070. var err error
  1071. // var id int // Inserted estimate's id
  1072. estimate.Borrower.Id, err = insertBorrower(db, estimate.Borrower)
  1073. if err != nil { return Estimate{}, err }
  1074. query = `INSERT INTO estimate
  1075. (
  1076. user_id,
  1077. borrower_id,
  1078. transaction,
  1079. price,
  1080. property,
  1081. occupancy,
  1082. zip,
  1083. pud
  1084. )
  1085. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  1086. RETURNING id
  1087. `
  1088. row = db.QueryRow(query,
  1089. estimate.User,
  1090. estimate.Borrower.Id,
  1091. estimate.Transaction,
  1092. estimate.Price,
  1093. estimate.Property,
  1094. estimate.Occupancy,
  1095. estimate.Zip,
  1096. estimate.Pud,
  1097. )
  1098. err = row.Scan(&estimate.Id)
  1099. if err != nil { return Estimate{}, err }
  1100. for _, l := range estimate.Loans {
  1101. l.EstimateId = estimate.Id
  1102. _, err = insertLoan(db, l)
  1103. if err != nil { return estimate, err }
  1104. }
  1105. estimates, err := getEstimates(db, estimate.Id, 0)
  1106. if err != nil { return Estimate{}, err }
  1107. return estimates[0], nil
  1108. }
  1109. func createEstimate(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1110. var estimate Estimate
  1111. err := json.NewDecoder(r.Body).Decode(&estimate)
  1112. if err != nil { http.Error(w, "Invalid fields.", 422); return }
  1113. claims, err := getClaims(r)
  1114. estimate.User = claims.Id
  1115. estimate, err = insertEstimate(db, estimate)
  1116. if err != nil { http.Error(w, err.Error(), 422); return }
  1117. estimate.Results = makeResults(estimate)
  1118. err = insertResults(db, estimate.Results)
  1119. if err != nil { http.Error(w, err.Error(), 500); return }
  1120. e, err := getEstimates(db, estimate.Id, 0)
  1121. if err != nil { http.Error(w, err.Error(), 500); return }
  1122. json.NewEncoder(w).Encode(e[0])
  1123. }
  1124. // Query all estimates that belong to the current user
  1125. func fetchEstimate(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1126. var estimates []Estimate
  1127. claims, err := getClaims(r)
  1128. estimates, err = getEstimates(db, 0, claims.Id)
  1129. if err != nil { http.Error(w, err.Error(), 500); return }
  1130. json.NewEncoder(w).Encode(estimates)
  1131. }
  1132. func checkConventional(l Loan, b Borrower) error {
  1133. if b.Credit < 620 {
  1134. return errors.New("Credit score too low for conventional loan")
  1135. }
  1136. // Buyer needs to put down 20% to avoid mortgage insurance
  1137. if (l.Ltv > 80 && l.Mi.Rate == 0) {
  1138. return errors.New(fmt.Sprintln(
  1139. l.Name,
  1140. "down payment must be 20% to avoid insurance",
  1141. ))
  1142. }
  1143. return nil
  1144. }
  1145. func checkFHA(l Loan, b Borrower) error {
  1146. if b.Credit < 500 {
  1147. return errors.New("Credit score too low for FHA loan")
  1148. }
  1149. if (l.Ltv > 96.5) {
  1150. return errors.New("FHA down payment must be at least 3.5%")
  1151. }
  1152. if (b.Credit < 580 && l.Ltv > 90) {
  1153. return errors.New("FHA down payment must be at least 10%")
  1154. }
  1155. // Debt-to-income must be below 45% if credit score is below 580.
  1156. if (b.Credit < 580 && l.Dti > 45) {
  1157. return errors.New(fmt.Sprintln(
  1158. l.Name, "debt to income is too high for credit score.",
  1159. ))
  1160. }
  1161. return nil
  1162. }
  1163. // Loan option for veterans with no set rules
  1164. func checkVA(l Loan, b Borrower) error {
  1165. return nil
  1166. }
  1167. // Loan option for residents of rural areas with no set rules
  1168. func checkUSDA(l Loan, b Borrower) error {
  1169. return nil
  1170. }
  1171. // Should also check loan amount limit maybe with an API.
  1172. func checkEstimate(e Estimate) error {
  1173. if e.Property == "" { return errors.New("Empty property type") }
  1174. if e.Price == 0 { return errors.New("Empty property price") }
  1175. if e.Borrower.Num == 0 {
  1176. return errors.New("Missing number of borrowers")
  1177. }
  1178. if e.Borrower.Credit == 0 {
  1179. return errors.New("Missing borrower credit score")
  1180. }
  1181. if e.Borrower.Income == 0 {
  1182. return errors.New("Missing borrower credit income")
  1183. }
  1184. for _, l := range e.Loans {
  1185. if l.Amount == 0 {
  1186. return errors.New(fmt.Sprintln(l.Name, "loan amount cannot be zero"))
  1187. }
  1188. if l.Term == 0 {
  1189. return errors.New(fmt.Sprintln(l.Name, "loan term cannot be zero"))
  1190. }
  1191. if l.Interest == 0 {
  1192. return errors.New(fmt.Sprintln(l.Name, "loan interest cannot be zero"))
  1193. }
  1194. // Can be used to check rules for specific loan types
  1195. var err error
  1196. switch l.Type.Id {
  1197. case 1:
  1198. err = checkConventional(l, e.Borrower)
  1199. case 2:
  1200. err = checkFHA(l, e.Borrower)
  1201. case 3:
  1202. err = checkVA(l, e.Borrower)
  1203. case 4:
  1204. err = checkUSDA(l, e.Borrower)
  1205. default:
  1206. err = errors.New("Invalid loan type")
  1207. }
  1208. if err != nil { return err }
  1209. }
  1210. return nil
  1211. }
  1212. func validateEstimate(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1213. var estimate Estimate
  1214. err := json.NewDecoder(r.Body).Decode(&estimate)
  1215. if err != nil { http.Error(w, err.Error(), 422); return }
  1216. err = checkEstimate(estimate)
  1217. if err != nil { http.Error(w, err.Error(), 406); return }
  1218. }
  1219. func api(w http.ResponseWriter, r *http.Request) {
  1220. var args []string
  1221. p := r.URL.Path
  1222. db, err := sql.Open("mysql",
  1223. fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/skouter",
  1224. config["DBUser"],
  1225. config["DBPass"]))
  1226. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  1227. err = db.Ping()
  1228. if err != nil {
  1229. fmt.Println("Bad database configuration: %v\n", err)
  1230. panic(err)
  1231. // maybe os.Exit(1) instead
  1232. }
  1233. switch {
  1234. case match(p, "/api/login", &args) &&
  1235. r.Method == http.MethodPost:
  1236. login(w, db, r)
  1237. case match(p, "/api/token", &args) &&
  1238. r.Method == http.MethodGet && guard(r, 1):
  1239. getToken(w, db, r)
  1240. case match(p, "/api/users", &args) && // Array of all users
  1241. r.Method == http.MethodGet && guard(r, 3):
  1242. getUsers(w, db, r)
  1243. case match(p, "/api/user", &args) &&
  1244. r.Method == http.MethodGet && guard(r, 1):
  1245. getUser(w, db, r)
  1246. case match(p, "/api/user", &args) &&
  1247. r.Method == http.MethodPost &&
  1248. guard(r, 3):
  1249. createUser(w, db, r)
  1250. case match(p, "/api/user", &args) &&
  1251. r.Method == http.MethodPatch &&
  1252. guard(r, 3): // For admin to modify any user
  1253. patchUser(w, db, r)
  1254. case match(p, "/api/user", &args) &&
  1255. r.Method == http.MethodPatch &&
  1256. guard(r, 2): // For employees to modify own accounts
  1257. patchSelf(w, db, r)
  1258. case match(p, "/api/user", &args) &&
  1259. r.Method == http.MethodDelete &&
  1260. guard(r, 3):
  1261. deleteUser(w, db, r)
  1262. case match(p, "/api/fees", &args) &&
  1263. r.Method == http.MethodGet &&
  1264. guard(r, 1):
  1265. getFeesTemp(w, db, r)
  1266. case match(p, "/api/estimates", &args) &&
  1267. r.Method == http.MethodGet &&
  1268. guard(r, 1):
  1269. fetchEstimate(w, db, r)
  1270. case match(p, "/api/estimate", &args) &&
  1271. r.Method == http.MethodPost &&
  1272. guard(r, 1):
  1273. createEstimate(w, db, r)
  1274. case match(p, "/api/estimate/validate", &args) &&
  1275. r.Method == http.MethodPost &&
  1276. guard(r, 1):
  1277. validateEstimate(w, db, r)
  1278. case match(p, "/api/estimate/summarize", &args) &&
  1279. r.Method == http.MethodPost &&
  1280. guard(r, 1):
  1281. summarize(w, db, r)
  1282. default:
  1283. http.Error(w, "Invalid route or token", 404)
  1284. }
  1285. db.Close()
  1286. }
  1287. func route(w http.ResponseWriter, r *http.Request) {
  1288. var page Page
  1289. var args []string
  1290. p := r.URL.Path
  1291. switch {
  1292. case r.Method == "GET" && match(p, "/", &args):
  1293. page = pages[ "home" ]
  1294. case match(p, "/terms", &args):
  1295. page = pages[ "terms" ]
  1296. case match(p, "/app", &args):
  1297. page = pages[ "app" ]
  1298. default:
  1299. http.NotFound(w, r)
  1300. return
  1301. }
  1302. page.Render(w)
  1303. }
  1304. func main() {
  1305. files := http.FileServer(http.Dir(""))
  1306. http.Handle("/assets/", files)
  1307. http.HandleFunc("/api/", api)
  1308. http.HandleFunc("/", route)
  1309. log.Fatal(http.ListenAndServe(address, nil))
  1310. }