Compare commits

..

No commits in common. "d9dcda072485a4d5ad8dc8c2899e50109906598a" and "e94928ae7feee5c29595175afe96866b5c91cced" have entirely different histories.

36 changed files with 553 additions and 1746 deletions

7
.gitignore vendored
View File

@ -44,10 +44,3 @@ application.yaml
initial-data.sql initial-data.sql
app.yaml app.yaml
*.env.json *.env.json
### API Logs ###
api.log
api.2024*
### Excel FIles ###
./excel

View File

@ -380,8 +380,3 @@ Authorization: {{auth-token}}
GET http://localhost:9001/api/vendor/quote/next GET http://localhost:9001/api/vendor/quote/next
Content-Type: application/json Content-Type: application/json
Authorization: {{auth-token}} Authorization: {{auth-token}}
### GET NEXT INCOMING SEW NUMBER
GET http://localhost:9001/api/vendor/incoming/next
Content-Type: application/json
Authorization: {{auth-token}}

View File

@ -1,61 +0,0 @@
#DO Not edit this file, copy to your HOME Directory and then rename it to app.yaml and then edit it
app:
db:
pass: password
url: jdbc:postgresql://10.10.10.211/arsalan_rmc_module_app
user: arsalan
name: arsalan_rmc_module_app
run_migration: 'true'
cors:
enabled: 'true'
hosts: www.readymixerp.com,app.readymixerp.com
port: '9001'
cache:
redis_uri: redis://10.10.10.112:6379/
iam:
url: https://auth.readymixerp.com
realm: rmc-dev
client_redirect_uri: http://localhost:9001/auth/code
client: rmc
scripts:
path: /Users/gowthaman.b/IdeaProjects/rmc_modules_api/src/main/resources/scripts
security:
private_key: |-
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQD4ba8OhlyB9MUx
MFmT8c9sOKqXOG6ZM6qLxr5SnY1au47rYsHXt8Hb+tTUxpkf+5bndaZYGVgQ1mtw
eEVj3qZq9A+FnxxwZ9uIIdbOUPvsZLzNYnK3bFFRsmWMf30gDs6ZdS63b2tnXXE0
aoItwVguElUKVXKUymS0VlBB0ZLCYTlD6Q4sDm7HGXJZj5kVNVbBCBe42yLx8Y1F
TyNL8nPSS+SAdLUaPJ/6j+741+exAIOc0rSBJOMF0XNOwBZ85EuOiPa0e1sUz0qj
VfmZyeRFxkSWJBnqum1jrVFp55bMb37DYtZa0aFIcPdDfY42frDlPLcI4zzRwCn3
ggHL/nL9AgMBAAECggEAJ85sxu8zl8/l4EsG3M8EdVWidrGgUyRgDElFCiLcWVta
prqVJIt5YNYRJU5J5Jc2fRGxHPEOrJVW84IUsvskVQM/ZiHyd3ZvdaGKdFZYpO5t
VvGSlR53l0IhGxal24L+isCn7X+ec5pu6b8JQJX4RbBConHCTDdz/yDMzQcXiiqj
ezzSovZ1Xy/2dn7sOTFtEZi47d3AhBnjh8Xqk3Dc9UChooxuIU6WEbqWFxEkbzJS
sXIv9xADVDqFqjHGv6Tk1W+y7y8M2EHosJfhO0LmWFL7nUdw0WSJV+UqQxHrUSJs
SnYHkKRTYl2ljpjkuECp/YqUqdlNq/5T5jBE6cyopwKBgQD6+XGZfssdAqfnaEK2
nHdUAdklUFAFQpSmwIUwTZEHDC/CD+ErVjfbEfZ2mFOvWAIMwLmiLFuDT7E5sHaT
K4A2DQ8KyU3iJkH4nhxdYepLc7MSYElkn6fHNrXcJ9vPACmrtoa9rVW/LpAjsRq6
fDxLo12/+EmFvpZ0oEAIQXk6ZwKBgQD9ZzBgPapI8m7cjcdojqq0dJ2M5Sw7Bx5n
VFOC3H4Cx0xWTdwwZ9CZQ4v/XiiHiUGzwhfkNJ2x3DdpUCkPDD8o3cFXPRW4GsjD
kv/D0kL/JJAesG9XB9yMTMBoe2yGMudDVc7SYgUI2YXhmHYkpcjSzM0DftLL2Z47
GY1h385Q+wKBgGTRxe/Kfp+lzHtqZ7ph+pG1uFyD+dFTINIn7pkr38G8BIdpx6OY
HBIWEjMsGBoNOa2T0j6yoQSMA/7Pw6J1TCjqcAt+OJpLkh7krTJaPjuXO+163qDc
fhLKCJ5rKKLsRtEjHtedhR+q/d5IrBsUA0jDVMrkW+ytVlV9dpuaaa+rAoGASON8
m8JBD/iEAPbbK+0VlxCQHO3ymgwDJ8+usc6AhIYVJCIDOv0xmFRAmbTYzZuihXVH
8AFedsGUQrunA8gPBs86hMByVeGGbBMFdKsvUDqRJfK0JAGD4+tT0PnnjnZn5Qty
kTtWnWQMSYbUPNhe+pukQOQi+DXheLhx3XxF2S8CgYEAopLjGIR/xeuV7QkGJfCO
d2wEJROBPd3pbDlR4fLDO8RCw3irFYQgQd9WgGJY5KgyfjKLHkK7DMQKn+/yfUp5
UKeesBDXATpyQQrpfoKIhhZKtYphOwvIzugtLsd5sza++sjC9RwkRmYr0rzlHdUl
vtr3fru0Bzven2MeiQnqmCM=
-----END PRIVATE KEY-----
public_key: |-
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+G2vDoZcgfTFMTBZk/HP
bDiqlzhumTOqi8a+Up2NWruO62LB17fB2/rU1MaZH/uW53WmWBlYENZrcHhFY96m
avQPhZ8ccGfbiCHWzlD77GS8zWJyt2xRUbJljH99IA7OmXUut29rZ11xNGqCLcFY
LhJVClVylMpktFZQQdGSwmE5Q+kOLA5uxxlyWY+ZFTVWwQgXuNsi8fGNRU8jS/Jz
0kvkgHS1Gjyf+o/u+NfnsQCDnNK0gSTjBdFzTsAWfORLjoj2tHtbFM9Ko1X5mcnk
RcZEliQZ6rptY61RaeeWzG9+w2LWWtGhSHD3Q32ONn6w5Ty3COM80cAp94IBy/5y
/QIDAQAB
-----END PUBLIC KEY-----

View File

@ -1,11 +1,8 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins { plugins {
kotlin("jvm") version "1.9.22" kotlin("jvm") version "1.9.22"
kotlin("kapt") version "1.9.22" kotlin("kapt") version "1.9.22"
id("idea") id("idea")
id("io.ebean") version "13.23.2" id("io.ebean") version "13.23.2"
id("com.github.johnrengelman.shadow") version "8.1.1"
application application
} }
@ -56,18 +53,6 @@ kotlin {
jvmToolchain(17) jvmToolchain(17)
} }
tasks {
named<ShadowJar>("shadowJar") {
archiveBaseName.set("rest-api")
mergeServiceFiles()
manifest {
attributes(mapOf("Main-Class" to "com.restapi.MainKt"))
}
isZip64 = true
}
}
application { application {
mainClass.set("com.restapi.MainKt") mainClass.set("com.restapi.MainKt")
} }

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -42,7 +42,7 @@ class AppAccessManager : AccessManager {
Role.DbOps -> listOf("ROLE_DB_OPS") Role.DbOps -> listOf("ROLE_DB_OPS")
Role.Entity -> loadEntityActionRole(entity, action) Role.Entity -> loadEntityActionRole(entity, action)
is Role.Standard -> role.action.toList().map { "ROLE_${entity}_${it}" } is Role.Standard -> role.action.toList().map { "ROLE_${entity}_${it}" }
is Role.Explicit -> role.roles.toList() + listOf("ROLE_ADMIN") is Role.Explicit -> role.roles
}.map(String::uppercase) }.map(String::uppercase)
} }

View File

@ -112,154 +112,54 @@ fun main(args: Array<String>) {
path("/vendor"){ path("/vendor"){
path("/"){ path("/"){
post("", VendorCtrl::create, Roles(Role.Explicit("ROLE_VENDOR_CREATE"))) post("", VendorCtrl::create, Roles(Role.Explicit(listOf("ROLE_VENDOR_CREATE", "ROLE_ADMIN"))))
post("/batch", VendorCtrl::createBatch, Roles(Role.Explicit("ROLE_VENDOR_CREATE"))) post("/batch", VendorCtrl::createBatch, Roles(Role.Explicit(listOf("ROLE_VENDOR_CREATE", "ROLE_ADMIN"))))
get("/{id}", VendorCtrl::get, Roles(Role.Explicit("ROLE_VENDOR_VIEW", "ROLE_VENDOR_CREATE"))) get("/{id}", VendorCtrl::get, Roles(Role.Explicit(listOf("ROLE_VENDOR_VIEW", "ROLE_VENDOR_CREATE", "ROLE_ADMIN"))))
post( post("/getAll", VendorCtrl::getAll, Roles(Role.Explicit(listOf("ROLE_VENDOR_VIEW", "ROLE_VENDOR_CREATE"))))
"/getAll", get("quotes/{id}", VendorCtrl::getQuotes, Roles(Role.Explicit(listOf("ROLE_ADMIN", "ROLE_QUOTE_VIEW", "ROLE_QUOTE_CREATE", "ROLE_VENDOR_VIEW"))))
VendorCtrl::getAll, get("pos/{id}", VendorCtrl::getPos, Roles(Role.Explicit(listOf("ROLE_ADMIN", "ROLE_PO_VIEW", "ROLE_PO_CREATE`"))))
Roles(Role.Explicit("ROLE_VENDOR_VIEW", "ROLE_VENDOR_CREATE")) put("/rate/{id}/{rating}", VendorCtrl::rate, Roles(Role.Explicit(listOf("ROLE_VENDOR_CREATE", "ROLE_ADMIN"))))
)
get(
"quotes/{id}",
VendorCtrl::getQuotes,
Roles(Role.Explicit("ROLE_QUOTE_VIEW", "ROLE_QUOTE_CREATE", "ROLE_VENDOR_VIEW"))
)
get("pos/{id}", VendorCtrl::getPos, Roles(Role.Explicit("ROLE_PO_VIEW", "ROLE_PO_CREATE`")))
put("/rate/{id}/{rating}", VendorCtrl::rate, Roles(Role.Explicit("ROLE_VENDOR_CREATE")))
put("/{id}", VendorCtrl::update, Roles(Role.Explicit("ROLE_VENDOR_CREATE")))
}
path("/incoming") {
post("", IncomingInventoryCtrl::create, Roles(Role.Explicit("ROLE_INVENTORY_CREATE")))
get("/next", IncomingInventoryCtrl::getNextNum, Roles(Role.Explicit("ROLE_INVENTORY_CREATE")))
get(
"/{id}",
IncomingInventoryCtrl::get,
Roles(Role.Explicit("ROLE_INVENTORY_VIEW", "ROLE_INVENTORY_CREATE"))
)
put("/{id}", IncomingInventoryCtrl::update, Roles(Role.Explicit("ROLE_INVENTORY_CREATE")))
post(
"/getAll",
IncomingInventoryCtrl::getAll,
Roles(Role.Explicit("ROLE_INVENTORY_CREATE", "ROLE_INVENTORY_VIEW"))
)
}
path("/outgoing") {
post("", OutgoingInventoryCtrl::create, Roles(Role.Explicit("ROLE_INVENTORY_CREATE")))
get("/next", OutgoingInventoryCtrl::getNextNum, Roles(Role.Explicit("ROLE_INVENTORY_CREATE")))
get(
"/{id}",
OutgoingInventoryCtrl::get,
Roles(Role.Explicit("ROLE_INVENTORY_VIEW", "ROLE_INVENTORY_CREATE"))
)
put("/{id}", OutgoingInventoryCtrl::update, Roles(Role.Explicit("ROLE_INVENTORY_CREATE")))
post(
"/getAll",
OutgoingInventoryCtrl::getAll,
Roles(Role.Explicit("ROLE_INVENTORY_CREATE", "ROLE_INVENTORY_VIEW"))
)
}
path("/invoice") {
post("", InvoiceCtrl::create, Roles(Role.Explicit("ROLE_INVOICE_CREATE")))
get("/next", InvoiceCtrl::getNextNum, Roles(Role.Explicit("ROLE_INVOICE_CREATE")))
get(
"/{id}",
InvoiceCtrl::get,
Roles(Role.Explicit("ROLE_INVOICE_VIEW", "ROLE_INVOICE_CREATE"))
)
put("/{id}", InvoiceCtrl::update, Roles(Role.Explicit("ROLE_INVOICE_CREATE")))
post(
"/getAll",
InvoiceCtrl::getAll,
Roles(Role.Explicit("ROLE_INVOICE_CREATE", "ROLE_INVOICE_VIEW"))
)
}
path("/payment") {
post("", PaymentCtrl::create, Roles(Role.Explicit("ROLE_PAYMENT_CREATE")))
get(
"/{id}",
PaymentCtrl::get,
Roles(Role.Explicit("ROLE_PAYMENT_VIEW", "ROLE_PAYMENT_CREATE"))
)
put("/{id}", PaymentCtrl::update, Roles(Role.Explicit("ROLE_PAYMENT_CREATE")))
post(
"/getAll",
PaymentCtrl::getAll,
Roles(Role.Explicit("ROLE_PAYMENT_CREATE", "ROLE_PAYMENT_VIEW"))
)
} }
path("/po"){ path("/po"){
get("/next", PurchaseOrderCtrl::getNextNum, Roles(Role.Explicit("ROLE_PO_CREATE"))) get("/next", PurchaseOrderCtrl::getNextNum, Roles(Role.Explicit(listOf("ROLE_PO_CREATE", "ROLE_ADMIN"))))
post("", PurchaseOrderCtrl::create, Roles(Role.Explicit("ROLE_PO_CREATE"))) post("", PurchaseOrderCtrl::create, Roles(Role.Explicit(listOf("ROLE_PO_CREATE", "ROLE_ADMIN"))))
post("/batch", PurchaseOrderCtrl::createBatch, Roles(Role.Explicit("ROLE_PO_CREATE"))) post("/batch", PurchaseOrderCtrl::createBatch, Roles(Role.Explicit(listOf("ROLE_PO_CREATE", "ROLE_ADMIN"))))
post( post("/getAll", PurchaseOrderCtrl::getAll, Roles(Role.Explicit(listOf("ROLE_PO_CREATE", "ROLE_PO_VIEW", "ROLE_VENDOR_CREATE", "ROLE_ADMIN"))))
"/getAll", get("/{id}", PurchaseOrderCtrl::get, Roles(Role.Explicit(listOf("ROLE_PO_CREATE", "ROLE_PO_VIEW", "ROLE_QUOTE_CREATE"))))
PurchaseOrderCtrl::getAll, put("/approve/{id}", PurchaseOrderCtrl::approve, Roles(Role.Explicit(listOf("ROLE_ADMIN"))))
Roles(Role.Explicit("ROLE_PO_CREATE", "ROLE_PO_VIEW", "ROLE_VENDOR_CREATE")) put("/reject/{id}", PurchaseOrderCtrl::reject, Roles(Role.Explicit(listOf("ROLE_ADMIN"))))
) get("/refQuote/{id}", PurchaseOrderCtrl::quoteReference, Roles(Role.Explicit(listOf("ROLE_PO_CREATE", "ROLE_ADMIN"))))
get(
"/{id}",
PurchaseOrderCtrl::get,
Roles(Role.Explicit("ROLE_PO_CREATE", "ROLE_PO_VIEW", "ROLE_QUOTE_CREATE"))
)
put("/{id}", PurchaseOrderCtrl::update, Roles(Role.Explicit("ROLE_PO_CREATE")))
put("/approve/{id}", PurchaseOrderCtrl::approve, Roles(Role.Explicit()))
put("/reject/{id}", PurchaseOrderCtrl::reject, Roles(Role.Explicit()))
get("/refQuote/{id}", PurchaseOrderCtrl::quoteReference, Roles(Role.Explicit("ROLE_PO_CREATE")))
} }
path("/quote"){ path("/quote"){
get("/next", QuotationCtrl::getNextNum, Roles(Role.Explicit("ROLE_QUOTE_CREATE"))) get("/next", QuotationCtrl::getNextNum, Roles(Role.Explicit(listOf("ROLE_QUOTE_CREATE", "ROLE_ADMIN"))))
post("", QuotationCtrl::create, Roles(Role.Explicit("ROLE_QUOTE_CREATE"))) post("", QuotationCtrl::create, Roles(Role.Explicit(listOf("ROLE_QUOTE_CREATE", "ROLE_ADMIN"))))
post("/batch", QuotationCtrl::createBatch, Roles(Role.Explicit("ROLE_QUOTE_CREATE"))) post("/batch", QuotationCtrl::createBatch, Roles(Role.Explicit(listOf("ROLE_QUOTE_CREATE", "ROLE_ADMIN"))))
post( post("/getAll", QuotationCtrl::getAll, Roles(Role.Explicit(listOf("ROLE_QUOTE_CREATE", "ROLE_ADMIN", "ROLE_QUOTE_VIEW"))))
"/getAll", get("/{id}", QuotationCtrl::get, Roles(Role.Explicit(listOf("ROLE_QUOTE_VIEW", "ROLE_ADMIN", "ROLE_QUOTE_CREATE"))))
QuotationCtrl::getAll, delete("/{id}", QuotationCtrl::delete, Roles(Role.Explicit(listOf("ROLE_QUOTE_CREATE", "ROLE_ADMIN"))))
Roles(Role.Explicit("ROLE_QUOTE_CREATE", "ROLE_QUOTE_VIEW"))
)
get("/{id}", QuotationCtrl::get, Roles(Role.Explicit("ROLE_QUOTE_VIEW", "ROLE_QUOTE_CREATE")))
put("/{id}", QuotationCtrl::update, Roles(Role.Explicit("ROLE_QUOTE_CREATE")))
delete("/{id}", QuotationCtrl::delete, Roles(Role.Explicit("ROLE_QUOTE_CREATE")))
} }
path("/product"){ path("/product"){
post("", ProductCtrl::create, Roles(Role.Explicit("ROLE_PRODUCT_CREATE"))) post("", ProductCtrl::create, Roles(Role.Explicit(listOf("ROLE_PRODUCT_CREATE", "ROLE_ADMIN"))))
put("/{id}", ProductCtrl::update, Roles(Role.Explicit("ROLE_PRODUCT_CREATE"))) //get("/{hsnCode}", ProductCtrl::get, Roles(Role.Explicit(listOf("ROLE_PRODUCT_VIEW", "ROLE_ADMIN"))))
delete("/{id}", ProductCtrl::delete, Roles(Role.Explicit("ROLE_PRODUCT_CREATE"))) put("/{id}", ProductCtrl::update, Roles(Role.Explicit(listOf("ROLE_PRODUCT_CREATE", "ROLE_ADMIN"))))
patch("/{id}", ProductCtrl::patch, Roles(Role.Explicit("ROLE_PRODUCT_CREATE"))) //patch("/{id}", ProductCtrl::patch, Roles(Role.Explicit(listOf("ROLE_PRODUCT_UPDATE", "ROLE_ADMIN"))))
post("/getAll", ProductCtrl::getAll, Roles(Role.Explicit("ROLE_PRODUCT_VIEW"))) delete("/{id}", ProductCtrl::delete, Roles(Role.Explicit(listOf("ROLE_PRODUCT_CREATE", "ROLE_ADMIN"))))
get("/{id}", ProductCtrl::get, Roles(Role.Explicit("ROLE_PRODUCT_VIEW"))) get("", ProductCtrl::getAll, Roles(Role.Explicit(listOf("ROLE_PRODUCT_VIEW", "ROLE_ADMIN"))))
get("/{id}", ProductCtrl::get, Roles(Role.Explicit(listOf("ROLE_PRODUCT_VIEW", "ROLE_ADMIN"))))
post("/getAll", ProductCtrl::getAll, Roles(Role.Explicit(listOf("ROLE_PRODUCT_VIEW", "ROLE_ADMIN"))))
} }
path("/doc"){ path("/doc"){
post("", DocumentCtrl::create, Roles(Role.Explicit("ROLE_DOC_CREATE"))) post("", Document::create, Roles(Role.Explicit(listOf("ROLE_DOC_CREATE", "ROLE_ADMIN"))))
//why type and refid are clubbed ?? //why type and refid are clubbed ??
get( get("/{type}/{refId}", Document::getWithRefId, Roles(Role.Explicit(listOf("ROLE_DOC_VIEW", "ROLE_ADMIN", "ROLE_PRODUCT_CREATE"))))
"/{type}/{refId}", get("/{id}", Document::get, Roles(Role.Explicit(listOf("ROLE_DOC_VIEW", "ROLE_ADMIN", "ROLE_PRODUCT_CREATE"))))
DocumentCtrl::getWithRefId, get("/print/{id}", Document::print, Roles(Role.Explicit(listOf("ROLE_DOC_CREATE", "ROLE_DOC_VIEW"))))
Roles(Role.Explicit("ROLE_DOC_VIEW", "ROLE_PRODUCT_CREATE")) delete("/{id}", Document::delete, Roles(Role.Explicit(listOf("ROLE_DOC_CREATE"))))
)
get("/{id}", DocumentCtrl::get, Roles(Role.Explicit("ROLE_DOC_VIEW", "ROLE_PRODUCT_CREATE")))
get(
"/print/{id}",
DocumentCtrl::print,
Roles(Role.Explicit("ROLE_DOC_CREATE", "ROLE_DOC_VIEW"))
)
delete("/{id}", DocumentCtrl::delete, Roles(Role.Explicit("ROLE_DOC_CREATE")))
} }
path("/reqForQuote"){ path("/reqForQuote"){
post( post("", RequestForQuote::create, Roles(Role.Explicit(listOf("ROLE_QUOTE_CREATE", "ROLE_PO_CREATE", "ROLE_RFQ_CREATE", "ROLE_ADMIN"))))
"", get("/{id}", RequestForQuote::get, Roles(Role.Explicit(listOf("ROLE_RFQ_CREATE", "ROLE_RFQ_VIEW", "ROLE_QUOTE_VIEW", "ROLE_PO_VIEW", "ROLE_ADMIN"))))
RequestForQuote::create, put("/{id}", RequestForQuote::update, Roles(Role.Explicit(listOf("ROLE_QUOTE_CREATE", "ROLE_PO_CREATE", "ROLE_RFQ_CREATE", "ROLE_ADMIN"))))
Roles(Role.Explicit("ROLE_QUOTE_CREATE", "ROLE_PO_CREATE", "ROLE_RFQ_CREATE"))
)
get(
"/{id}",
RequestForQuote::get,
Roles(Role.Explicit("ROLE_RFQ_CREATE", "ROLE_RFQ_VIEW", "ROLE_QUOTE_VIEW", "ROLE_PO_VIEW"))
)
put(
"/{id}",
RequestForQuote::update,
Roles(Role.Explicit("ROLE_QUOTE_CREATE", "ROLE_PO_CREATE", "ROLE_RFQ_CREATE"))
)
} }
} }
post("/script/database/{name}", Entities::executeStoredProcedure, Roles(adminRole, Role.DbOps)) post("/script/database/{name}", Entities::executeStoredProcedure, Roles(adminRole, Role.DbOps))

View File

@ -1,74 +0,0 @@
package com.restapi
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.restapi.controllers.QueryParam
import com.restapi.controllers.RawQuery
class FDeserializer : JsonDeserializer<F>() {
override fun deserialize(p: JsonParser, p1: DeserializationContext?): F {
//custom logic to do thia
val node = p.readValueAsTree<JsonNode>()
if (node.isObject) {
if (node.has("name")) {
return F.P(name = node.get("name").textValue())
} else if (node.has("num")) {
return F.Q(num = node.get("num").textValue())
} else if (node.has("tag")) {
return F.D(tag = node.get("tag").textValue())
}
} else {
//incorrect
}
throw IllegalArgumentException()
}
}
val om = jacksonObjectMapper()
@JsonDeserialize(using = FDeserializer::class)
sealed interface F {
data class P(val name: String) : F
data class Q(val num: String) : F
data class D(val tag: String) : F
}
val j = """
{"name":"a"}
""".trimIndent()
val j2 = """
{"num":"a"}
""".trimIndent()
val j3 = """
{"tag":"a"}
""".trimIndent()
val j4 = """
{
"sql":"aaaa",
"params": {
"a":"b",
"c": {
"type":"STRING",
"value":"aaaa"
}
}
}
""".trimIndent()
fun main() {
println(om.readValue<F>(j))
println(om.readValue<F>(j2))
println(om.readValue<F>(j3))
println(om.readValue<RawQuery>(j4))
}

View File

@ -235,7 +235,7 @@ enum class Action {
sealed class Role { sealed class Role {
open class Standard(vararg val action: Action) : Role() open class Standard(vararg val action: Action) : Role()
data object Entity : Role() data object Entity : Role()
open class Explicit(vararg val roles: String) : Role() data class Explicit(val roles: List<String>) : Role()
data object DbOps : Role() data object DbOps : Role()
} }

View File

@ -6,15 +6,18 @@ import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.restapi.domain.* import com.restapi.domain.*
import com.restapi.domain.Product
import com.restapi.domain.PurchaseOrder
import com.restapi.domain.Quotation
import com.restapi.domain.Session.currentUser import com.restapi.domain.Session.currentUser
import com.restapi.domain.Session.database import com.restapi.domain.Session.database
import com.restapi.domain.Session.findDataModelByEntityAndUniqId import com.restapi.domain.Session.findDataModelByEntityAndUniqId
import com.restapi.domain.Vendor
import com.restapi.integ.Scripting import com.restapi.integ.Scripting
import io.ebean.CallableSql import io.ebean.CallableSql
import io.ebean.RawSqlBuilder import io.ebean.RawSqlBuilder
import io.javalin.http.* import io.javalin.http.*
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import java.io.FileInputStream
import java.sql.Types import java.sql.Types
import java.time.LocalDate import java.time.LocalDate
import java.time.LocalDateTime import java.time.LocalDateTime
@ -57,7 +60,6 @@ sealed class QueryParam {
return when (this) { return when (this) {
is Complex -> getValueComplex() is Complex -> getValueComplex()
is Simple -> simple is Simple -> simple
else -> {}
} }
} }
} }
@ -371,7 +373,6 @@ object Entities {
false false
} }
} }
data class Filters(val common :CommonFilters, val custom :CustomFilters) data class Filters(val common :CommonFilters, val custom :CustomFilters)
data class SequenceNumber(val number:String) data class SequenceNumber(val number:String)
data class BatchPos(val pos :List<PurchaseOrder>) data class BatchPos(val pos :List<PurchaseOrder>)
@ -386,39 +387,22 @@ object PurchaseOrderCtrl {
val seq = SequenceNumber(prefix + cnt) val seq = SequenceNumber(prefix + cnt)
ctx.json(seq).status(HttpStatus.OK) ctx.json(seq).status(HttpStatus.OK)
} }
fun get(ctx :Context){ fun get(ctx :Context){
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val po = database.find(PurchaseOrder::class.java, id) ?: throw NotFoundResponse("po not found for $id") val po = database.find(PurchaseOrder::class.java, id) ?: throw NotFoundResponse("po not found for $id")
ctx.json(po).status(HttpStatus.OK) ctx.json(po).status(HttpStatus.OK)
} }
data class PF(val common: CommonFilters, val poFilters: POFilters) data class PF(val common: CommonFilters, val poFilters: POFilters)
fun getAll(ctx :Context){ fun getAll(ctx :Context){
val filters = ctx.bodyAsClass<PF>() val filters = ctx.bodyAsClass<PF>()
val pos = searchPos(filters.common, filters.poFilters) val pos = searchPos(filters.common, filters.poFilters)
val excel = ctx.queryParam("excel")
if (excel != null) {
exportPos(pos)
val inputStream = FileInputStream("./excel/Pos.xls")
ctx.result(inputStream).status(HttpStatus.OK)
} else {
ctx.json(pos).status(HttpStatus.OK) ctx.json(pos).status(HttpStatus.OK)
} }
}
fun create(ctx :Context){ fun create(ctx :Context){
val po = ctx.bodyAsClass<PurchaseOrder>() val po = ctx.bodyAsClass<PurchaseOrder>()
val prods = po.products
if (prods.isEmpty()) {
ctx.json(mapOf("error" to "empty product list")).status(HttpStatus.BAD_REQUEST)
return
}
database.save(po) database.save(po)
ctx.json(po).status(HttpStatus.CREATED) ctx.json(po).status(HttpStatus.CREATED)
} }
fun createBatch(ctx :Context){ fun createBatch(ctx :Context){
val pos = ctx.bodyAsClass<List<PurchaseOrder>>() val pos = ctx.bodyAsClass<List<PurchaseOrder>>()
val txn = database.beginTransaction() val txn = database.beginTransaction()
@ -435,7 +419,6 @@ object PurchaseOrderCtrl {
} }
ctx.result("pos batch created").status(HttpStatus.CREATED) ctx.result("pos batch created").status(HttpStatus.CREATED)
} }
fun approve(ctx :Context){ fun approve(ctx :Context){
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val po = database.find(PurchaseOrder::class.java, id) ?: throw NotFoundResponse("po not found for $id") val po = database.find(PurchaseOrder::class.java, id) ?: throw NotFoundResponse("po not found for $id")
@ -444,17 +427,13 @@ object PurchaseOrderCtrl {
ctx.json(po).status(HttpStatus.CREATED) ctx.json(po).status(HttpStatus.CREATED)
//reject all other pos pertaining to the same tx ?? //reject all other pos pertaining to the same tx ??
} }
fun reject(ctx :Context){ fun reject(ctx :Context){
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val po = database.find(PurchaseOrder::class.java, id) ?: throw NotFoundResponse("po not found for $id") val po = database.find(PurchaseOrder::class.java, id) ?: throw NotFoundResponse("po not found for $id")
po.apply { po.approvalStatus = ApprovalStatus.REJECTED
approvalStatus = ApprovalStatus.REJECTED po.save()
save()
}
ctx.json(po).status(HttpStatus.CREATED) ctx.json(po).status(HttpStatus.CREATED)
} }
fun quoteReference(ctx :Context){ fun quoteReference(ctx :Context){
//gets the quote reference on which this po is based on //gets the quote reference on which this po is based on
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
@ -464,22 +443,6 @@ object PurchaseOrderCtrl {
?: throw NotFoundResponse("reference quotation not found for po $id") ?: throw NotFoundResponse("reference quotation not found for po $id")
ctx.json(quote) ctx.json(quote)
} }
fun update(ctx: Context) {
val id = ctx.pathParam("id").toLong()
val po = database.find(PurchaseOrder::class.java, id) ?: throw NotFoundResponse("po not found for $id")
val updatedPo = ctx.bodyAsClass<PurchaseOrder>()
po.patchValues(updatedPo)
po.update()
ctx.json(po).status(HttpStatus.OK)
}
fun delete(ctx: Context) {
val id = ctx.pathParam("id")
val po = database.find(PurchaseOrder::class.java, id) ?: throw NotFoundResponse("no po found with id $id")
database.delete(po)
ctx.status(HttpStatus.OK)
}
} }
data class ProductSearch( data class ProductSearch(
@ -495,25 +458,17 @@ object ProductCtrl {
.eq("sys_pk", id.toLong()) .eq("sys_pk", id.toLong())
.findOne() .findOne()
?: throw NotFoundResponse("Product not found for $id") ?: throw NotFoundResponse("Product not found for $id")
println("Product found")
println(product)
ctx.json(product).status(HttpStatus.OK) ctx.json(product).status(HttpStatus.OK)
} }
data class PF(val common: CommonFilters, val productFilters: ProductFilters)
fun getAll(ctx: Context){ fun getAll(ctx: Context){
val filters = ctx.bodyAsClass<PF>() val productList = Session.database.find(Product::class.java)
val prods = searchProducts(filters.common, filters.productFilters) .findList()
val excel = ctx.queryParam("excel") .sortedBy { it.hsnCode }
if (excel != null) {
exportProds(prods)
val inputStream = FileInputStream("./excel/Products.xls")
ctx.result(inputStream).status(HttpStatus.OK)
} else { ctx.json(productList)
ctx.json(prods).status(HttpStatus.OK)
} }
}
fun create(ctx :Context){ fun create(ctx :Context){
val product = ctx.bodyAsClass<Product>() val product = ctx.bodyAsClass<Product>()
database.save(product) database.save(product)
@ -522,59 +477,17 @@ object ProductCtrl {
fun delete(ctx: Context) { fun delete(ctx: Context) {
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val prod = database.find(Product::class.java, id) ?: throw NotFoundResponse("no product found with id $id") val product = database.delete(Product::class.java, id)
database.delete(prod)
ctx.status(HttpStatus.OK)
} }
fun patch(ctx: Context) { fun patch(ctx: Context) {
val id = ctx.pathParam("id")
val patchValues = ctx.bodyAsClass<Map<String, Any>>()
database.beginTransaction().use {
patchValues.entries.forEach { en ->
val key = en.key
val value = en.value
database.sqlUpdate("update products set $key = ? where id = ?").apply {
setParameter(1, value)
setParameter(2, id)
execute()
}
}
it.commit()
}
} }
fun update(ctx: Context) { fun update(ctx: Context) {
val id = ctx.pathParam("id").toLong() val id = ctx.pathParam("id")
val product = database.find(Product::class.java, id) ?: throw NotFoundResponse("product not found for $id")
val updatedProduct = ctx.bodyAsClass<Product>()
product.patchValues(updatedProduct)
product.update()
ctx.json(product).status(HttpStatus.OK)
} }
@JvmStatic
fun main(args: Array<String>) {
val patchValues = mapOf("name" to 1)
val id = 1;
database.beginTransaction().use {
patchValues.entries.forEach { en ->
val key = en.key
val value = en.value
database.sqlUpdate("update product set $key = ? where sys_pk = ?").apply {
setParameter(1, value)
setParameter(2, id)
execute()
}
}
it.commit()
}
}
} }
object QuotationCtrl { object QuotationCtrl {
@ -587,41 +500,24 @@ object QuotationCtrl {
val seq = SequenceNumber(prefix + cnt) val seq = SequenceNumber(prefix + cnt)
ctx.json(seq).status(HttpStatus.OK) ctx.json(seq).status(HttpStatus.OK)
} }
fun get(ctx :Context){ fun get(ctx :Context){
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val quote = database.find(Quotation::class.java, id) ?: throw NotFoundResponse("quote not found for $id") val quote = database.find(Quotation::class.java, id) ?: throw NotFoundResponse("quote not found for $id")
ctx.status(HttpStatus.OK) ctx.status(HttpStatus.OK)
ctx.json(quote) ctx.json(quote)
} }
data class QF(val common: CommonFilters, val quoteFilters: QuoteFilters) data class QF(val common: CommonFilters, val quoteFilters: QuoteFilters)
fun getAll(ctx :Context){ fun getAll(ctx :Context){
val filters = ctx.bodyAsClass<QF>() val filters = ctx.bodyAsClass<QF>()
val excel: String? = ctx.queryParam("excel")
val quotes = searchQuotes(filters.common, filters.quoteFilters) val quotes = searchQuotes(filters.common, filters.quoteFilters)
if (excel != null) {
exportQuotations(quotes)
val inputStream = FileInputStream("./excel/Quotes.xls")
ctx.result(inputStream).status(HttpStatus.OK)
} else {
ctx.json(quotes).status(HttpStatus.OK) ctx.json(quotes).status(HttpStatus.OK)
} }
}
fun create(ctx :Context){ fun create(ctx :Context){
val quote = ctx.bodyAsClass<Quotation>() val quote = ctx.bodyAsClass<Quotation>()
//validation
val prods = quote.products
if (prods.isEmpty()) {
ctx.json(mapOf("error" to "empty product list")).status(HttpStatus.BAD_REQUEST)
return
}
database.save(quote) database.save(quote)
ctx.json(quote).status(HttpStatus.CREATED) ctx.json(quote).status(HttpStatus.CREATED)
} }
fun createBatch(ctx :Context){ fun createBatch(ctx :Context){
val quotes = ctx.bodyAsClass<List<Quotation>>() val quotes = ctx.bodyAsClass<List<Quotation>>()
val txn = database.beginTransaction() val txn = database.beginTransaction()
@ -638,149 +534,134 @@ object QuotationCtrl {
} }
ctx.result("Quotes batch created").status(HttpStatus.CREATED) ctx.result("Quotes batch created").status(HttpStatus.CREATED)
} }
fun delete(ctx :Context){ fun delete(ctx :Context){
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val quote = database.find(Quotation::class.java, id) ?: throw NotFoundResponse("no quote found with id $id") val quote = database.find(Quotation::class.java, id) ?: throw NotFoundResponse("quote not found for id $id")
database.delete(quote) quote.delete()
ctx.status(HttpStatus.OK) ctx.status(HttpStatus.OK)
ctx.result("quote with $id deleted")
} }
fun generatePO(ctx :Context){
fun update(ctx: Context) { //user should be redirected to a po form submission with prefilled values
val id = ctx.pathParam("id").toLong() //create a PO object with values from the quote and then send it as body to vendor/po/create ??
val quote = database.find(Quotation::class.java, id) ?: throw NotFoundResponse("quote not found for $id") }
val updatedQuote = ctx.bodyAsClass<Quotation>() fun reqForQuote(ctx :Context){
quote.patchValues(updatedQuote) val reqForQuoteNum = ctx.pathParam(("rfqNum"))
quote.update() val rfq = database.find(RequestForQuote::class.java)
ctx.json(quote).status(HttpStatus.OK) .where()
.eq("reqForQuoteNum", reqForQuoteNum)
?: throw NotFoundResponse("request for quote not found for this quotation")
ctx.status(HttpStatus.OK)
ctx.json(rfq)
} }
} }
object Document {
object DocumentCtrl {
fun get(ctx :Context){ fun get(ctx :Context){
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val doc = database.find(Document::class.java, id) ?: throw NotFoundResponse("no doc found with id $id") val doc = database.find(Document::class.java, id) ?: throw NotFoundResponse("no doc found with id $id")
ctx.status(HttpStatus.OK) ctx.status(HttpStatus.OK)
ctx.json(doc) ctx.json(doc)
} }
fun create(ctx :Context){ fun create(ctx :Context){
val doc = ctx.bodyAsClass<Document>() val doc = ctx.bodyAsClass<Document>()
database.save(doc) database.save(doc)
ctx.status(HttpStatus.CREATED) ctx.status(HttpStatus.CREATED)
ctx.json(doc) ctx.json(doc)
} }
fun print(ctx :Context){ fun print(ctx :Context){
//would be handled in the frontend ?? //would be handled in the frontend ??
} }
fun delete(ctx :Context){ fun delete(ctx :Context){
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val doc = database.find(Document::class.java, id) ?: throw NotFoundResponse("no document found with id $id") val doc = database.find(Document::class.java, id) ?: throw NotFoundResponse("no doc found with id $id")
database.delete(doc) //doc.delete()
ctx.status(HttpStatus.OK) ctx.status(HttpStatus.OK)
ctx.result("document deleted with id $id")
} }
fun getWithRefId(ctx :Context){ fun getWithRefId(ctx :Context){
//fetches a particular doc (po, quote) with ref id //fetches a particular doc (po, quote) with ref id
val refId = ctx.pathParam("refId") val refId = ctx.pathParam("refId")
val doc = database.find(Document::class.java) val doc = database.find(Document::class.java)
.where() .where()
.eq("typeOfDoc", DocType.valueOf(ctx.pathParam("type"))) .eq("refId", refId)
.eq("refIdOfDoc", refId)
?: throw NotFoundResponse("no doc found for refId $refId") ?: throw NotFoundResponse("no doc found for refId $refId")
ctx.status(HttpStatus.OK) ctx.status(HttpStatus.OK)
ctx.json(doc) ctx.json(doc)
} }
} }
object VendorCtrl { object VendorCtrl {
val logger = LoggerFactory.getLogger("Vendor")
fun get(ctx :Context){ fun get(ctx :Context){
val id = ctx.pathParam("id").toLong() val id = ctx.pathParam("id")
val vendor = database.find(Vendor::class.java, id) ?: throw NotFoundResponse("no vendor found with id $id") val vendor = database.find(Vendor::class.java, id) ?: throw NotFoundResponse("no vendor found with id $id")
ctx.status(HttpStatus.OK) ctx.status(HttpStatus.OK)
ctx.json(vendor) ctx.json(vendor)
} }
data class VF(val common : CommonFilters, val vendorFilters: VendorFilters) data class VF(val common : CommonFilters, val vendorFilters: VendorFilters)
fun getAll(ctx :Context){ fun getAll(ctx :Context){
val filters = ctx.bodyAsClass<VF>() val filters = ctx.bodyAsClass<VF>()
logger.info("filters = {}", filters) println(filters.common)
val excel: String? = ctx.queryParam("excel") println(filters.vendorFilters)
val vendors = searchVendors(filters.common, filters.vendorFilters) val pos = searchVendors(filters.common, filters.vendorFilters)
if (excel !== null) { ctx.status(HttpStatus.OK)
exportVendors(vendors) ctx.json(pos)
val inputStream = FileInputStream("./excel/VendorList.xls")
ctx.result(inputStream).status(HttpStatus.OK)
} else {
ctx.json(vendors).status(HttpStatus.OK)
} }
}
fun createBatch(ctx: Context){ fun createBatch(ctx: Context){
val vendors = ctx.bodyAsClass<List<Vendor>>() val vendors = ctx.bodyAsClass<List<Vendor>>()
database.saveAll(vendors) val txn = database.beginTransaction()
try {
txn.isBatchMode = true
for(v in vendors) database.save(v)
txn.commit()
ctx.status(HttpStatus.CREATED).result("Vendors Created")
} catch(e :Exception){
txn.rollback()
ctx.status(HttpStatus.INTERNAL_SERVER_ERROR).result("Vendor Creation failed" + e.message)
} finally {
txn.end()
}
} }
fun create(ctx :Context){ fun create(ctx :Context){
val vendor = ctx.bodyAsClass<Vendor>() val vendor = ctx.bodyAsClass<Vendor>()
database.save(vendor) database.save(vendor)
ctx.status(HttpStatus.CREATED) ctx.status(HttpStatus.CREATED)
ctx.json(vendor) ctx.json(vendor)
} }
fun update(ctx :Context){ fun update(ctx :Context){
val id = ctx.pathParam("id").toLong()
val vendor = database.find(Vendor::class.java, id) ?: throw NotFoundResponse("vendor not found for $id")
val updatedVendor = ctx.bodyAsClass<Vendor>()
vendor.patchValues(updatedVendor)
vendor.update()
ctx.json(vendor).status(HttpStatus.OK)
}
}
fun delete(ctx :Context){ fun delete(ctx :Context){
val id = ctx.pathParam("id")
val vendor = database.find(Vendor::class.java, id) ?: throw NotFoundResponse("no vendor found with id $id")
database.delete(vendor)
ctx.status(HttpStatus.OK)
}
}
fun getQuotes(ctx :Context){ fun getQuotes(ctx :Context){
val id = ctx.pathParam("id").toLong() val id = ctx.pathParam("id")
val quotes = database.find(Quotation::class.java) val quotes = database.find(Quotation::class.java)
.where() .where()
.eq("vendor", database.find(Vendor::class.java, id) ?: throw NotFoundResponse("vendor not found for $id")) .eq("vendor", id)
.findList() .findList()
ctx.json(quotes).status(HttpStatus.OK) ctx.status(HttpStatus.OK)
ctx.json(quotes)
} }
fun getPos(ctx :Context){ fun getPos(ctx :Context){
val id = ctx.pathParam("id").toLong() val id = ctx.pathParam("id")
val pos = database.find(PurchaseOrder::class.java) val pos = database.find(PurchaseOrder::class.java)
.where() .where()
.eq("vendor", database.find(Vendor::class.java, id) ?: throw NotFoundResponse("vendor not found for $id")) .eq("vendor", id)
.findList() .findList()
ctx.json(pos).status(HttpStatus.OK) ctx.status(HttpStatus.OK)
ctx.json(pos)
} }
fun rate(ctx :Context){ fun rate(ctx :Context){
val id = ctx.pathParam("id") val id = ctx.pathParam("id")
val rating1 = ctx.pathParam("rating").toDouble() val rating = ctx.pathParam("rating").toDouble()
val vendor = database.find(Vendor::class.java, id) ?: throw NotFoundResponse("vendor not found for id $id")
database.find(Vendor::class.java, id)?.let { //could place some rating validation checks
it.rating = rating1 vendor.rating = rating
it.save() vendor.save()
} ?: throw NotFoundResponse("vendor not found for id $id") ctx.status(HttpStatus.OK)
ctx.result("rating changed")
ctx.result("rating changed").status(HttpStatus.OK)
} }
} }
object RequestForQuote { object RequestForQuote {
fun create(ctx: Context) { fun create(ctx: Context) {
val rfq = ctx.bodyAsClass<ReqForQuote>() val rfq = ctx.bodyAsClass<ReqForQuote>()
@ -804,203 +685,3 @@ object RequestForQuote {
} }
} }
object IncomingInventoryCtrl {
fun create(ctx: Context) {
val ticket = ctx.bodyAsClass<IncomingInventory>()
database.save(ticket)
ctx.json(ticket).status(HttpStatus.CREATED)
}
fun update(ctx: Context) {
val id = ctx.pathParam("id").toLong()
val ticket =
database.find(IncomingInventory::class.java, id) ?: throw NotFoundResponse("quote not found for $id")
val updatedTicket = ctx.bodyAsClass<IncomingInventory>()
ticket.patchValues(updatedTicket)
ticket.update()
ctx.json(ticket).status(HttpStatus.OK)
}
fun get(ctx: Context) {
val id = ctx.pathParam("id").toLong()
val ticket = database.find(IncomingInventory::class.java, id)
?: throw NotFoundResponse("No incoming inventory ticket found with id $id")
ctx.json(ticket).status(HttpStatus.OK)
}
data class IIF(val common: CommonFilters, val incomingInventoryFilters: IncomingInventoryFilters)
fun getAll(ctx: Context) {
val filters = ctx.bodyAsClass<IIF>()
val tickets = searchIncomingInventory(filters.common, filters.incomingInventoryFilters)
val excel = ctx.queryParam("excel")
if (excel !== null) {
exportIncomingInventory(tickets)
val inputStream = FileInputStream("./excel/IncomingInventory.xls")
ctx.result(inputStream).status(HttpStatus.OK)
} else {
ctx.json(tickets).status(HttpStatus.OK)
}
}
fun getNextNum(ctx: Context) {
val prefix = "MRN/"
val cnt = database.find(IncomingInventory::class.java)
.findCount()
.toString()
.padStart(6, '0')
val seq = SequenceNumber(prefix + cnt)
ctx.json(seq).status(HttpStatus.OK)
}
}
object OutgoingInventoryCtrl {
fun create(ctx: Context) {
val ticket = ctx.bodyAsClass<OutgoingInventory>()
database.save(ticket)
ctx.json(ticket).status(HttpStatus.CREATED)
}
fun update(ctx: Context) {
val id = ctx.pathParam("id").toLong()
val ticket =
database.find(OutgoingInventory::class.java, id) ?: throw NotFoundResponse("quote not found for $id")
val updatedTicket = ctx.bodyAsClass<OutgoingInventory>()
ticket.patchValues(updatedTicket)
ticket.update()
ctx.json(ticket).status(HttpStatus.OK)
}
fun get(ctx: Context) {
val id = ctx.pathParam("id").toLong()
val ticket = database.find(OutgoingInventory::class.java, id)
?: throw NotFoundResponse("No incoming inventory ticket found with id $id")
ctx.json(ticket).status(HttpStatus.OK)
}
data class OIF(val common: CommonFilters, val outgoingInventoryFilters: OutgoingInventoryFilters)
fun getAll(ctx: Context) {
val filters = ctx.bodyAsClass<OIF>()
val tickets = searchOutgoingInventory(filters.common, filters.outgoingInventoryFilters)
val excel = ctx.queryParam("excel")
if (excel !== null) {
exportOutgoingInventory(tickets)
val inputStream = FileInputStream("./excel/OutgoingInventory.xls")
ctx.result(inputStream).status(HttpStatus.OK)
} else {
ctx.json(tickets).status(HttpStatus.OK)
}
}
fun getNextNum(ctx: Context) {
val prefix = "MDN/"
val cnt = database.find(OutgoingInventory::class.java)
.findCount()
.toString()
.padStart(6, '0')
val seq = SequenceNumber(prefix + cnt)
ctx.json(seq).status(HttpStatus.OK)
}
}
object PaymentCtrl {
fun create(ctx :Context){
val pmt = ctx.bodyAsClass(Payment::class.java)
database.save(pmt)
//update the status of invoices pertaining to payment.vendor
val invcs = searchInvoices(CommonFilters(sortBy = "date", sortAsc = true), InvoiceFilters(status = InvoiceStatus.PAID_NONE))
val tot: Double = pmt.amount
for(inv in invcs){
val deduct = Math.min(pmt.amount, inv.totalAmount)
inv.totalAmount -= deduct
pmt.amount -= deduct
database.update(inv)
if(pmt.amount <= 0.0) break
}
if (pmt.amount > 0.0){
//balance left for this vendor
val v = pmt.vendor?.sysPk?.let { database.find(Vendor::class.java, it) }
v?.apply {
outstanding = outstanding?.minus(tot)
database.update(v)
}
}
ctx.json(pmt).status(HttpStatus.CREATED)
}
fun get(ctx : Context){
val id = ctx.pathParam("id")
val pmt = database.find(Payment::class.java, id)
?: throw NotFoundResponse("No payment found for this id")
ctx.json(pmt).status(HttpStatus.OK)
}
data class PMTF(val common : CommonFilters, val paymentFilters: PaymentFilters)
fun getAll(ctx : Context){
val filters = ctx.bodyAsClass<PMTF>()
val payments = searchPayments(filters.common, filters.paymentFilters)
println(payments)
val excel = ctx.queryParam("excel")
if (excel !== null) {
// exportPayments(payments)
val inputStream = FileInputStream("./excel/Payments.xls")
ctx.result(inputStream).status(HttpStatus.OK)
} else {
ctx.json(payments).status(HttpStatus.OK)
}
}
fun update(ctx : Context){
val id = ctx.pathParam("id").toLong()
val pmt =
database.find(Payment::class.java, id) ?: throw NotFoundResponse("payment not found for $id")
val updatedPayment = ctx.bodyAsClass<Payment>()
pmt.patchValues(updatedPayment)
pmt.update()
ctx.json(pmt).status(HttpStatus.OK)
}
}
object InvoiceCtrl {
fun create(ctx : Context){
val invoice = ctx.bodyAsClass<Invoice>()
database.save(invoice)
ctx.json(invoice).status(HttpStatus.CREATED)
}
fun get(ctx : Context){
val id = ctx.pathParam("id").toLong()
val invoice = database.find(Invoice::class.java, id)
?: throw NotFoundResponse("No invoice found with id $id")
ctx.json(invoice).status(HttpStatus.OK)
}
data class INVF(val common: CommonFilters, val invoiceFilters: InvoiceFilters)
fun getAll(ctx : Context){
val filters = ctx.bodyAsClass<INVF>()
val invoices = searchInvoices(filters.common, filters.invoiceFilters)
val excel = ctx.queryParam("excel")
if (excel !== null) {
// exportPayments(payments)
val inputStream = FileInputStream("./excel/Invoices.xls")
ctx.result(inputStream).status(HttpStatus.OK)
} else {
ctx.json(invoices).status(HttpStatus.OK)
}
}
fun update(ctx : Context){
val id = ctx.pathParam("id").toLong()
val invoice =
database.find(Invoice::class.java, id) ?: throw NotFoundResponse("invoice not found for $id")
val updatedPayment = ctx.bodyAsClass<Invoice>()
invoice.patchValues(updatedPayment)
invoice.update()
ctx.json(invoice).status(HttpStatus.OK)
}
fun getNextNum(ctx : Context){
val prefix = "INV/"
val cnt = database.find(Invoice::class.java)
.findCount()
.toString()
.padStart(6, '0')
val seq = SequenceNumber(prefix + cnt)
ctx.json(seq).status(HttpStatus.OK)
}
}

View File

@ -1,5 +1,7 @@
package com.restapi.controllers package com.restapi.controllers
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.google.gson.Gson import com.google.gson.Gson
import com.restapi.domain.* import com.restapi.domain.*
import com.restapi.domain.Document import com.restapi.domain.Document
@ -12,15 +14,10 @@ import com.restapi.domain.Session.database
import com.restapi.domain.Vendor import com.restapi.domain.Vendor
import org.apache.poi.hssf.usermodel.DVConstraint import org.apache.poi.hssf.usermodel.DVConstraint
import org.apache.poi.hssf.usermodel.HSSFDataValidation import org.apache.poi.hssf.usermodel.HSSFDataValidation
import org.apache.poi.ss.usermodel.Cell import org.apache.poi.ss.usermodel.*
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.ss.usermodel.DateUtil
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.apache.poi.ss.util.CellRangeAddressList import org.apache.poi.ss.util.CellRangeAddressList
import java.io.File import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.FileInputStream import java.io.*
import java.io.FileOutputStream
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.time.LocalDate import java.time.LocalDate
import java.time.ZoneId import java.time.ZoneId
@ -41,7 +38,6 @@ fun createHeaderRow(cols: List<String>, sh: HSSFSheet, wb: Workbook) {
} }
} }
} }
fun String.parseDate(format: String): Date? { fun String.parseDate(format: String): Date? {
val locale = Locale.getDefault() val locale = Locale.getDefault()
return try { return try {
@ -50,7 +46,6 @@ fun String.parseDate(format: String): Date? {
null null
} }
} }
fun dateFromCellHelper(cell: Cell): LocalDate?{ fun dateFromCellHelper(cell: Cell): LocalDate?{
val date = when(cell.cellType){ val date = when(cell.cellType){
CellType.STRING -> cell.stringCellValue.parseDate("yyyy-MM-dd") CellType.STRING -> cell.stringCellValue.parseDate("yyyy-MM-dd")
@ -61,12 +56,10 @@ fun dateFromCellHelper(cell: Cell): LocalDate? {
null null
} }
} }
else -> null else -> null
} }
return date?.toInstant()?.atZone(ZoneId.systemDefault())?.toLocalDate() return date?.toInstant()?.atZone(ZoneId.systemDefault())?.toLocalDate()
} }
fun stringFromCellHelper(cell: Cell): String { fun stringFromCellHelper(cell: Cell): String {
val string = when(cell.cellType){ val string = when(cell.cellType){
CellType.NUMERIC -> cell.numericCellValue.toString() CellType.NUMERIC -> cell.numericCellValue.toString()
@ -75,7 +68,6 @@ fun stringFromCellHelper(cell: Cell): String {
} }
return string return string
} }
fun doubleFromCellHelper(cell: Cell): Double { fun doubleFromCellHelper(cell: Cell): Double {
val double = when(cell.cellType){ val double = when(cell.cellType){
CellType.NUMERIC -> cell.numericCellValue CellType.NUMERIC -> cell.numericCellValue
@ -93,130 +85,71 @@ fun longIntFromCellHelper(cell: Cell): Long {
} }
return long return long
} }
enum class FileType { enum class FileType {
QUOTES, POS, VENDORS, PRODS, DOCS QUOTES, POS, VENDORS, PRODS, DOCS
} }
enum class EnumFor { enum class EnumFor {
UOM, DocType UOM, DocType
} }
fun saveExcelFileLocally(fileName :String, wb: Workbook){ fun saveExcelFileLocally(fileName :String, wb: Workbook){
val path = "./excel/" val out = FileOutputStream(fileName)
val out = FileOutputStream(path + fileName)
wb.use { wb.use {
it.write(out) it.write(out)
} }
out.close() out.close()
} }
fun TemplateExcelFile(fileType: FileType){ fun TemplateExcelFile(fileType: FileType){
when(fileType){ when(fileType){
FileType.QUOTES -> { FileType.QUOTES -> {
val headers: List<String> = listOf( val headers : List<String> = listOf("Quotation Number", "Date", "Open Till", "Product Id", "Product Name", "Product Unit Price", "Quantity", "Vendor Name", "Vendor Address", "RFQ Number", "Total Amount", "Terms and Conditions")
"Quotation Number",
"Date",
"Open Till",
"Product Id",
"Product Name",
"Product Unit Price",
"Quantity",
"Vendor Name",
"Vendor Address",
"RFQ Number",
"Total Amount",
"Terms and Conditions"
)
val wb = HSSFWorkbook() val wb = HSSFWorkbook()
val sh = wb.createSheet() val sh = wb.createSheet()
createHeaderRow(headers, sh, wb) createHeaderRow(headers, sh, wb)
saveExcelFileLocally("Quotes_Template.xls", wb) saveExcelFileLocally("Quotes_Template.xls", wb)
} }
FileType.POS -> { FileType.POS -> {
val headers: List<String> = listOf( val headers : List<String> = listOf("Number", "Date", "Open Till", "Reference Quotation Number", "Vendor Name", "Vendor Address", "Product Id", "Product Name", "Unit Price", "Quantity", "Total Amount", "Terms and Conditions")
"Number",
"Date",
"Open Till",
"Reference Quotation Number",
"Vendor Name",
"Vendor Address",
"Product Id",
"Product Name",
"Unit Price",
"Quantity",
"Total Amount",
"Terms and Conditions"
)
val wb = HSSFWorkbook() val wb = HSSFWorkbook()
val sh = wb.createSheet() val sh = wb.createSheet()
createHeaderRow(headers, sh, wb) createHeaderRow(headers, sh, wb)
saveExcelFileLocally("Purchase_Order_Template.xls", wb) saveExcelFileLocally("Purchase_Order_Template.xls", wb)
} }
FileType.VENDORS -> { FileType.VENDORS -> {
val headers: List<String> = listOf( val headers : List<String> = listOf("Name", "MSME", "GST Number", "Address", "Rating", "Contact Name", "Contact Email", "Contact Mobile")
"Name",
"MSME",
"GST Number",
"Address",
"Rating",
"Contact Name",
"Contact Email",
"Contact Mobile"
)
val wb = HSSFWorkbook() val wb = HSSFWorkbook()
val sh = wb.createSheet() val sh = wb.createSheet()
createHeaderRow(headers, sh, wb) createHeaderRow(headers, sh, wb)
saveExcelFileLocally("Vendors_Template.xls", wb) saveExcelFileLocally("Vendors_Template.xls", wb)
} }
FileType.PRODS -> { FileType.PRODS -> {
val headers : List<String> = listOf("Id", "Name", "Description", "HSN Code", "UOM") val headers : List<String> = listOf("Id", "Name", "Description", "HSN Code", "UOM")
val wb = HSSFWorkbook() val wb = HSSFWorkbook()
val sh = wb.createSheet() val sh = wb.createSheet()
createHeaderRow(headers, sh, wb) createHeaderRow(headers, sh, wb)
val r0 = CellRangeAddressList(0, 1000, 4, 4) val r0 = CellRangeAddressList(0, 1000, 4, 4)
val dv0 = HSSFDataValidation( val dv0 = HSSFDataValidation(r0, DVConstraint.createExplicitListConstraint(arrayOf("LTR", "MTR", "NOS", "ALL"))).apply {
r0,
DVConstraint.createExplicitListConstraint(arrayOf("LTR", "MTR", "NOS", "ALL"))
).apply {
suppressDropDownArrow = true suppressDropDownArrow = true
} }
sh.addValidationData(dv0) sh.addValidationData(dv0)
saveExcelFileLocally("Products_Template.xls", wb) saveExcelFileLocally("Products_Template.xls", wb)
} }
FileType.DOCS -> { FileType.DOCS -> {
} }
} }
} }
fun ExportQuotations(quotes :List<Quotation>) {
fun exportQuotations(quotes: List<Quotation>) {
val wb = HSSFWorkbook() val wb = HSSFWorkbook()
val sh = wb.createSheet() val sh = wb.createSheet()
val headers: List<String> = listOf( val headers : List<String> = listOf("Quotation Number", "Date", "Open Till", "Product Id", "Product Name", "Product Unit Price", "Quantity", "Vendor Name", "Vendor Address", "RFQ Number", "Total AMount", "Terms and Conditions")
"Quotation Number",
"Date",
"Open Till",
"Product Id",
"Product Name",
"Product Unit Price",
"Quantity",
"Vendor Name",
"Vendor Address",
"RFQ Number",
"Total AMount",
"Terms and Conditions"
)
createHeaderRow(headers, sh, wb) createHeaderRow(headers, sh, wb)
val totalCols = headers.size
var rowCnt = 1 var rowCnt = 1
for(quote in quotes){ for(quote in quotes){
val prodCnt = quote.products.size val prodCnt = quote.products.size
for (j in 0..<prodCnt) { for (j in 0..prodCnt - 1){
val row = sh.createRow(rowCnt++) val row = sh.createRow(rowCnt++)
var i = 0; var i = 0;
row.createCell(i++).setCellValue(quote.quoteNum) row.createCell(i++).setCellValue(quote.quoteNum)
@ -237,15 +170,13 @@ fun exportQuotations(quotes: List<Quotation>) {
row.createCell(i++).setCellValue(quote.tnc?.joinToString(";")) row.createCell(i++).setCellValue(quote.tnc?.joinToString(";"))
} }
} }
saveExcelFileLocally("Quotes.xls", wb)
} }
fun exportVendors(vendors: List<Vendor>) { fun ExportVendors(vendors :List<Vendor>){
val wb = HSSFWorkbook() val wb = HSSFWorkbook()
val sh = wb.createSheet() val sh = wb.createSheet()
val headers: List<String> = val headers : List<String> = listOf("Name", "MSME", "GST Number", "Address", "Rating", "Contact Name", "Contact Email", "Contact Mobile")
listOf("No.", "Name", "MSME", "GST Number", "Address", "Rating", "Contact Name", "Contact Email", "Contact Mobile")
createHeaderRow(headers, sh, wb) createHeaderRow(headers, sh, wb)
val totalCols = headers.size val totalCols = headers.size
@ -253,11 +184,9 @@ fun exportVendors(vendors: List<Vendor>) {
for (vendor in vendors){ for (vendor in vendors){
val contactCnt = vendor.contacts.size val contactCnt = vendor.contacts.size
for (j in 0..<contactCnt) { for (j in 0..contactCnt - 1){
val row = sh.createRow(rowCnt++) val row = sh.createRow(rowCnt++)
var i = 0 var i = 0
row.createCell(i++).setCellValue((rowCnt - 1).toString())
row.createCell(i++).setCellValue(vendor.name)
row.createCell(i++).setCellValue(vendor.msme) row.createCell(i++).setCellValue(vendor.msme)
row.createCell(i++).setCellValue(vendor.gstNumber) row.createCell(i++).setCellValue(vendor.gstNumber)
row.createCell(i++).setCellValue(vendor.address) row.createCell(i++).setCellValue(vendor.address)
@ -267,16 +196,16 @@ fun exportVendors(vendors: List<Vendor>) {
row.createCell(i++).setCellValue(vendor.contacts[j].mobile) row.createCell(i++).setCellValue(vendor.contacts[j].mobile)
} }
} }
saveExcelFileLocally("VendorList.xls", wb)
} }
fun exportProds(prods: List<Product>) { fun ExportProds(prods :List<Product>){
val wb = HSSFWorkbook() val wb = HSSFWorkbook()
val sh = wb.createSheet() val sh = wb.createSheet()
val headers : List<String> = listOf("Id", "Name", "Description", "HSN Code", "UOM") val headers : List<String> = listOf("Id", "Name", "Description", "HSN Code", "UOM")
createHeaderRow(headers, sh, wb) createHeaderRow(headers, sh, wb)
val totalCols = headers.size
var rowCnt = 1 var rowCnt = 1
for (prod in prods){ for (prod in prods){
@ -288,34 +217,20 @@ fun exportProds(prods: List<Product>) {
row.createCell(i++).setCellValue(prod.hsnCode) row.createCell(i++).setCellValue(prod.hsnCode)
row.createCell(i++).setCellValue(prod.uom?.name) row.createCell(i++).setCellValue(prod.uom?.name)
} }
saveExcelFileLocally("Products.xls", wb)
} }
fun ExportPos(pos :List<PurchaseOrder>){
fun exportPos(pos: List<PurchaseOrder>) {
val wb = HSSFWorkbook() val wb = HSSFWorkbook()
val sh = wb.createSheet() val sh = wb.createSheet()
val headers: List<String> = listOf( val headers : List<String> = listOf("Number", "Date", "Open Till", "Reference Quotation Number", "Vendor Name", "Vendor Address", "Product Id", "Product Name", "Unit Price", "Quantity", "Total Amount", "Terms and Conditions")
"Number",
"Date",
"Open Till",
"Reference Quotation Number",
"Vendor Name",
"Vendor Address",
"Product Id",
"Product Name",
"Unit Price",
"Quantity",
"Total Amount",
"Terms and Conditions"
)
createHeaderRow(headers, sh, wb) createHeaderRow(headers, sh, wb)
val totalCols = headers.size
var rowCnt = 1 var rowCnt = 1
for(po in pos){ for(po in pos){
val prodCnt = po.products.size val prodCnt = po.products.size
for (j in 0..<prodCnt) { for (j in 0..prodCnt - 1){
val row = sh.createRow(rowCnt++) val row = sh.createRow(rowCnt++)
var i = 0 var i = 0
row.createCell(i++).setCellValue(po.poNum) row.createCell(i++).setCellValue(po.poNum)
@ -335,87 +250,6 @@ fun exportPos(pos: List<PurchaseOrder>) {
row.createCell(i++).setCellValue(po.tnc?.joinToString(";")) row.createCell(i++).setCellValue(po.tnc?.joinToString(";"))
} }
} }
saveExcelFileLocally("Pos.xls", wb)
}
fun exportIncomingInventory(tickets : List<IncomingInventory>) {
val wb = HSSFWorkbook()
val sh = wb.createSheet()
val headers: List<String> = listOf(
"MRN",
"Date",
"Vendor Name",
"Vendor Bill Number",
"Vendor Bill Amount",
"Product Id",
"Product Name",
"Unit Price",
"Quantity",
)
createHeaderRow(headers, sh, wb)
var rowCnt = 1
for (ticket in tickets) {
val prodCnt = ticket.products?.size
for (j in 0..<prodCnt!!) {
val row = sh.createRow(rowCnt++)
var i = 0
row.createCell(i++).setCellValue(ticket.mrn)
row.createCell(i++).setCellValue(ticket.date)
row.createCell(i++).setCellValue(ticket.vendor?.name)
row.createCell(i++).setCellValue(ticket.vendorBillNum)
row.createCell(i++).setCellValue(ticket.vendorBillAmount)
//6 would be repeated
row.createCell(i++).setCellValue(ticket.products!![j].productId)
row.createCell(i++).setCellValue(ticket.products!![j].productName)
row.createCell(i++).setCellValue(ticket.products!![j].unitPrice)
row.createCell(i++).setCellValue(ticket.products!![j].quantity)
}
}
saveExcelFileLocally("IncomingInventory.xls", wb)
}
fun exportOutgoingInventory(tickets : List<OutgoingInventory>) {
val wb = HSSFWorkbook()
val sh = wb.createSheet()
val headers: List<String> = listOf(
"MDN",
"Date",
"Out Mode",
"Purpose",
"Product Id",
"Product Name",
"Unit Price",
"Quantity",
)
createHeaderRow(headers, sh, wb)
var rowCnt = 1
for (ticket in tickets) {
val prodCnt = ticket.products?.size
for (j in 0..<prodCnt!!) {
val row = sh.createRow(rowCnt++)
var i = 0
row.createCell(i++).setCellValue(ticket.mdn)
row.createCell(i++).setCellValue(ticket.date)
row.createCell(i++).setCellValue(ticket.outMode.toString())
row.createCell(i++).setCellValue(ticket.purpose)
//6 would be repeated
row.createCell(i++).setCellValue(ticket.products!![j].productId)
row.createCell(i++).setCellValue(ticket.products!![j].productName)
row.createCell(i++).setCellValue(ticket.products!![j].unitPrice)
row.createCell(i++).setCellValue(ticket.products!![j].quantity)
}
}
saveExcelFileLocally("OutgoingInventory.xls", wb)
} }
fun main() { fun main() {
//ImportFromExcel(FileType.QUOTES, "C:\\Users\\arsalan\\Downloads\\Book.xlsx") //ImportFromExcel(FileType.QUOTES, "C:\\Users\\arsalan\\Downloads\\Book.xlsx")
@ -479,7 +313,6 @@ fun ImportFromExcel(fileType: FileType, filePath: String) {
// println("$v") // println("$v")
// } // }
} }
FileType.POS -> { FileType.POS -> {
//poNum, poDate, validTill, refQuoteNum, prodName, prodQuantity, totalAmount, products, vendorName, vendorGst, vendorAddress, tnc[]. docs[] //poNum, poDate, validTill, refQuoteNum, prodName, prodQuantity, totalAmount, products, vendorName, vendorGst, vendorAddress, tnc[]. docs[]
val PoMap : MutableMap<String, PurchaseOrder> = mutableMapOf() val PoMap : MutableMap<String, PurchaseOrder> = mutableMapOf()
@ -515,7 +348,6 @@ fun ImportFromExcel(fileType: FileType, filePath: String) {
} }
} }
} }
FileType.VENDORS -> { FileType.VENDORS -> {
sh.rowIterator().forEach { row -> sh.rowIterator().forEach { row ->
//name, msme, gstNum, addresss, rating, contacts //name, msme, gstNum, addresss, rating, contacts
@ -535,7 +367,6 @@ fun ImportFromExcel(fileType: FileType, filePath: String) {
vendor.rating = rating vendor.rating = rating
} }
} }
FileType.PRODS -> { FileType.PRODS -> {
sh.rowIterator().forEach { row -> sh.rowIterator().forEach { row ->
if(row == null) return@forEach if(row == null) return@forEach
@ -556,11 +387,10 @@ fun ImportFromExcel(fileType: FileType, filePath: String) {
"nos" -> UOM.NOS "nos" -> UOM.NOS
"ltr" -> UOM.LTR "ltr" -> UOM.LTR
"mtr" -> UOM.MTR "mtr" -> UOM.MTR
else -> UOM.ALL else -> UOM.LTR
} }
} }
} }
FileType.DOCS -> { FileType.DOCS -> {
sh.rowIterator().forEach { row -> sh.rowIterator().forEach { row ->
//Document Name, Document Type, RefID, url //Document Name, Document Type, RefID, url
@ -579,9 +409,173 @@ fun ImportFromExcel(fileType: FileType, filePath: String) {
"invoice" -> DocType.INVOICE "invoice" -> DocType.INVOICE
else -> DocType.ALL else -> DocType.ALL
} }
doc.refIdOfDoc = refId.toLong() doc.refId = refId
doc.url = url doc.url = url
} }
} }
} }
} }
data class validateExcel(
val name: String,
val description: String,
val hsnCode: String,
val ok: Boolean,
val err: String,
)
val app_common_om = jacksonObjectMapper().apply {
registerModule(JavaTimeModule())
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}
fun ExcelRead(): String{
val inputStream = FileInputStream("C:\\Users\\vinay\\IdeaProjects\\readymixerp_modules_api_git\\Untitled 1.xlsx")
val workbook = WorkbookFactory.create(inputStream)
val workSheet = workbook.getSheetAt(0)
var h = true
//Header check
if(workSheet.getRow(0).getCell(0).stringCellValue.equals("Name")) {
if (workSheet.getRow(0).getCell(1).stringCellValue.equals("Description")) {
if (workSheet.getRow(0).getCell(2).stringCellValue.equals("HSN")) {
if (workSheet.getRow(0).getCell(3).stringCellValue.equals("UOM")) {
h = false
}else return "Header UOM mismatch"
}else return "Header-HSN mismatch"
}else return "Header-Desc mismatch"
}else return "Header-Name mismatch"
val resp = arrayListOf<validateExcel>()
if(h==false) {
workSheet.rowIterator().forEach { row ->
if (row == null) return@forEach
if (h) {
val pName = row.getCell(0).run {
when {
this == null -> ""
this.cellType == CellType.STRING -> this.stringCellValue
else -> ""
}
}
val pDesc = row.getCell(1).run {
when {
this == null -> ""
this.cellType == CellType.STRING -> this.stringCellValue
else -> ""
}
}
val pHsn = row.getCell(2).run {
when {
this == null -> ""
this.cellType == CellType.STRING -> this.stringCellValue
else -> ""
}
}
if (pName.isEmpty() && pDesc.isEmpty() && pHsn.isEmpty()) {
return@forEach
}
if (pName.isEmpty()) {
resp.add(
validateExcel(
name = pName,
description = pDesc,
hsnCode = pHsn,
ok = false,
err = "Product name is required"
)
)
return@forEach
}
if (pDesc.isEmpty()) {
resp.add(
validateExcel(
name = pName,
description = pDesc,
hsnCode = pHsn,
ok = false,
err = "Product description is required"
)
)
return@forEach
}
if (pHsn.isEmpty()) {
resp.add(
validateExcel(
name = pName,
description = pDesc,
hsnCode = pHsn,
ok = false,
err = "Product HSN is required"
)
)
return@forEach
}
}
h = true
}
}
return app_common_om.writeValueAsString(resp)
}
fun CreateExcel(productList: List<Product>): InputStream {
val wb = XSSFWorkbook()
val sh = wb.createSheet()
val rows: Row = sh.createRow(0)
rows.createCell(0).setCellValue("Name")
rows.createCell(1).setCellValue("Description")
rows.createCell(2).setCellValue("HSN")
rows.createCell(3).setCellValue("UOM")
var rowNum = 1
for (product in productList) {
val row: Row = sh.createRow(rowNum++)
row.createCell(0).setCellValue(product.name)
row.createCell(1).setCellValue(product.description)
row.createCell(2).setCellValue(product.hsnCode)
val uomCell: Cell = row.createCell(3)
uomCell.setCellValue(product.uom?.name ?: "")
}
val baos = ByteArrayOutputStream()
wb.write(baos)
wb.close()
return ByteArrayInputStream(baos.toByteArray())
}
fun excelToDb(): List<Product> {
val inputStream = FileInputStream("C:\\Users\\vinay\\IdeaProjects\\readymixerp_modules_api_git\\Untitled 1.xlsx")
val workbook = WorkbookFactory.create(inputStream)
val workSheet = workbook.getSheetAt(0)
for (row in workSheet) {
val cell1Value = row.getCell(0).stringCellValue
val cell2Value = row.getCell(1).stringCellValue
val cell3Value = row.getCell(2).stringCellValue
val cell4Value = row?.getCell(3)?.stringCellValue
val prod = Product()
prod.name = cell1Value
prod.description = cell2Value
prod.hsnCode = cell3Value
prod.uom = when(cell4Value) {
"nos" -> UOM.NOS
"ltr" -> UOM.LTR
"mtr" -> UOM.MTR
else -> UOM.ALL
}
database.saveAll(prod)
}
val productList = Session.database.find(Product::class.java).findList()
return productList
}

View File

@ -1,29 +1,26 @@
package com.restapi.controllers package com.restapi.controllers
import com.restapi.domain.* import com.restapi.domain.*
import com.restapi.domain.Quotation
import com.restapi.domain.Session.database import com.restapi.domain.Session.database
import org.checkerframework.checker.index.qual.LessThan
import java.time.LocalDate import java.time.LocalDate
//constants //constants
const val IGNORE = "%" const val IGNORE = "%"
val baseDate: LocalDate = LocalDate.of(1500, 1, 1) val baseDate :LocalDate = LocalDate.of(1500, 1,1, )
val maxDate :LocalDate = LocalDate.of(3000, 1 ,1) val maxDate :LocalDate = LocalDate.of(3000, 1 ,1)
const val RATING_MAX = 10.0 const val RATING_MAX = 10.0
const val RATING_MIN = 0.0 const val RATING_MIN = 0.0
//common filters would be used by most of the handlers //common filters would be used by most of the handlers
//require a list of vendor ids to be passed //require a list of vendor ids to be passed
data class CommonFilters ( data class CommonFilters (
val from: LocalDate = baseDate, val fromDate :LocalDate = baseDate,
val to: LocalDate = maxDate, val toDate :LocalDate = maxDate,
val vendor :List<Long>? = null, val vendor :List<Long>? = null,
val sortAsc :Boolean = true, val sortAsc :Boolean = true,
val sortBy :String = IGNORE val sortBy :String = IGNORE
) )
interface CustomFilters{} interface CustomFilters{}
data class POFilters ( data class POFilters (
val poNumLike :String = IGNORE, val poNumLike :String = IGNORE,
val totalAmountExceeds :Long = Long.MIN_VALUE, val totalAmountExceeds :Long = Long.MIN_VALUE,
@ -33,25 +30,25 @@ data class POFilters(
val refQuotation :String = IGNORE, val refQuotation :String = IGNORE,
) : CustomFilters ) : CustomFilters
enum class UOMFilter {
ALL //fixme: later
}
data class ProductFilters ( data class ProductFilters (
val nameLike :String = IGNORE, val nameLike :String = IGNORE,
val hsnLike :String = IGNORE, val hsnLike :String = IGNORE,
val uom: UOM = UOM.ALL, val uom :UOMFilter = UOMFilter.ALL,
) : CustomFilters ) : CustomFilters
data class DocumentFilters ( data class DocumentFilters (
val nameLike :String = IGNORE, val nameLike :String = IGNORE,
val typeOfDoc :DocType = DocType.ALL, val typeOfDoc :DocType = DocType.ALL,
val docDateFrom :LocalDate = baseDate, val docDateFrom :LocalDate = baseDate,
val docDataTo :LocalDate = maxDate, val docDataTo :LocalDate = maxDate,
) :CustomFilters ) :CustomFilters
data class RFQFilters ( data class RFQFilters (
val validBefore :LocalDate = maxDate, val validBefore :LocalDate = maxDate,
val validAfter :LocalDate = baseDate, val validAfter :LocalDate = baseDate,
val reqForQuoteNumLike :String = IGNORE, val reqForQuoteNumLike :String = IGNORE,
) : CustomFilters )
data class QuoteFilters ( data class QuoteFilters (
val quoteNumLike :String = IGNORE, val quoteNumLike :String = IGNORE,
val validBefore :LocalDate = maxDate, val validBefore :LocalDate = maxDate,
@ -59,7 +56,6 @@ data class QuoteFilters(
val totalAmountExceeds :Long = Long.MIN_VALUE, val totalAmountExceeds :Long = Long.MIN_VALUE,
val totalAmountLessThan :Long = Long.MAX_VALUE, val totalAmountLessThan :Long = Long.MAX_VALUE,
) :CustomFilters ) :CustomFilters
data class VendorFilters ( data class VendorFilters (
val nameLike :String = IGNORE, val nameLike :String = IGNORE,
val msmeLike :String = IGNORE, val msmeLike :String = IGNORE,
@ -68,36 +64,6 @@ data class VendorFilters(
val ratingExceeds :Double = RATING_MIN, val ratingExceeds :Double = RATING_MIN,
val ratingLessThan :Double = RATING_MAX, val ratingLessThan :Double = RATING_MAX,
) :CustomFilters ) :CustomFilters
data class IncomingInventoryFilters(
val mrnLike: String = IGNORE,
val vehicleLike: String = IGNORE,
val vendorBillAmountExceeds: Double = Double.MIN_VALUE,
val vendorBillAmountLessThan: Double = Double.MAX_VALUE
) : CustomFilters
data class OutgoingInventoryFilters(
val mdnLike: String = IGNORE,
val purposeLike: String = IGNORE,
val personLike: String = IGNORE,
val vehicleLike: String = IGNORE,
val outMode: OutMode = OutMode.ALL
) : CustomFilters
data class InvoiceFilters(
val numLike: String = IGNORE,
val poNumLike: String = IGNORE,
val status: InvoiceStatus = InvoiceStatus.ALL,
val totalAmountExceeds: Double = Double.MIN_VALUE,
val totalAmountLessThan: Double = Double.MAX_VALUE
) : CustomFilters
data class PaymentFilters(
val refNumberLike: String = IGNORE,
val amountExceeds: Double = Double.MIN_VALUE,
val amountLessThan: Double = Double.MAX_VALUE
) : CustomFilters
fun<T> applyVendorHelper(q :io.ebean.ExpressionList<T>, vids :List<Long>?) { fun<T> applyVendorHelper(q :io.ebean.ExpressionList<T>, vids :List<Long>?) {
if (vids.isNullOrEmpty()) return if (vids.isNullOrEmpty()) return
// q.apply { // q.apply {
@ -107,39 +73,34 @@ fun <T> applyVendorHelper(q: io.ebean.ExpressionList<T>, vids: List<Long>?) {
// println(vids[0]) // println(vids[0])
q.eq("vendor_sys_pk", vids[0]) q.eq("vendor_sys_pk", vids[0])
} }
fun<T> applySortHelper(q :io.ebean.ExpressionList<T>, sortBy :String, asc :Boolean) { fun<T> applySortHelper(q :io.ebean.ExpressionList<T>, sortBy :String, asc :Boolean) {
if(sortBy == IGNORE) return; if(sortBy == IGNORE) return;
val order = if (asc) "ASC" else "DESC" val order = if (asc) "ASC" else "DESC"
q.orderBy("$sortBy $order") q.orderBy("$sortBy $order")
} }
fun<T> applyFromToHelper(q :io.ebean.ExpressionList<T>, fromDate: LocalDate, toDate: LocalDate, colName :String) { fun<T> applyFromToHelper(q :io.ebean.ExpressionList<T>, fromDate: LocalDate, toDate: LocalDate, colName :String) {
q.ge(colName, fromDate) q.ge(colName, fromDate)
.le(colName, toDate) .le(colName, toDate)
} }
fun<T> applyCommonFilters(q :io.ebean.ExpressionList<T>, commonFilters: CommonFilters) { fun<T> applyCommonFilters(q :io.ebean.ExpressionList<T>, commonFilters: CommonFilters) {
applyVendorHelper<T>(q, commonFilters.vendor) applyVendorHelper<T>(q, commonFilters.vendor)
applySortHelper<T>(q, commonFilters.sortBy, commonFilters.sortAsc) applySortHelper<T>(q, commonFilters.sortBy, commonFilters.sortAsc)
} }
fun searchQuotes(commonFilters: CommonFilters, quoteFilters: QuoteFilters) : List<Quotation> { fun searchQuotes(commonFilters: CommonFilters, quoteFilters: QuoteFilters) : List<Quotation> {
val q = database.find(Quotation::class.java) val q = database.find(Quotation::class.java)
.where() .where()
.ge("quoteDate", commonFilters.from) .ge("quoteDate", commonFilters.fromDate)
.le("quoteDate", commonFilters.to) .le("quoteDate", commonFilters.toDate)
.ge("validTill",quoteFilters.validAfter) .ge("validTill",quoteFilters.validAfter)
.le("validTill", quoteFilters.validBefore) .le("validTill", quoteFilters.validBefore)
.ge("totalAmount", quoteFilters.totalAmountExceeds) .ge("totalAmount", quoteFilters.totalAmountExceeds)
.le("totalAmount", quoteFilters.totalAmountLessThan) .le("totalAmount", quoteFilters.totalAmountLessThan)
.ilike("quoteNum", "%" + quoteFilters.quoteNumLike + "%") .ilike("quoteNum", "%" + quoteFilters.quoteNumLike + "%")
applyFromToHelper(q, commonFilters.from, commonFilters.to, "quoteDate") applyFromToHelper(q, commonFilters.fromDate, commonFilters.toDate, "quoteDate")
applyVendorHelper(q, commonFilters.vendor) applyVendorHelper(q, commonFilters.vendor)
applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc) applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc)
return q.findList() return q.findList()
} }
fun searchVendors(commonFilters: CommonFilters, vendorFilters: VendorFilters) : List<Vendor> { fun searchVendors(commonFilters: CommonFilters, vendorFilters: VendorFilters) : List<Vendor> {
val q = database.find(Vendor::class.java) val q = database.find(Vendor::class.java)
.where() .where()
@ -152,20 +113,6 @@ fun searchVendors(commonFilters: CommonFilters, vendorFilters: VendorFilters): L
applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc) applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc)
return q.findList() return q.findList()
} }
fun searchProducts(commonFilters: CommonFilters, productFilters: ProductFilters): List<Product> {
val q = database.find(Product::class.java)
.where()
.ilike("name", "%" + productFilters.nameLike + "%")
.ilike("hsnCode", "%" + productFilters.hsnLike + "%")
if (productFilters.uom != UOM.ALL) {
q.eq("uom", productFilters.uom)
}
applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc)
return q.findList()
}
fun searchDocs(commonFilters: CommonFilters, documentFilters: DocumentFilters) : List<Document> { fun searchDocs(commonFilters: CommonFilters, documentFilters: DocumentFilters) : List<Document> {
val q = database.find(Document::class.java) val q = database.find(Document::class.java)
.where() .where()
@ -179,7 +126,6 @@ fun searchDocs(commonFilters: CommonFilters, documentFilters: DocumentFilters):
applyVendorHelper(q, commonFilters.vendor) applyVendorHelper(q, commonFilters.vendor)
return q.findList() return q.findList()
} }
fun searchPos(commonFilters: CommonFilters, poFilters: POFilters?) : List<PurchaseOrder> { fun searchPos(commonFilters: CommonFilters, poFilters: POFilters?) : List<PurchaseOrder> {
val poFilters = poFilters ?: POFilters() val poFilters = poFilters ?: POFilters()
val q = database.find(PurchaseOrder::class.java) val q = database.find(PurchaseOrder::class.java)
@ -190,12 +136,11 @@ fun searchPos(commonFilters: CommonFilters, poFilters: POFilters?): List<Purchas
.le("validTill", poFilters.validBefore) .le("validTill", poFilters.validBefore)
.ilike("poNum", "%" + poFilters.poNumLike + "%") .ilike("poNum", "%" + poFilters.poNumLike + "%")
.ilike("referenceQuotation", "%" + poFilters.refQuotation + "%") .ilike("referenceQuotation", "%" + poFilters.refQuotation + "%")
applyFromToHelper(q, commonFilters.from, commonFilters.to, "poDate") applyFromToHelper(q, commonFilters.fromDate, commonFilters.toDate, "poDate")
applyVendorHelper(q, commonFilters.vendor) applyVendorHelper(q, commonFilters.vendor)
applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc) applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc)
return q.findList() return q.findList()
} }
fun searchRFQ(commonFilters: CommonFilters, rfqFilters: RFQFilters) : List<ReqForQuote> { fun searchRFQ(commonFilters: CommonFilters, rfqFilters: RFQFilters) : List<ReqForQuote> {
val q = database.find(ReqForQuote::class.java) val q = database.find(ReqForQuote::class.java)
.where() .where()
@ -207,64 +152,11 @@ fun searchRFQ(commonFilters: CommonFilters, rfqFilters: RFQFilters): List<ReqFor
return q.findList() return q.findList()
} }
fun searchIncomingInventory( fun searchProduct(commonFilters: CommonFilters, productFilters: ProductFilters): List<Product> {
commonFilters: CommonFilters, val p = database.find(Product::class.java)
incomingInventoryFilters: IncomingInventoryFilters
): List<IncomingInventory> {
val q = database.find(IncomingInventory::class.java)
.where() .where()
.ge("vendorBillAmount", incomingInventoryFilters.vendorBillAmountExceeds) .ilike("hsnCode", productFilters.hsnLike)
.le("vendorBillAmount", incomingInventoryFilters.vendorBillAmountLessThan) .ilike("Pname", productFilters.nameLike)
.ilike("mrn", "%" + incomingInventoryFilters.mrnLike + "%") applySortHelper(p, commonFilters.sortBy, commonFilters.sortAsc)
.ilike("vehicle", "%" + incomingInventoryFilters.vehicleLike + "%") return p.findList()
applyFromToHelper(q, commonFilters.from, commonFilters.to, "date")
applyVendorHelper(q, commonFilters.vendor)
applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc)
return q.findList()
} }
fun searchOutgoingInventory(
commonFilters: CommonFilters,
outgoingInventoryFilters: OutgoingInventoryFilters
): List<OutgoingInventory> {
val q = database.find(OutgoingInventory::class.java)
.where()
.ilike("mdn", "%" + outgoingInventoryFilters.mdnLike + "%")
.ilike("purpose", "%" + outgoingInventoryFilters.purposeLike + "%")
// .ilike("person", "%" + outgoingInventoryFilters.personLike + "%")
//.ilike("vehicle", "%" + outgoingInventoryFilters.vehicleLike + "%")
if (outgoingInventoryFilters.outMode != OutMode.ALL) {
q.eq("outMode", outgoingInventoryFilters.outMode)
}
applyFromToHelper(q, commonFilters.from, commonFilters.to, "date")
applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc)
return q.findList()
}
fun searchInvoices(commonFilters: CommonFilters, invoiceFilters: InvoiceFilters): List<Invoice> {
val q = database.find(Invoice::class.java)
.where()
.ilike("number", "%" + invoiceFilters.numLike + "%")
if (invoiceFilters.status != InvoiceStatus.ALL) {
q.eq("status", invoiceFilters.status)
}
applyFromToHelper(q, commonFilters.from, commonFilters.to, "date")
applyVendorHelper(q, commonFilters.vendor)
applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc)
return q.findList()
}
fun searchPayments(commonFilters: CommonFilters, paymentFilters: PaymentFilters): List<Payment> {
val q = database.find(Payment::class.java)
.where()
.ilike("refNumber", "%" + paymentFilters.refNumberLike + "%")
.ge("amount", paymentFilters.amountExceeds)
.le("amount", paymentFilters.amountLessThan)
applyFromToHelper(q, commonFilters.from, commonFilters.to, "date")
applyVendorHelper(q, commonFilters.vendor)
applySortHelper(q, commonFilters.sortBy, commonFilters.sortAsc)
return q.findList()
}
//if date is null then fromtoheper drops that///

View File

@ -8,7 +8,7 @@ object DBMigration {
private fun create(){ private fun create(){
val dbMigration: DbMigration = DbMigration.create() val dbMigration: DbMigration = DbMigration.create()
dbMigration.setPlatform(Platform.POSTGRES) dbMigration.setPlatform(Platform.POSTGRES)
//dbMigration.setGeneratePendingDrop("1.8")
dbMigration.generateMigration() dbMigration.generateMigration()
} }

View File

@ -9,16 +9,11 @@ import io.ebean.annotation.*
import io.ebean.annotation.Index import io.ebean.annotation.Index
import java.time.LocalDate import java.time.LocalDate
import java.time.LocalDateTime import java.time.LocalDateTime
import java.util.*
import javax.persistence.* import javax.persistence.*
data class Comments(val text: String = "", val by: String = "", val at: LocalDateTime = LocalDateTime.now()) data class Comments(val text: String = "", val by: String = "", val at: LocalDateTime = LocalDateTime.now())
data class POProducts( data class POProducts(val productId: String = "", val productName: String = "", val unitPrice :Double = 0.0, val quantity: Double = 0.0, val description :String = "")
val productId: String = "",
val productName: String = "",
val unitPrice: Double = 0.0,
val quantity: Double = 0.0,
val description: String = ""
)
enum class ApprovalStatus { enum class ApprovalStatus {
@ -224,6 +219,7 @@ open class DataModel : BaseTenantModel() {
} }
@Entity @Entity
@Index(unique = true, name = "unique_session_id", columnNames = ["session_id"]) @Index(unique = true, name = "unique_session_id", columnNames = ["session_id"])
open class AnonSession : BaseTenantModel() { open class AnonSession : BaseTenantModel() {
@ -249,48 +245,20 @@ class SafeStringDeserializer : JsonDeserializer<String>() {
} }
data class ContactPerson(val name: String = "", val email: String = "", val mobile: String = "") data class ContactPerson(val name: String = "", val email: String = "", val mobile: String = "")
@Entity @Entity
open class Vendor :BaseTenantModel() { open class Vendor :BaseTenantModel() {
fun patchValues(updatedVendor: Vendor) {
this.name = updatedVendor.name
this.msme = updatedVendor.msme
this.gstNumber = updatedVendor.gstNumber
this.address = updatedVendor.address
this.rating = updatedVendor.rating
this.contacts = updatedVendor.contacts
this.outstanding = updatedVendor.outstanding
this.asOnWhichDate = updatedVendor.asOnWhichDate
}
var name :String = "" var name :String = ""
var msme :String = "" var msme :String = ""
var gstNumber :String = "" var gstNumber :String = ""
var address :String = "" var address :String = ""
var rating :Double = 0.0 var rating :Double = 0.0
var outstanding: Double?=0.0
var asOnWhichDate: LocalDate?=null
@DbJsonB @DbJsonB
var contacts :List<ContactPerson> = mutableListOf() var contacts :List<ContactPerson> = mutableListOf()
} }
@Entity @Entity
open class PurchaseOrder :BaseTenantModel() { open class PurchaseOrder :BaseTenantModel() {
fun patchValues(updatedPo: PurchaseOrder) {
this.poDate = updatedPo.poDate
this.validTill = updatedPo.validTill
this.tnc = updatedPo.tnc
this.products = updatedPo.products
this.vendor = updatedPo.vendor
this.documents = updatedPo.documents
this.totalAmount = updatedPo.totalAmount
}
@DbJsonB @DbJsonB
var products :MutableList<POProducts> = mutableListOf() var products :MutableList<POProducts> = mutableListOf()
@ManyToOne @ManyToOne
var vendor :Vendor? = null var vendor :Vendor? = null
var referenceQuotation :String? = "" var referenceQuotation :String? = ""
@ -298,10 +266,8 @@ open class PurchaseOrder : BaseTenantModel() {
var poNum: String = "" var poNum: String = ""
var poDate: LocalDate? = null var poDate: LocalDate? = null
var validTill: LocalDate? = null var validTill: LocalDate? = null
@DbArray @DbArray
var tnc: List<String>? = arrayListOf() var tnc: List<String>? = arrayListOf()
@DbArray @DbArray
var documents: List<String>? = arrayListOf() var documents: List<String>? = arrayListOf()
} }
@ -310,50 +276,20 @@ enum class UOM {
NOS, LTR, MTR, ALL NOS, LTR, MTR, ALL
} }
enum class TypeOfProduct {
RAW_MATERIAL
}
@Entity @Entity
open class Product :BaseTenantModel() { open class Product :BaseTenantModel() {
fun patchValues(updatedProduct: Product) {
this.name = updatedProduct.name
this.description = updatedProduct.description
this.hsnCode = updatedProduct.hsnCode
this.uom = updatedProduct.uom
}
var id: Long? = null var id: Long? = null
var name :String = "" var name :String = ""
var description :String = "" var description :String = ""
var hsnCode :String = "" var hsnCode :String = ""
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
var uom: UOM? = null var uom: UOM? = null
@Enumerated(EnumType.STRING)
var type: TypeOfProduct? = null
} }
@Entity @Entity
open class Quotation :BaseTenantModel() { open class Quotation :BaseTenantModel() {
fun patchValues(updatedQuote: Quotation) {
this.quoteDate = updatedQuote.quoteDate
this.vendorQuoteNum = updatedQuote.vendorQuoteNum
this.validTill = updatedQuote.validTill
this.reqForQuoteNum = updatedQuote.reqForQuoteNum
this.tnc = updatedQuote.tnc
this.products = updatedQuote.products
this.vendor = updatedQuote.vendor
this.documents = updatedQuote.documents
this.totalAmount = updatedQuote.totalAmount
}
@DbJsonB @DbJsonB
var products :MutableList<POProducts> = mutableListOf() var products :MutableList<POProducts> = mutableListOf()
@ManyToOne @ManyToOne
var vendor :Vendor? = null var vendor :Vendor? = null
var totalAmount :Double = 0.0 var totalAmount :Double = 0.0
@ -363,147 +299,42 @@ open class Quotation : BaseTenantModel() {
var vendorQuoteNum: String? = "" var vendorQuoteNum: String? = ""
var quoteDate: LocalDate? = null var quoteDate: LocalDate? = null
var validTill: LocalDate? = null var validTill: LocalDate? = null
@DbArray @DbArray
var tnc: List<String>? = arrayListOf() var tnc: List<String>? = arrayListOf()
@DbArray @DbArray
var documents: List<String>? = arrayListOf() var documents: List<String>? = arrayListOf()
var taxesIncluded: Boolean ?= null
} }
enum class DocType{ enum class DocType{
PO, QUOTE, INVOICE, ALL PO, QUOTE, INVOICE, ALL
} }
@Entity @Entity
open class Document :BaseTenantModel() { open class Document :BaseTenantModel() {
var name :String = "" var name :String = ""
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
var typeOfDoc :DocType? = null var typeOfDoc :DocType? = null
//could be quoteNum, PoNum, InvoiceNum //could be quoteNum, PoNum, InvoiceNum
var refIdOfDoc: Long? = null var refId: String? = null
var description :String = "" var description :String = ""
var url :String = "" var url :String = ""
var docDate :LocalDate? = null var docDate :LocalDate? = null
var vendor :Vendor? = null
} }
enum class RFQStatus{ enum class RFQStatus{
DELIVERED, PO, QUOTE, CANCELLED DELIVERED, PO, QUOTE, CANCELLED
} }
@Entity @Entity
open class ReqForQuote :BaseTenantModel() { open class ReqForQuote :BaseTenantModel() {
@DbArray @DbArray
var potentialVendors :List<Long>? = null var potentialVendors :List<Long>? = null
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
var status :RFQStatus? = null var status :RFQStatus? = null
// @DbArray
// var docs :List<Document>? = null
@DbJsonB @DbJsonB
var products :List<POProducts>? = null var products :List<POProducts>? = null
var reqForQuoteNum: String? = null var reqForQuoteNum: String? = null
var openTill: LocalDate? = null var openTill: LocalDate? = null
} }
@Entity
open class IncomingInventory : BaseTenantModel() {
fun patchValues(updated: IncomingInventory) {
this.date = updated.date
this.vendorBillNum = updated.vendorBillNum
this.vendorBillAmount = updated.vendorBillAmount
this.vehicle = updated.vehicle
this.products = updated.products
this.vendor = updated.vendor
}
var mrn: String? = null
var date: LocalDate? = null
var vendorBillNum: String? = null
var vendorBillAmount: Double = 0.0
var vehicle: String = ""
@DbJsonB
var products: List<POProducts>? = null
@ManyToOne
var vendor: Vendor? = null
}
enum class OutMode {
PERSON, VEHICLE, ALL
}
@Entity
open class OutgoingInventory : BaseTenantModel() {
fun patchValues(updated: OutgoingInventory) {
this.date = updated.date
this.products = updated.products
this.purpose = updated.purpose
this.outMode = updated.outMode
this.person = updated.person
this.vehicle = updated.vehicle
}
var mdn: String? = null
var date: LocalDate? = null
@DbJsonB
var products: List<POProducts>? = null
var purpose: String? = null
@Enumerated(EnumType.STRING)
var outMode: OutMode? = null
var person: String? = null
var vehicle: String? = null
}
enum class InvoiceStatus{
PAID_FULL, PAID_SOME, PAID_NONE, ALL
}
@Entity
open class Invoice : BaseTenantModel() {
fun patchValues(updated : Invoice) {
this.date = updated.date
this.number = updated.number
this.totalAmount = updated.totalAmount
this.poNum = updated.poNum
this.products = updated.products
this.vendor = updated.vendor
this.status = updated.status
}
var number: String = ""
var date: LocalDate?=null
var totalAmount : Double=0.0
var poNum:String?=null
@DbJsonB
var products: List<POProducts> ?= null
@ManyToOne
var vendor: Vendor? = null
@Enumerated(EnumType.STRING)
var status:InvoiceStatus?=null
}
@Entity
open class Payment : BaseTenantModel() {
fun patchValues(updated : Payment){
this.refNumber = updated.refNumber
this.amount = updated.amount
this.date = updated.date
this.remark = updated.remark
this.vendor = updated.vendor
}
var refNumber:String=""
var amount:Double=0.0
var date:LocalDate?=null
var remark:String?= null
@ManyToOne
var vendor:Vendor?=null
}

View File

@ -1,2 +0,0 @@
-- apply alter tables
alter table incoming_inventory drop column vendor_bil_num;

View File

@ -1,3 +0,0 @@
-- apply alter tables
alter table incoming_inventory drop column mdn;
alter table outgoing_inventory drop column mrn;

View File

@ -1,64 +0,0 @@
-- apply changes
create table invoice (
sys_pk bigint generated by default as identity not null,
deleted_on timestamp,
current_approval_level integer default 0 not null,
required_approval_levels integer default 0 not null,
date date,
total_amount float not null,
vendor_sys_pk bigint,
deleted boolean default false not null,
version integer default 1 not null,
created_at timestamp default 'now()' not null,
modified_at timestamp default 'now()' not null,
deleted_by varchar(255),
approval_status varchar(8) default 'APPROVED' not null,
tags varchar[] default '{}' not null,
comments jsonb default '[]' not null,
tenant_id varchar(255) not null,
number varchar(255) not null,
po_num varchar(255),
products jsonb,
status varchar(9),
created_by varchar(255) not null,
modified_by varchar(255) not null,
constraint ck_invoice_approval_status check ( approval_status in ('PENDING','APPROVED','REJECTED')),
constraint ck_invoice_status check ( status in ('PAID_FULL','PAID_SOME','PAID_NONE','ALL')),
constraint pk_invoice primary key (sys_pk)
);
create table payment (
sys_pk bigint generated by default as identity not null,
deleted_on timestamp,
current_approval_level integer default 0 not null,
required_approval_levels integer default 0 not null,
amount float not null,
date date,
vendor_sys_pk bigint,
deleted boolean default false not null,
version integer default 1 not null,
created_at timestamp default 'now()' not null,
modified_at timestamp default 'now()' not null,
deleted_by varchar(255),
approval_status varchar(8) default 'APPROVED' not null,
tags varchar[] default '{}' not null,
comments jsonb default '[]' not null,
tenant_id varchar(255) not null,
ref_number varchar(255) not null,
remark varchar(255),
created_by varchar(255) not null,
modified_by varchar(255) not null,
constraint ck_payment_approval_status check ( approval_status in ('PENDING','APPROVED','REJECTED')),
constraint pk_payment primary key (sys_pk)
);
-- apply alter tables
alter table vendor add column if not exists outstanding float;
alter table vendor add column if not exists as_on_which_date date;
-- foreign keys and indices
create index ix_invoice_vendor_sys_pk on invoice (vendor_sys_pk);
alter table invoice add constraint fk_invoice_vendor_sys_pk foreign key (vendor_sys_pk) references vendor (sys_pk) on delete restrict on update restrict;
create index ix_payment_vendor_sys_pk on payment (vendor_sys_pk);
alter table payment add constraint fk_payment_vendor_sys_pk foreign key (vendor_sys_pk) references vendor (sys_pk) on delete restrict on update restrict;

View File

@ -1,2 +0,0 @@
-- apply alter tables
alter table document add column if not exists ref_id_of_doc bigint;

View File

@ -1,64 +0,0 @@
-- apply changes
create table incoming_inventory (
sys_pk bigint generated by default as identity not null,
deleted_on timestamp,
current_approval_level integer default 0 not null,
required_approval_levels integer default 0 not null,
date date,
vendor_bill_amount float not null,
vendor_sys_pk bigint,
deleted boolean default false not null,
version integer default 1 not null,
created_at timestamp default 'now()' not null,
modified_at timestamp default 'now()' not null,
deleted_by varchar(255),
approval_status varchar(8) default 'APPROVED' not null,
tags varchar[] default '{}' not null,
comments jsonb default '[]' not null,
tenant_id varchar(255) not null,
mdn varchar(255) not null,
vendor_bil_num varchar(255) not null,
vehicle varchar(255) not null,
products jsonb,
created_by varchar(255) not null,
modified_by varchar(255) not null,
constraint ck_incoming_inventory_approval_status check ( approval_status in ('PENDING','APPROVED','REJECTED')),
constraint pk_incoming_inventory primary key (sys_pk)
);
create table outgoing_inventory (
sys_pk bigint generated by default as identity not null,
deleted_on timestamp,
current_approval_level integer default 0 not null,
required_approval_levels integer default 0 not null,
date date,
deleted boolean default false not null,
version integer default 1 not null,
created_at timestamp default 'now()' not null,
modified_at timestamp default 'now()' not null,
deleted_by varchar(255),
approval_status varchar(8) default 'APPROVED' not null,
tags varchar[] default '{}' not null,
comments jsonb default '[]' not null,
tenant_id varchar(255) not null,
mrn varchar(255) not null,
purpose varchar(255),
out_mode varchar(7),
person varchar(255),
vehicle varchar(255),
created_by varchar(255) not null,
modified_by varchar(255) not null,
constraint ck_outgoing_inventory_approval_status check ( approval_status in ('PENDING','APPROVED','REJECTED')),
constraint ck_outgoing_inventory_out_mode check ( out_mode in ('PERSON','VEHICLE','ALL')),
constraint pk_outgoing_inventory primary key (sys_pk)
);
-- apply alter tables
alter table product add column if not exists type varchar(12);
alter table quotation add column if not exists taxes_included boolean;
-- apply post alter
alter table product add constraint ck_product_type check ( type in ('RAW_MATERIAL'));
-- foreign keys and indices
create index ix_incoming_inventory_vendor_sys_pk on incoming_inventory (vendor_sys_pk);
alter table incoming_inventory add constraint fk_incoming_inventory_vendor_sys_pk foreign key (vendor_sys_pk) references vendor (sys_pk) on delete restrict on update restrict;

View File

@ -1,2 +0,0 @@
-- apply alter tables
alter table incoming_inventory add column if not exists vendor_bill_num varchar(255);

View File

@ -1,4 +0,0 @@
-- apply alter tables
alter table incoming_inventory add column if not exists mrn varchar(255);
alter table outgoing_inventory add column if not exists mdn varchar(255);
alter table outgoing_inventory add column if not exists products jsonb;

View File

@ -1,2 +0,0 @@
-- apply alter tables
alter table document drop column ref_id;

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply" dropsFor="1.7">
<dropColumn columnName="vendor_bil_num" tableName="incoming_inventory"/>
</changeSet>
</migration>

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply" dropsFor="1.8">
<dropColumn columnName="mdn" tableName="incoming_inventory"/>
<dropColumn columnName="mrn" tableName="outgoing_inventory"/>
</changeSet>
</migration>

View File

@ -1,55 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply">
<createTable name="invoice" pkName="pk_invoice">
<column name="sys_pk" type="bigint" primaryKey="true"/>
<column name="deleted_on" type="localdatetime"/>
<column name="deleted_by" type="varchar"/>
<column name="current_approval_level" type="integer" defaultValue="0" notnull="true"/>
<column name="required_approval_levels" type="integer" defaultValue="0" notnull="true"/>
<column name="approval_status" type="varchar(8)" defaultValue="'APPROVED'" notnull="true" checkConstraint="check ( approval_status in ('PENDING','APPROVED','REJECTED'))" checkConstraintName="ck_invoice_approval_status"/>
<column name="tags" type="varchar[]" defaultValue="'{}'" notnull="true"/>
<column name="comments" type="jsonb" defaultValue="'[]'" notnull="true"/>
<column name="tenant_id" type="varchar" notnull="true"/>
<column name="number" type="varchar" notnull="true"/>
<column name="date" type="date"/>
<column name="total_amount" type="double" notnull="true"/>
<column name="po_num" type="varchar"/>
<column name="products" type="jsonb"/>
<column name="vendor_sys_pk" type="bigint" references="vendor.sys_pk" foreignKeyName="fk_invoice_vendor_sys_pk" foreignKeyIndex="ix_invoice_vendor_sys_pk"/>
<column name="status" type="varchar(9)" checkConstraint="check ( status in ('PAID_FULL','PAID_SOME','PAID_NONE','ALL'))" checkConstraintName="ck_invoice_status"/>
<column name="deleted" type="boolean" defaultValue="false" notnull="true"/>
<column name="version" type="integer" defaultValue="1" notnull="true"/>
<column name="created_at" type="localdatetime" defaultValue="'now()'" notnull="true"/>
<column name="modified_at" type="localdatetime" defaultValue="'now()'" notnull="true"/>
<column name="created_by" type="varchar" notnull="true"/>
<column name="modified_by" type="varchar" notnull="true"/>
</createTable>
<createTable name="payment" pkName="pk_payment">
<column name="sys_pk" type="bigint" primaryKey="true"/>
<column name="deleted_on" type="localdatetime"/>
<column name="deleted_by" type="varchar"/>
<column name="current_approval_level" type="integer" defaultValue="0" notnull="true"/>
<column name="required_approval_levels" type="integer" defaultValue="0" notnull="true"/>
<column name="approval_status" type="varchar(8)" defaultValue="'APPROVED'" notnull="true" checkConstraint="check ( approval_status in ('PENDING','APPROVED','REJECTED'))" checkConstraintName="ck_payment_approval_status"/>
<column name="tags" type="varchar[]" defaultValue="'{}'" notnull="true"/>
<column name="comments" type="jsonb" defaultValue="'[]'" notnull="true"/>
<column name="tenant_id" type="varchar" notnull="true"/>
<column name="ref_number" type="varchar" notnull="true"/>
<column name="amount" type="double" notnull="true"/>
<column name="date" type="date"/>
<column name="remark" type="varchar"/>
<column name="vendor_sys_pk" type="bigint" references="vendor.sys_pk" foreignKeyName="fk_payment_vendor_sys_pk" foreignKeyIndex="ix_payment_vendor_sys_pk"/>
<column name="deleted" type="boolean" defaultValue="false" notnull="true"/>
<column name="version" type="integer" defaultValue="1" notnull="true"/>
<column name="created_at" type="localdatetime" defaultValue="'now()'" notnull="true"/>
<column name="modified_at" type="localdatetime" defaultValue="'now()'" notnull="true"/>
<column name="created_by" type="varchar" notnull="true"/>
<column name="modified_by" type="varchar" notnull="true"/>
</createTable>
<addColumn tableName="vendor">
<column name="outstanding" type="double"/>
<column name="as_on_which_date" type="date"/>
</addColumn>
</changeSet>
</migration>

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply">
<addColumn tableName="document">
<column name="ref_id_of_doc" type="bigint"/>
</addColumn>
</changeSet>
<changeSet type="pendingDrops">
<dropColumn columnName="ref_id" tableName="document"/>
</changeSet>
</migration>

View File

@ -1,58 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply">
<createTable name="incoming_inventory" pkName="pk_incoming_inventory">
<column name="sys_pk" type="bigint" primaryKey="true"/>
<column name="deleted_on" type="localdatetime"/>
<column name="deleted_by" type="varchar"/>
<column name="current_approval_level" type="integer" defaultValue="0" notnull="true"/>
<column name="required_approval_levels" type="integer" defaultValue="0" notnull="true"/>
<column name="approval_status" type="varchar(8)" defaultValue="'APPROVED'" notnull="true" checkConstraint="check ( approval_status in ('PENDING','APPROVED','REJECTED'))" checkConstraintName="ck_incoming_inventory_approval_status"/>
<column name="tags" type="varchar[]" defaultValue="'{}'" notnull="true"/>
<column name="comments" type="jsonb" defaultValue="'[]'" notnull="true"/>
<column name="tenant_id" type="varchar" notnull="true"/>
<column name="mdn" type="varchar" notnull="true"/>
<column name="date" type="date"/>
<column name="vendor_bil_num" type="varchar" notnull="true"/>
<column name="vendor_bill_amount" type="double" notnull="true"/>
<column name="vehicle" type="varchar" notnull="true"/>
<column name="products" type="jsonb"/>
<column name="vendor_sys_pk" type="bigint" references="vendor.sys_pk" foreignKeyName="fk_incoming_inventory_vendor_sys_pk" foreignKeyIndex="ix_incoming_inventory_vendor_sys_pk"/>
<column name="deleted" type="boolean" defaultValue="false" notnull="true"/>
<column name="version" type="integer" defaultValue="1" notnull="true"/>
<column name="created_at" type="localdatetime" defaultValue="'now()'" notnull="true"/>
<column name="modified_at" type="localdatetime" defaultValue="'now()'" notnull="true"/>
<column name="created_by" type="varchar" notnull="true"/>
<column name="modified_by" type="varchar" notnull="true"/>
</createTable>
<createTable name="outgoing_inventory" pkName="pk_outgoing_inventory">
<column name="sys_pk" type="bigint" primaryKey="true"/>
<column name="deleted_on" type="localdatetime"/>
<column name="deleted_by" type="varchar"/>
<column name="current_approval_level" type="integer" defaultValue="0" notnull="true"/>
<column name="required_approval_levels" type="integer" defaultValue="0" notnull="true"/>
<column name="approval_status" type="varchar(8)" defaultValue="'APPROVED'" notnull="true" checkConstraint="check ( approval_status in ('PENDING','APPROVED','REJECTED'))" checkConstraintName="ck_outgoing_inventory_approval_status"/>
<column name="tags" type="varchar[]" defaultValue="'{}'" notnull="true"/>
<column name="comments" type="jsonb" defaultValue="'[]'" notnull="true"/>
<column name="tenant_id" type="varchar" notnull="true"/>
<column name="mrn" type="varchar" notnull="true"/>
<column name="date" type="date"/>
<column name="purpose" type="varchar"/>
<column name="out_mode" type="varchar(7)" checkConstraint="check ( out_mode in ('PERSON','VEHICLE','ALL'))" checkConstraintName="ck_outgoing_inventory_out_mode"/>
<column name="person" type="varchar"/>
<column name="vehicle" type="varchar"/>
<column name="deleted" type="boolean" defaultValue="false" notnull="true"/>
<column name="version" type="integer" defaultValue="1" notnull="true"/>
<column name="created_at" type="localdatetime" defaultValue="'now()'" notnull="true"/>
<column name="modified_at" type="localdatetime" defaultValue="'now()'" notnull="true"/>
<column name="created_by" type="varchar" notnull="true"/>
<column name="modified_by" type="varchar" notnull="true"/>
</createTable>
<addColumn tableName="product">
<column name="type" type="varchar(12)" checkConstraint="check ( type in ('RAW_MATERIAL'))" checkConstraintName="ck_product_type"/>
</addColumn>
<addColumn tableName="quotation">
<column name="taxes_included" type="boolean"/>
</addColumn>
</changeSet>
</migration>

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply">
<addColumn tableName="incoming_inventory">
<column name="vendor_bill_num" type="varchar"/>
</addColumn>
</changeSet>
<changeSet type="pendingDrops">
<dropColumn columnName="vendor_bil_num" tableName="incoming_inventory"/>
</changeSet>
</migration>

View File

@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply">
<addColumn tableName="incoming_inventory">
<column name="mrn" type="varchar"/>
</addColumn>
<addColumn tableName="outgoing_inventory">
<column name="mdn" type="varchar"/>
<column name="products" type="jsonb"/>
</addColumn>
</changeSet>
<changeSet type="pendingDrops">
<dropColumn columnName="mdn" tableName="incoming_inventory"/>
<dropColumn columnName="mrn" tableName="outgoing_inventory"/>
</changeSet>
</migration>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply" dropsFor="1.5">
<dropColumn columnName="ref_id" tableName="document"/>
</changeSet>
</migration>

View File

@ -1,19 +1,4 @@
<configuration> <configuration>
<appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>api.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>api.%d{yyyy-MM-dd}.%i.log.gz</FileNamePattern>
<MaxHistory>30</MaxHistory>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder> <encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
@ -29,6 +14,5 @@
<root level="info"> <root level="info">
<appender-ref ref="STDOUT" /> <appender-ref ref="STDOUT" />
<appender-ref ref="ROLLING" />
</root> </root>
</configuration> </configuration>