package main import ( "net/http" "log" "sync" "regexp" "html/template" "database/sql" _ "github.com/go-sql-driver/mysql" "fmt" "encoding/json" // "io" "strconv" "bytes" ) type Page struct { tpl *template.Template Title string Name string } type Borrower struct { Id int `json:"id"` Credit int `json:"credit"` Income int `json:"income"` Num int `json:"num"` } type FeeTemplate struct { Id int `json:"id"` User int `json:"user"` Branch int `json:"branch"` Amount int `json:"amount"` Perc int `json:"perc"` Type string `json:"type"` Notes string `json:"notes"` Name string `json:"name"` Category string `json:"category"` Auto bool `json:"auto"` } type Fee struct { Id int `json:"id"` LoanId int `json:"loan_id"` Amount int `json:"amount"` Perc int `json:"perc"` Type string `json:"type"` Notes string `json:"notes"` Name string `json:"name"` Category string `json:"category"` } type LoanType struct { Id int `json:"id"` User int `json:"user"` Branch int `json:"branch"` Name string `json:"name"` } type Loan struct { Id int `json:id` EstimateId int `json:estimate_id` Type LoanType `json:"loanType"` Amount int `json:"loanAmount"` Term int `json:"term"` Ltv float32 `json:"ltv"` Dti float32 `json:"dti"` Hoi int `json:"hoi"` Interest int `json:"interest"` Lender string `json:"lender"` MiName string `json:"miName"` MiAmount int `json:"miAmount"` Mi map[string]interface{} `json:"mi"` Fees []Fee `json:"fees"` Name string `json:"name"` } type MI struct { Id int } type Estimate struct { Id int `json:"id"` User int `json:"user"` Borrower Borrower `json:"borrower"` Transaction string `json:"transaction"` Price int `json:"price"` Property string `json:"property"` Occupancy string `json:"occupancy"` Zip string `json:"zip"` Pud bool `json:"pud"` Loans []Loan `json:"loans"` } var ( regexen = make(map[string]*regexp.Regexp) relock sync.Mutex address = "127.0.0.1:8001" ) var paths = map[string]string { "home": "home.tpl", "terms": "terms.tpl", "app": "app.tpl", } var pages = map[string]Page { "home": cache("home", "Home"), "terms": cache("terms", "Terms and Conditions"), "app": cache("app", "App"), } func cache(name string, title string) Page { var p = []string{"master.tpl", paths[name]} tpl := template.Must(template.ParseFiles(p...)) return Page{tpl: tpl, Title: title, Name: name, } } func (page Page) Render(w http.ResponseWriter) { err := page.tpl.Execute(w, page) if err != nil { log.Print(err) } } func match(path, pattern string, args *[]string) bool { relock.Lock() defer relock.Unlock() regex := regexen[pattern] if regex == nil { regex = regexp.MustCompile("^" + pattern + "$") regexen[pattern] = regex } matches := regex.FindStringSubmatch(path) if len(matches) <= 0 { return false } *args = matches[1:] return true } func getLoanType( db *sql.DB, user int, branch int, isUser bool) ([]LoanType, error) { var loans []LoanType // Should be changed to specify user rows, err := db.Query(`SELECT * FROM loan_type WHERE user_id = ? AND branch_id = ? ` + "OR (user_id = 0 AND branch_id = 0)", user, branch) if err != nil { return nil, fmt.Errorf("loan_type error: %v", err) } defer rows.Close() for rows.Next() { var loan LoanType if err := rows.Scan( &loan.Id, &loan.User, &loan.Branch, &loan.Name) err != nil { log.Printf("Error occured fetching loan: %v", err) return nil, fmt.Errorf("Error occured fetching loan: %v", err) } loans = append(loans, loan) } log.Printf("The loans: %v", loans) return loans, nil } func getEstimate(db *sql.DB, id int) (Estimate, error) { var estimate Estimate var err error query := `SELECT e.id, e.user_id, e.transaction, e.price, e.property, e.occupancy, e.zip, e.pud, b.id, b.credit_score, b.monthly_income, b.num FROM estimate e INNER JOIN borrower b ON e.borrower_id = b.id WHERE e.id = ? ` // Inner join should always be valid because a borrower is a required // foreign key. row := db.QueryRow(query, id) if err = row.Scan( &estimate.Id, &estimate.User, &estimate.Transaction, &estimate.Price, &estimate.Property, &estimate.Occupancy, &estimate.Zip, &estimate.Pud, &estimate.Borrower.Id, &estimate.Borrower.Credit, &estimate.Borrower.Income, &estimate.Borrower.Num, ) err != nil { return estimate, fmt.Errorf("Estimate scanning error: %v", err) } estimate.Loans, err = getLoans(db, estimate.Id) return estimate, err } func getFees(db *sql.DB, loan int) ([]Fee, error) { var fees []Fee rows, err := db.Query( "SELECT * FROM fees " + "WHERE loan_id = ?", loan) if err != nil { return nil, fmt.Errorf("Fee query error %v", err) } defer rows.Close() for rows.Next() { var fee Fee if err := rows.Scan( &fee.Id, &fee.LoanId, &fee.Amount, &fee.Perc, &fee.Type, &fee.Notes, &fee.Name, &fee.Category, ) err != nil { return nil, fmt.Errorf("Fees scanning error: %v", err) } fees = append(fees, fee) } return fees, nil } // Fetch fees from the database func getFeesTemp(db *sql.DB, user int) ([]FeeTemplate, error) { var fees []FeeTemplate rows, err := db.Query( "SELECT * FROM fee_template " + "WHERE user_id = ? OR user_id = 0", user) if err != nil { return nil, fmt.Errorf("Fee template query error %v", err) } defer rows.Close() for rows.Next() { var fee FeeTemplate if err := rows.Scan( &fee.Id, &fee.User, &fee.Branch, &fee.Amount, &fee.Perc, &fee.Type, &fee.Notes, &fee.Name, &fee.Category, &fee.Auto) err != nil { return nil, fmt.Errorf("FeesTemplate scanning error: %v", err) } fees = append(fees, fee) } return fees, nil } func getLoans(db *sql.DB, estimate int) ([]Loan, error) { var loans []Loan query := `SELECT l.id, l.amount, l.term, l.interest, l.ltv, l.dti, l.hoi, l.mi_name, l.mi_amount, lt.id, lt.user_id, lt.branch_id, lt.name FROM loan l INNER JOIN loan_type lt ON l.type_id = lt.id WHERE l.estimate_id = ? ` rows, err := db.Query(query, estimate) if err != nil { return nil, fmt.Errorf("Loan query error %v", err) } defer rows.Close() for rows.Next() { var loan Loan if err := rows.Scan( &loan.Id, &loan.Amount, &loan.Term, &loan.Interest, &loan.Ltv, &loan.Dti, &loan.Hoi, &loan.MiName, &loan.MiAmount, &loan.Type.Id, &loan.Type.User, &loan.Type.Branch, &loan.Type.Name, ) err != nil { return loans, fmt.Errorf("Loans scanning error: %v", err) } loans = append(loans, loan) } return loans, nil } func getBorrower(db *sql.DB, id int) (Borrower, error) { var borrower Borrower row := db.QueryRow( "SELECT * FROM borrower " + "WHERE id = ? LIMIT 1", id) if err := row.Scan( &borrower.Id, &borrower.Credit, &borrower.Income, &borrower.Num, ) err != nil { return borrower, fmt.Errorf("Borrower scanning error: %v", err) } return borrower, nil } func getMi(db *sql.DB, estimate *Estimate, pos int) (*Estimate) { var err error var loan Loan = estimate.Loans[pos] var ltv = func(l float32) string { switch { case l > 95: return "LTV97" case l > 90: return "LTV95" case l > 85: return "LTV90" default: return "LTV85" } } var term = func(t int) string { switch { case t <= 10: return "A10" case t <= 15: return "A15" case t <= 20: return "A20" case t <= 25: return "A25" case t <= 30: return "A30" default: return "A40" } } var propertyCodes = map[string]string { "Single Attached": "SFO", "Single Detached": "SFO", "Condo Lo-rise": "CON", "Condo Hi-rise": "CON", } var purposeCodes = map[string]string { "Purchase": "PUR", "Refinance": "RRT", } body, err := json.Marshal(map[string]any{ "zipCode": estimate.Zip, "stateCode": "CA", "address": "", "propertyTypeCode": propertyCodes[estimate.Property], "occupancyTypeCode": "PRS", "loanPurposeCode": purposeCodes[estimate.Transaction], "loanAmount": loan.Amount, "loanToValue": ltv(loan.Ltv), "amortizationTerm": term(loan.Term), "loanTypeCode": "FXD", "duLpDecisionCode": "DAE", "loanProgramCodes": []any{}, "debtToIncome": loan.Dti, "wholesaleLoan": 0, "coveragePercentageCode": "L30", "productCode": "BPM", "renewalTypeCode": "CON", "numberOfBorrowers": 1, "coBorrowerCreditScores": []any{}, "borrowerCreditScore": strconv.Itoa(estimate.Borrower.Credit), "masterPolicy": nil, "selfEmployedIndicator": false, "armType": "", "userId": 44504, }) if err != nil { log.Printf("Could not marshal NationalMI body: \n%v\n%v\n", bytes.NewBuffer(body), err) } req, err := http.NewRequest("POST", "https://rate-gps.nationalmi.com/rates/productRateQuote", bytes.NewBuffer(body)) req.Header.Add("Content-Type", "application/json") req.AddCookie(&http.Cookie{ Name: "nmirategps_email", Value: config["NationalMIEmail"]}) resp, err := http.DefaultClient.Do(req) var res map[string]interface{} if resp.StatusCode != 200 { log.Printf("the status: %v\nthe resp: %v\n the req: %v\n the body: %v\n", resp.Status, resp, req.Body, bytes.NewBuffer(body)) } else { json.NewDecoder(resp.Body).Decode(&res) log.Printf("the valid resp: %v", res) estimate.Loans[pos].Mi = res } return estimate } func validateEstimate() { return } func route(w http.ResponseWriter, r *http.Request) { var page Page var args []string p := r.URL.Path switch { case r.Method == "GET" && match(p, "/", &args): page = pages[ "home" ] case match(p, "/terms", &args): page = pages[ "terms" ] case match(p, "/app", &args): page = pages[ "app" ] case match(p, "/assets", &args): page = pages[ "app" ] default: http.NotFound(w, r) return } page.Render(w) } func api(w http.ResponseWriter, r *http.Request) { var args []string // var response string p := r.URL.Path db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/skouter", config["DBUser"], config["DBPass"])) w.Header().Set("Content-Type", "application/json; charset=UTF-8") err = db.Ping() if err != nil { print("Bad database configuration: %v", err) panic(err) // maybe os.Exit(1) instead } switch { case match(p, "/api/loans", &args): resp, err := getLoanType(db, 0, 0, true) if resp != nil { json.NewEncoder(w).Encode(resp) } else { json.NewEncoder(w).Encode(err) } case match(p, "/api/fees", &args): resp, err := getFeesTemp(db, 0) if resp != nil { json.NewEncoder(w).Encode(resp) } else { json.NewEncoder(w).Encode(err) } case match(p, "/api/mi", &args): var err error est, err := getEstimate(db, 1) if err != nil { json.NewEncoder(w).Encode(err) log.Println("error occured:", err) break } json.NewEncoder(w).Encode(getMi(db, &est, 0)) // if err != nil { // json.NewEncoder(w).Encode(err) // break // } else { // json.NewEncoder(w).Encode(resp) // } } } func main() { files := http.FileServer(http.Dir("")) http.Handle("/assets/", files) http.HandleFunc("/api/", api) http.HandleFunc("/", route) log.Fatal(http.ListenAndServe(address, nil)) }