Skip to content

Commit

Permalink
feat(Tenant): added support when on default hostname for tenant query…
Browse files Browse the repository at this point in the history
… support
  • Loading branch information
crisner1978 committed Jun 3, 2024
1 parent 793db42 commit 74afe70
Show file tree
Hide file tree
Showing 13 changed files with 126 additions and 138 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
"sonner": "^0.3.0",
"tailwind-merge": "^1.12.0",
"tailwind-scrollbar-hide": "^1.1.7",

"us-zcta-counties": "^0.0.2",
"zod": "^3.21.4",
"zustand": "^4.3.9"
Expand Down
15 changes: 13 additions & 2 deletions src/app/[vin]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,19 @@ import Form from '@/components/Form'
import useCustomer from '../../store'
import StoreInitializer from '../../store/StoreInitializer'
import { getVehicleById, getVehicleDetails } from '@/lib/actions/vehicle.action'
import getTenant from '@/lib/actions/getTeanant'

export default async function VinPage({ params }: { params: { vin: string } }) {
interface VinPageProps {
params: {
vin: string
}
searchParams: {
tenant?: string
}
}

export default async function VinPage({ params, searchParams }: VinPageProps) {
const tenantQuery = await getTenant(searchParams)
const vdp =
params.vin.length < 17 ? await getVehicleById(params.vin) : await getVehicleDetails(params.vin)

Expand All @@ -19,7 +30,7 @@ export default async function VinPage({ params }: { params: { vin: string } }) {

return (
<div className='mx-auto my-8 mb-16 max-w-[1200px] py-10 max-[1200px]:my-0 sm:p-4 md:p-10'>
<Form vdp={vdp} />
<Form vdp={vdp} tenant={tenantQuery} />
<StoreInitializer
vehicleMileage={vdp?.miles}
vehiclePrice={vdp?.price}
Expand Down
45 changes: 30 additions & 15 deletions src/app/api/credit-app/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,53 @@ import { slackMsgRequest } from '@/utils/slackMsg'
import { NextResponse } from 'next/server'
import { withAppRouterHighlight } from '@/utils/withAppRouterHighlight'

type RouteOnePayload = {
primaryBuyer: Record<string, any>
vehicles: Record<string, any>[]
tenant: string
buyerRelationship?: string
coBuyer?: Record<string, any>
trade?: {
tradeInAllowance: number
id: string
lienholder: string
}
}

const slackUrl = process.env.SLACK_WEBHOOK_URL
const TENANT = process.env.NODE_ENV === 'development' ? 'CLOUD-DEV' : 'CLOUD-PROD'
export const maxDuration = 300

export const POST = withAppRouterHighlight(async (request: Request) => {
let payload: Record<string, any> = {
tenant: TENANT,
}
const data = await request.json()
const { primary, secondary, vehicle, tradeIn } = data
const { primary, secondary, vehicle, tradeIn, tenant } = data

const primaryRequest = formatApplicant(primary)
payload['primaryBuyer'] = primaryRequest?.app
payload['vehicles'] = [vehicle]
let payload: RouteOnePayload = {
primaryBuyer: formatApplicant(primary).app,
vehicles: [vehicle],
tenant,
}

if (secondary) {
const secondaryRequest = formatApplicant(secondary)
const buyerRelationship = secondaryRequest?.app?.buyerRelationship
delete secondaryRequest?.app.buyerRelationship
payload['coBuyer'] = secondaryRequest?.app
payload['buyerRelationship'] = buyerRelationship
payload['buyerRelationship'] = secondary.buyerRelationship
delete secondary.buyerRelationship
payload['coBuyer'] = formatApplicant(secondary).app
}

if (tradeIn) {
payload['trade'] = tradeIn
payload['trade'] = {
tradeInAllowance: tradeIn?.allowance,
id: tradeIn?.id,
lienholder: tradeIn?.lienholder,
}
}

console.log('🚀 ~ CREDIT_API_DRIVLY ~ payload:', payload)

try {
await slackMsgRequest({ url: slackUrl, data })
const d = await fetch(`${process.env.CREDIT_API_DRIVLY}/applications`, {
method: 'POST',
body: JSON.stringify({ ...payload }),
body: JSON.stringify(payload),
headers: { 'Content-Type': 'application/json' },
})

Expand Down
14 changes: 11 additions & 3 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import Form from '@/components/Form'
import getTenant from '@/lib/actions/getTeanant'

interface HomePageProps {
searchParams: {
tenant?: string
}
}

export default async function HomePage({ searchParams }: HomePageProps) {
const tenantQuery = await getTenant(searchParams)

export default function HomePage() {

return (
<div className='mx-auto my-8 mb-16 max-w-[1200px] py-10 max-[1200px]:my-0 sm:p-4 md:p-10'>
<Form />
<Form tenant={tenantQuery} />
</div>
)
}
25 changes: 5 additions & 20 deletions src/components/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,18 @@ const defaultValues = {
dateOfBirth: moment().subtract(18, 'years').format('DD/MM/YYYY'),
ssn: '',
residenceTypeCode: '',
employedPrimary: 'YES',
coEmployedJoint: 'YES',
employmentStatusCode: 'Full Time',
co_employmentStatusCode: 'Full Time',
joint: false,
agree: false,
}

type Props = {
tenant: string
vdp?: VehicleDetailProps | null
}

export default function Form({ vdp }: Props) {
export default function Form({ tenant, vdp }: Props) {
const [customer, setCustomer] = useCustomer((s) => [s.customer, s.setCustomer])
const [isError, setError] = useState(false)
const { handleOnChange } = useHasChanged()
Expand All @@ -54,6 +53,8 @@ export default function Form({ vdp }: Props) {
defaultValues: {
...defaultValues,
...searchParamValues,
joint: searchParamValues?.joint === 'true' ? true : false,
sameAddress: searchParamValues?.sameAddress === 'true' ? true : false,
vehicleYear: vdp?.year,
vehicleMake: vdp?.make,
vehicleModel: vdp?.model,
Expand Down Expand Up @@ -97,33 +98,17 @@ export default function Form({ vdp }: Props) {
return
}

let trade: Record<string, any> = {}
const { sameAddress, ...rest } = data
const toastId = toast.loading('Submitting your application...')
let formData = formatRequest(rest)
console.log('formData', formData)

if (formData?.tradeIn !== null) {
const { tradeIn, ...rest } = formData

trade = customer?.tradeInfo
formData = {
...rest,
tradeIn: {
tradeInAllowance: trade?.tradeInAllowance,
id: trade?.id,
lienholder: trade?.lienholder,
},
}
}

try {
const request = await fetch('/api/credit-app', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
body: JSON.stringify({ tenant, ...formData }),
}).then((res) => res.json())
console.log('request', request)

Expand Down
2 changes: 1 addition & 1 deletion src/components/sections/TradeInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const TradeInfo = ({ errors, isSubmitting }: TradeInfoProps) => {
})
const customer = useCustomer((s) => s.customer)
const methods = useFormContext()
const { register, watch, setValue, setFocus } = methods
const { register, watch } = methods
const watchLien = watch('tradeInLienIndicator')
const islien = watchLien === 'Y'

Expand Down
5 changes: 5 additions & 0 deletions src/hooks/usePayoffLenders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ const usePayoffLenders = () => {
}, [isTrade, setValue])

useEffect(() => {
/**
* Fetches the payoff lenders from the API and sets the sorted lenders in the state.
*
* Test Lender: Ally Test FS
*/
const getPayoffLenders = async () => {
const { data } = await fetch('https://credit.api.driv.ly/fields').then((res) => res.json())
const lenders = await data?.ancillaryServices?.[0].financeSourceList
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/usePayoffQuery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ const usePayoffQuery = ({
const lenderString = lenders.find((item) => item.fsId === watchLienName)?.fsName
toast.success('Payoff Quote Found', { id: toastId })
setValue('tradeInAllowance', response?.allowance)
setValue('tradeInLienholder', lenderString)
setValue('tradeInId', response?.id)
setValue('tradeInGrossPayOffAmount', response?.quote?.grossPayOffAmount)
setCustomer({
...customer,
Expand Down
10 changes: 10 additions & 0 deletions src/lib/actions/getTeanant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use server'

import { headers } from 'next/headers'
import { HOSTNAMES, TENANT } from '../constants'

export default async function getTenant(params: { tenant?: string }) {
const hostName = headers().get('x-forwarded-host') || headers().get('host')
const shouldSupportTenant = HOSTNAMES.some((host) => hostName?.includes(host))
return shouldSupportTenant && params?.tenant ? params.tenant : TENANT
}
3 changes: 3 additions & 0 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export const CONSTANTS = {
NEXT_PUBLIC_HIGHLIGHT_PROJECT_ID: process.env.NEXT_PUBLIC_HIGHLIGHT_PROJECT_ID as string,
}

export const HOSTNAMES = ['localhost', 'credit.driv.ly'] as const
export const TENANT = process.env.NODE_ENV === 'development' ? 'CLOUD-DEV' : 'CLOUD-PROD'
18 changes: 1 addition & 17 deletions src/utils/formatApplicant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export const formatApplicant = (applicant: Record<string, any>) => {

const pCounty = zcta.find({ zip: applicant?.zipCode })

console.log('pCounty', pCounty)
const currentAddressMonths = addressYears * 12 + addressMonths
const previousAddressMonths = prevAddressYears * 12 + prevAddressMonths
const currentJobMonths = timeOnJobYears * 12 + timeOnJobMonths
Expand All @@ -35,15 +34,11 @@ export const formatApplicant = (applicant: Record<string, any>) => {
monthsOnJob: currentJobMonths,
previousMonthsOnJob: prevJobMonths,
prevMonthsAtAddress: previousAddressMonths,

county: pCounty?.county,
countryCode: 'US',
// residenceTypeCode: '1', added 1 own 2 rent 3 others
educationLevelCode: '',
incomeIntervalCode: 'MO',
// otherIncomeSourceCode: otherIncome,
// form asks for monthly income
incomeAmount: Number(applicant?.incomeAmount?.replaceAll(/\$|,/g, '')),
incomeAmount: Number(applicant?.incomeAmount?.replaceAll(/\$|,/g, '')), // form asks for monthly income
otherIncomeAmount: Number(applicant?.otherIncomeAmount?.replaceAll(/\$|,/g, '')),
phone: parsePhoneNumber(applicant?.phone),
employerPhone: parsePhoneNumber(applicant?.employerPhone),
Expand All @@ -63,17 +58,6 @@ export const formatApplicant = (applicant: Record<string, any>) => {
'prevTimeOnJobYears',
'prevTimeOnJobMonths',
'agree',
// 'licenseNumber',
// 'licenseState',
// 'licenseExp',
// 'prevEmployerPhone',
// 'prevIncomeAmount',
'coEmployedJoint',
'year',
'make',
'model',
'price',
'vin',
]

fieldsToDelete.forEach((field) => delete formattedApp[field])
Expand Down
4 changes: 1 addition & 3 deletions src/utils/formatRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ export function formatRequest(data: any) {
const { joint } = data

delete data.joint
delete data.employedPrimary
delete data.employedJoint

let primary: Record<string, any> = {}
let secondary: Record<string, any> | null = {}
Expand All @@ -20,7 +18,7 @@ export function formatRequest(data: any) {
let newKey = key.replace('vehicle', '')
newKey = newKey.charAt(0).toLowerCase() + newKey.slice(1)
vehicle[newKey] = data[key]
} else if (key.includes('tradeIn') && data[key]?.length > 0) {
} else if (key.includes('tradeIn') && data[key]) {
let newKey = key.replace('tradeIn', '')
newKey = newKey.charAt(0).toLowerCase() + newKey.slice(1)
tradeIn[newKey] = data[key]
Expand Down
Loading

0 comments on commit 74afe70

Please sign in to comment.