Add PayU settings and dynamic QR generation
Some checks failed
build-and-deploy / build-deploy (push) Failing after 29s
Some checks failed
build-and-deploy / build-deploy (push) Failing after 29s
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
package com.android.trisolarisserver.controller
|
||||
|
||||
import com.android.trisolarisserver.component.PropertyAccess
|
||||
import com.android.trisolarisserver.controller.dto.PayuQrGenerateRequest
|
||||
import com.android.trisolarisserver.controller.dto.PayuQrGenerateResponse
|
||||
import com.android.trisolarisserver.models.booking.BookingStatus
|
||||
import com.android.trisolarisserver.models.payment.PayuQrRequest
|
||||
import com.android.trisolarisserver.models.payment.PayuQrStatus
|
||||
import com.android.trisolarisserver.models.property.Role
|
||||
import com.android.trisolarisserver.repo.BookingRepo
|
||||
import com.android.trisolarisserver.repo.PaymentRepo
|
||||
import com.android.trisolarisserver.repo.PayuQrRequestRepo
|
||||
import com.android.trisolarisserver.repo.PayuSettingsRepo
|
||||
import com.android.trisolarisserver.repo.RoomStayRepo
|
||||
import com.android.trisolarisserver.security.MyPrincipal
|
||||
import org.springframework.http.HttpStatus
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
import org.springframework.util.LinkedMultiValueMap
|
||||
import org.springframework.web.bind.annotation.PathVariable
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
import org.springframework.web.bind.annotation.RequestBody
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
import org.springframework.web.client.RestTemplate
|
||||
import org.springframework.web.server.ResponseStatusException
|
||||
import java.security.MessageDigest
|
||||
import java.time.OffsetDateTime
|
||||
import java.util.UUID
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/properties/{propertyId}/bookings/{bookingId}/payments/payu")
|
||||
class PayuQrPayments(
|
||||
private val propertyAccess: PropertyAccess,
|
||||
private val bookingRepo: BookingRepo,
|
||||
private val roomStayRepo: RoomStayRepo,
|
||||
private val paymentRepo: PaymentRepo,
|
||||
private val payuSettingsRepo: PayuSettingsRepo,
|
||||
private val payuQrRequestRepo: PayuQrRequestRepo,
|
||||
private val restTemplate: RestTemplate
|
||||
) {
|
||||
|
||||
@PostMapping("/qr")
|
||||
@Transactional
|
||||
fun generateQr(
|
||||
@PathVariable propertyId: UUID,
|
||||
@PathVariable bookingId: UUID,
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
@RequestBody request: PayuQrGenerateRequest
|
||||
): PayuQrGenerateResponse {
|
||||
requireRole(propertyAccess, propertyId, principal, Role.ADMIN, Role.MANAGER, Role.FINANCE)
|
||||
|
||||
val booking = bookingRepo.findById(bookingId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Booking not found")
|
||||
}
|
||||
if (booking.property.id != propertyId) {
|
||||
throw ResponseStatusException(HttpStatus.NOT_FOUND, "Booking not found for property")
|
||||
}
|
||||
if (booking.status == BookingStatus.CANCELLED || booking.status == BookingStatus.NO_SHOW || booking.status == BookingStatus.CHECKED_OUT) {
|
||||
throw ResponseStatusException(HttpStatus.CONFLICT, "Booking closed")
|
||||
}
|
||||
|
||||
val settings = payuSettingsRepo.findByPropertyId(propertyId)
|
||||
?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "PayU settings not configured")
|
||||
val salt = pickSalt(settings)
|
||||
|
||||
val stays = roomStayRepo.findByBookingId(bookingId)
|
||||
val expectedPay = computeExpectedPay(stays, booking.property.timezone)
|
||||
val collected = paymentRepo.sumAmountByBookingId(bookingId)
|
||||
val pending = expectedPay - collected
|
||||
if (pending <= 0) {
|
||||
throw ResponseStatusException(HttpStatus.CONFLICT, "No pending amount")
|
||||
}
|
||||
|
||||
val txnid = "QR${bookingId.toString().substring(0, 8)}${System.currentTimeMillis()}"
|
||||
val productInfo = "Booking $bookingId"
|
||||
val firstname = request.customerName?.trim()?.ifBlank { null } ?: "Guest"
|
||||
val email = request.customerEmail?.trim()?.ifBlank { null } ?: "guest@example.com"
|
||||
val phone = request.customerPhone?.trim()?.ifBlank { null } ?: ""
|
||||
val amount = String.format("%.2f", pending.toDouble())
|
||||
|
||||
val udf1 = bookingId.toString()
|
||||
val udf2 = propertyId.toString()
|
||||
val udf3 = ""
|
||||
val udf4 = ""
|
||||
val udf5 = ""
|
||||
val hash = sha512(
|
||||
listOf(
|
||||
settings.merchantKey,
|
||||
txnid,
|
||||
amount,
|
||||
productInfo,
|
||||
firstname,
|
||||
email,
|
||||
udf1,
|
||||
udf2,
|
||||
udf3,
|
||||
udf4,
|
||||
udf5,
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
salt
|
||||
).joinToString("|")
|
||||
)
|
||||
|
||||
val form = LinkedMultiValueMap<String, String>().apply {
|
||||
add("key", settings.merchantKey)
|
||||
add("txnid", txnid)
|
||||
add("amount", amount)
|
||||
add("productinfo", productInfo)
|
||||
add("firstname", firstname)
|
||||
add("email", email)
|
||||
add("phone", phone)
|
||||
add("pg", "DBQR")
|
||||
add("bankcode", "UPIDBQR")
|
||||
add("hash", hash)
|
||||
add("udf1", udf1)
|
||||
add("udf2", udf2)
|
||||
add("txn_s2s_flow", "4")
|
||||
add("s2s_client_ip", "127.0.0.1")
|
||||
add("s2s_device_info", "TrisolarisServer")
|
||||
request.expiryMinutes?.let { add("expiry_time", it.toString()) }
|
||||
}
|
||||
|
||||
val requestPayload = form.entries.joinToString("&") { entry ->
|
||||
entry.value.joinToString("&") { value -> "${entry.key}=$value" }
|
||||
}
|
||||
|
||||
val record = payuQrRequestRepo.save(
|
||||
PayuQrRequest(
|
||||
property = booking.property,
|
||||
booking = booking,
|
||||
txnid = txnid,
|
||||
amount = pending,
|
||||
currency = booking.property.currency,
|
||||
status = PayuQrStatus.CREATED,
|
||||
requestPayload = requestPayload,
|
||||
createdAt = OffsetDateTime.now()
|
||||
)
|
||||
)
|
||||
|
||||
val headers = org.springframework.http.HttpHeaders().apply {
|
||||
contentType = MediaType.APPLICATION_FORM_URLENCODED
|
||||
}
|
||||
val entity = org.springframework.http.HttpEntity(form, headers)
|
||||
val response = restTemplate.postForEntity(settings.baseUrl, entity, String::class.java)
|
||||
val responseBody = response.body ?: ""
|
||||
|
||||
record.responsePayload = responseBody
|
||||
record.status = if (response.statusCode.is2xxSuccessful) PayuQrStatus.SENT else PayuQrStatus.FAILED
|
||||
payuQrRequestRepo.save(record)
|
||||
|
||||
if (!response.statusCode.is2xxSuccessful) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_GATEWAY, "PayU request failed")
|
||||
}
|
||||
|
||||
return PayuQrGenerateResponse(
|
||||
txnid = txnid,
|
||||
amount = pending,
|
||||
currency = booking.property.currency,
|
||||
payuResponse = responseBody
|
||||
)
|
||||
}
|
||||
|
||||
private fun pickSalt(settings: com.android.trisolarisserver.models.payment.PayuSettings): String {
|
||||
val salt = if (settings.useSalt256) settings.salt256 else settings.salt32
|
||||
return salt?.trim()?.ifBlank { null }
|
||||
?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "PayU salt missing")
|
||||
}
|
||||
|
||||
private fun sha512(input: String): String {
|
||||
val bytes = MessageDigest.getInstance("SHA-512").digest(input.toByteArray())
|
||||
return bytes.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private fun computeExpectedPay(stays: List<com.android.trisolarisserver.models.room.RoomStay>, timezone: String?): Long {
|
||||
if (stays.isEmpty()) return 0
|
||||
val now = nowForProperty(timezone)
|
||||
var total = 0L
|
||||
stays.forEach { stay ->
|
||||
val rate = stay.nightlyRate ?: 0L
|
||||
if (rate == 0L) return@forEach
|
||||
val start = stay.fromAt.toLocalDate()
|
||||
val endAt = stay.toAt ?: now
|
||||
val end = endAt.toLocalDate()
|
||||
val nights = daysBetweenInclusive(start, end)
|
||||
total += rate * nights
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
private fun daysBetweenInclusive(start: java.time.LocalDate, end: java.time.LocalDate): Long {
|
||||
val diff = end.toEpochDay() - start.toEpochDay()
|
||||
return if (diff <= 0) 1L else diff
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user