Skip to content

Commit

Permalink
fixed Bug
Browse files Browse the repository at this point in the history
  • Loading branch information
balanka committed Oct 25, 2022
1 parent 633dc33 commit fd23ff4
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 82 deletions.
10 changes: 10 additions & 0 deletions src/main/resources/init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,16 @@ insert into account
, '9900', true, true, 0.0, 0.0, 0.0, 0.0, 'EUR'),
('9902','Bilanz Passiva','Bilanz Passiva',current_timestamp, current_timestamp, current_timestamp, '1000',11
, '9900', false, true, 0.0, 0.0, 0.0, 0.0, 'EUR'),
('9800','GuV Aktiva','GuV Aktiva',current_timestamp, current_timestamp, current_timestamp, '1000',11
, '9902', true, true, 0.0, 0.0, 0.0, 0.0, 'EUR'),
('9801','GuV Aktiva','GuV Aktiva',current_timestamp, current_timestamp, current_timestamp, '1000',11
, '9800', true, true, 0.0, 0.0, 0.0, 0.0, 'EUR'),
('9802','GuV Passiva','GuV Passiva',current_timestamp, current_timestamp, current_timestamp, '1000',11
, '9800', false, true, 0.0, 0.0, 0.0, 0.0, 'EUR'),
('4000','Umsatzerloese','Umsatzerloese',current_timestamp, current_timestamp, current_timestamp, '1000',11
, '9802', false, true, 0.0, 0.0, 0.0, 0.0, 'EUR'),
('4400','Umsatzerloese 19%','Umsatzerloese 19%',current_timestamp, current_timestamp, current_timestamp, '1000',11
, '4000', false, true, 0.0, 0.0, 0.0, 0.0, 'EUR'),
('1200','Forderungen aus Lieferungen und Leistungen','Forderung a. L & L',current_timestamp, current_timestamp, current_timestamp, '1000',11
, '9901', true, true, 0.0, 0.0, 0.0, 0.0, 'EUR'),
('1800','Bank','Bank',current_timestamp, current_timestamp, current_timestamp, '1000',11
Expand Down
67 changes: 39 additions & 28 deletions src/main/scala/com/kabasoft/iws/domain/models.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import zio._
import java.text.NumberFormat
import java.time.format.DateTimeFormatter
import scala.collection.immutable.{ ::, Nil }
import scala.annotation.tailrec

object common {

Expand Down Expand Up @@ -102,13 +103,37 @@ final case class Account(
def addAll(accSet: Set[Account]) =
copy(subAccounts = subAccounts ++ accSet)

def updateBalance(acc: Account): Account =
idebiting(acc.idebit).icrediting(acc.icredit).debiting(acc.debit).crediting(acc.credit)
def updateBalance(acc: Account): Account = {
if(acc.account.isEmpty) this
else {
val xx =idebiting(acc.idebit).icrediting(acc.icredit).debiting(acc.debit).crediting(acc.credit)
println("xxxx>>>>>"+xx)
xx
//idebiting(acc.idebit).icrediting(acc.icredit).debiting(acc.debit).crediting(acc.credit)
}

}

// def updateBalance(acc: Balance_Type): Account =
// def updateBalance(acc: Balance_Type): Account =
// idebiting(acc._1).icrediting(acc._2).debiting(acc._3).crediting(acc._4)

//import common._

@tailrec
def updateBalanceParent(all:List[Account]): List[Account] = {
all.find(acc=>acc.id == account) match {
case Some(parent)=>{
val y:Account = parent.updateBalance(this)
val z:List[Account]= all.filterNot(acc=>acc.id == parent.id):+y
y.updateBalanceParent(z)
}
case None=> all
}

}



def childBalances: BigDecimal =
if (subAccounts.nonEmpty) { reduce(subAccounts, Account.dummy).balance }
else {
Expand Down Expand Up @@ -233,39 +258,25 @@ object Account {
.copy(subAccounts = sub)
}

def unwrapDataTailRec(account: Account): List[Account] = {
// @tailrec
def unwrapData(res: List[Account]): List[Account] =
res.flatMap(acc =>
acc.subAccounts.toList match {
case Nil => if (acc.balance == 0.0 && acc.subAccounts.isEmpty) List.empty[Account] else List(acc)
case (head: Account) :: tail => List(acc, head) ++ unwrapData(tail)
}
)
unwrapData(account.subAccounts.toList)
}

def withChildren(accId: String, accList: List[Account]): Account =
accList.find(x => x.id == accId) match {
case Some(acc) => List(acc).foldMap(addSubAccounts(_, accList.groupBy(_.account))).copy(id = accId)
case None => Account.dummy
}
/*
def wrapAsData(account: Account): Daten =
account.subAccounts.toList match {
case Nil => Daten(BaseData(account))
case rest @ _ =>
Daten(BaseData(account)).copy(children = account.subAccounts.toList.map(wrapAsData))
}
def consolidateData(acc: Account): Daten =
List(acc).map(wrapAsData) match {
case Nil => Daten(BaseData(Account.dummy))
case account :: _ => account
}


*/
def consolidate(accId: String, accList: List[Account], pacs: List[PeriodicAccountBalance]): Account = {
val accMap = accList.groupBy(_.account)
accList.find(x => x.id == accId) match {
case Some(acc) =>
val x: Account = addSubAccounts(acc, accMap) // List(acc)
val y = getAllSubBalances(x, pacs)
val z = removeSubAccounts(y.copy(id = acc.id))
z
case None => Account.dummy
}
}
def flattenTailRec(ls: Set[Account]): Set[Account] = {
// @tailrec
def flattenR(res: List[Account], rem: List[Account]): List[Account] = rem match {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ trait AccountRepository {
def delete(items: List[String], company: String): ZIO[Any, RepositoryError, List[Int]] =
ZIO.collectAll(items.map(delete(_, company)))
def list(company: String): ZStream[Any, RepositoryError, Account]
def all(companyId: String): ZStream[Any, RepositoryError, Account]
def getBy(id: String, company: String): ZIO[Any, RepositoryError, Account]
def getByModelId(modelid: Int, company: String): ZIO[Any, RepositoryError, Account]
def modify(model: Account): ZIO[Any, RepositoryError, Int]
Expand All @@ -34,6 +35,9 @@ object AccountRepository {
def list(company: String): ZStream[AccountRepository, RepositoryError, Account] =
ZStream.service[AccountRepository] flatMap (_.list(company))

def all(companyId: String): ZStream[AccountRepository, RepositoryError, Account]=
ZStream.service[AccountRepository] flatMap (_.all(companyId))

def getBy(id: String, company: String): ZIO[AccountRepository, RepositoryError, Account] =
ZIO.service[AccountRepository] flatMap (_.getBy(id, company))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ final class AccountRepositoryImpl(pool: ConnectionPool) extends AccountRepositor
import ColumnSet._

lazy val driverLayer = ZLayer.make[SqlDriver](SqlDriver.live, ZLayer.succeed(pool))
val map:List[Account] = List.empty[Account]

val account =
(string("id") ++ string("name") ++ string("description") ++ instant("posting_date") ++ instant(
Expand Down Expand Up @@ -129,15 +130,58 @@ final class AccountRepositoryImpl(pool: ConnectionPool) extends AccountRepositor
.mapError(e => RepositoryError(e.getCause()))
}

override def list(companyId: String): ZStream[Any, RepositoryError, Account] = {
val selectAll = SELECT
//override def all(companyId: String): ZStream[Any, RepositoryError, Account] = for {
// trans <- list(companyId).mapZIO(tr => getByParentId(acc.id, companyId))
// } yield trans

override def all(companyId: String): ZStream[Any, RepositoryError, Account] = for {
account <- list(companyId).mapZIO(acc => getAccountWithLines(acc.id, companyId))
} yield {println("accountZZZ"+map) ; account}

private[this] def getAccountWithLines(id: String, companyId: String): ZIO[Any, RepositoryError, Account] = for {
account <- getBy(id, companyId)
lines_ <- getByParentIdX(id, companyId)//.runCollect.map(_.toList)
} yield account.copy(subAccounts = lines_.toSet)
/* getBy(id, companyId).map(account=>{
val s:List[Account]=Nil
val r = map.find(acc => acc.account == account.id)
.groupBy(_.id)
.map { case (k, v:List[Account]) => s:::v}
account.copy(subAccounts = s.toSet)
})*/





override def list(companyId: String): ZStream[Any, RepositoryError, Account] = //for {
// acc<-
ZStream.fromZIO(
ZIO.logInfo(s"Query to execute findAll is ${renderRead(SELECT)}")
) *> execute(SELECT.to(c => {val x = Account.apply(c); map :+ (x); println("MMMMMMMM"+x);println("TTTTTTT"+map); x}))
.provideDriver(driverLayer)
//.flatMap(acc=>acc.copy(subAccounts =getByParentIdX(acc.id, companyId)))

// getByParentIdX(acc.id, companyId)))//.runCollect.map(_.toSet))

//accounts<-getByParentIdX(acc.id, companyId)


// account <- getByParentId(acc.id, companyId)
// }yield acc.copy( subAccounts = accounts)

private def getByParentIdX(Id: String, companyId: String)= for{
accounts<-getByParentId_(Id, companyId).runCollect.map(_.toSet)
}yield accounts

private def getByParentId_(Id: String, companyId: String): ZStream[Any, RepositoryError,Account] = {
val selectAll = SELECT.where((accountid === Id) && (company === companyId))
ZStream.fromZIO(
ZIO.logInfo(s"Query to execute findAll is ${renderRead(selectAll)}")
) *>
execute(selectAll.to(c => Account.apply(c)))
ZIO.logInfo(s"Query to execute findBy is ${renderRead(selectAll)}")) *>
execute(selectAll.to(c => (Account.apply(c))))
.provideDriver(driverLayer)
}

override def getBy(Id: String, companyId: String): ZIO[Any, RepositoryError, Account] = {
val selectAll = SELECT.where((id === Id) && (company === companyId))

Expand Down
71 changes: 29 additions & 42 deletions src/main/scala/com/kabasoft/iws/service/AccountServiceImpl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,55 +6,42 @@ import com.kabasoft.iws.domain.common._
import com.kabasoft.iws.repository.{ AccountRepository, PacRepository }
import zio._
import zhttp.logging.Logger
import scala.annotation.tailrec


final class AccountServiceImpl(accRepo: AccountRepository, pacRepo: PacRepository) extends AccountService {
val logger = Logger.make.withLevel(zhttp.logging.LogLevel.Error)

def getBalance(accId: String, fromPeriod: Int, toPeriod: Int, companyId: String
): ZIO[Any, RepositoryError, Account] =
for {
accounts <- accRepo.list(companyId).runCollect.map(_.toList)
period = fromPeriod.toString.slice(0, 4).concat("00").toInt
def getBalance(
accId: String,
fromPeriod: Int,
toPeriod: Int,
companyId: String
): ZIO[Any, RepositoryError, Account] =
(for {
accounts <- accRepo.list(companyId).runCollect.map(_.toList)
period = fromPeriod.toString.slice(0, 4).concat("00").toInt
pacBalances <- pacRepo.getBalances4Period(fromPeriod, toPeriod, companyId).runCollect.map(_.toList)
pacs <- pacRepo.find4Period(period, period, companyId).runCollect.map(_.toList)
pacs <- pacRepo.find4Period(period, period, companyId).runCollect.map(_.toList)
} yield {
val all = (pacBalances ::: pacs)
.groupBy(_.account)
.map { case (k, v) => reduce(v, PeriodicAccountBalance.dummy) }
.filterNot(_.id == PeriodicAccountBalance.dummy.id)
.toList

val acc = accounts.filter(_.id == accId)
val list = all
.flatMap(pac =>
accounts
.find(acc => pac.account == acc.id)
.map(_.copy(idebit = pac.idebit, debit = pac.debit, icredit = pac.icredit, credit = pac.credit))
) //::: acc
println(" list::::::" + list)
val account = group(accId, list, accounts)
logger.info(" ACCOUNTS::::::" + account)
account
}


@tailrec
def group(accid: String, accounts0: List[Account], all: List[Account]): Account =
if (accounts0.size == 2 && accounts0.head.account.equals(accid) ) accounts0.head
else {
val accounts1 = accounts0
.groupBy(_.account)
.map { case (_, v) => reduce(v, Account.dummy).copy(subAccounts = v.toSet) }
val acc = accounts.filter(_.id == accId)
val list = pacBalances.map(pac =>
accounts
.find(acc => pac.account == acc.id)
.getOrElse(Account.dummy)
.copy(idebit = pac.idebit, debit = pac.debit, icredit = pac.icredit, credit = pac.credit)
) ::: acc
.filterNot(_.id == Account.dummy.id)
.flatMap(pac =>
all
.find(acc => acc.id == pac.account)
.map(_.copy(idebit = pac.idebit, debit = pac.debit, icredit = pac.icredit, credit = pac.credit))
).toList
println(" lisaccounts1::::::" + accounts1)
group(accid, accounts1, all)
}
//println(" ACCOUNTS Beforee::::::" + list)
val accountsWithBalances = pacBalances.map(pac =>
accounts.find(acc => pac.account == acc.id)
map (_.copy(idebit = pac.idebit, debit = pac.debit, icredit = pac.icredit, credit = pac.credit)
)).flatten
val accountsWithoutBalances = accounts.filterNot(acc =>accountsWithBalances.map(_.id).contains(acc.id))
val XX = accountsWithBalances:::accountsWithoutBalances
val account = Account.consolidate(accId, XX, pacs)
//println(" ACCOUNTS::::::" + account)
account
})

def closePeriod(fromPeriod: Int, toPeriod: Int, inStmtAccId: String, company: String): ZIO[Any, RepositoryError, Int] =
for {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ object AccountRepositoryLiveSpec extends ZIOSpecDefault {
test("count all accounts") {
for {
count <- AccountRepository.list(company).runCount
} yield assertTrue(count == 6)
} yield assertTrue(count == 11)
},
test("insert two new accounts") {
for {
oneRow <- AccountRepository.create(accounts)
list <- AccountRepository.list(company).runCollect.map(_.toList)
count <- AccountRepository.list(company).runCount
} yield assertTrue(oneRow == 2) && assertTrue(count ==8)&& assertTrue(list.size == 8)
} yield assertTrue(oneRow == 2) && assertTrue(count ==13)&& assertTrue(list.size == 13)
},
test("get an account by its id") {
for {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ object TransactionRepositoryLiveSpec extends ZIOSpecDefault {
val terms ="changed text"
for {
oneRow <- TransactionRepository.create(ftr1)
ftr <- TransactionRepository.getByTransId(ftr1.tid, company)
all <- TransactionRepository.all(company).runCollect.map(_.toList)
ftr <- TransactionRepository.getByTransId(all(0).tid, company)
count <- TransactionRepository.all(company).runCount
nrUpdated <- TransactionRepository.modify(ftr.copy(text=terms))
ftr2 <- TransactionRepository.getByTransId(ftr1.tid, company)
} yield assertTrue(oneRow == 3) && assertTrue(ftr.tid == ftr1.tid) && assertTrue(count == 1) &&
ftr2 <- TransactionRepository.getByTransId(ftr.tid, company)
} yield assertTrue(oneRow == 3) && assertTrue(count == 1) &&
assertTrue(nrUpdated == 3) &&assertTrue(ftr2.text == terms)
}
).provideLayerShared(testLayer.orDie) @@ sequential
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ object AccountServiceLiveSpec extends ZIOSpecDefault {
val toPeriod = currentYear.toString.concat("12").toInt
for {
account <-AccountService.getBalance(paccountId0, fromPeriod, toPeriod, company)
} yield assertTrue(account.id == paccountId0) &&assertTrue(account.balance == 1100)
} yield assertTrue(account.id == paccountId0) &&assertTrue(account.balance == 100)
},
test("Close an accounting period") {
val previousYear = common.getYear(LocalDateTime.now().minusYears(1).toInstant(ZoneOffset.UTC))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ object FinancialsServiceLiveSpec extends ZIOSpecDefault {
assertTrue(nrOfPacs == 1) && assertTrue(accountEntry == 3) &&
assertTrue(oaccountEntry == 1)&& assertTrue(vatEntry == 1) && assertTrue(balances4P.size == 2) &&
assertTrue(balances4P.headOption.getOrElse(PeriodicAccountBalance.dummy).debit == 119) &&
assertTrue(balance.debit == 1119) && assertTrue(balance.credit == 119))
assertTrue(balance.debit == 238) && assertTrue(balance.credit == 119))
}
}
).provideLayerShared(testServiceLayer.orDie) @@ sequential
Expand Down

0 comments on commit fd23ff4

Please sign in to comment.