Esempio n. 1
0
 public function convertFromUSD(Money $money, Currency $currency, ExchangeRate $exchangeRate)
 {
     if ($exchangeRate->getCurrency() != $currency) {
         throw new InvalidCurrencyExchangeException();
     }
     $rate = $exchangeRate->getRate();
     $amount = $money->multiply($rate);
     return Money::create($amount->getAmount(), $currency);
 }
Esempio n. 2
0
 public function testConvertCurrency(UnitTester $I)
 {
     $exchangeRate = new \Zidisha\Currency\ExchangeRate();
     $exchangeRate->setRate(80)->setCurrencyCode(Currency::CODE_KES);
     // convert to USD
     $money = Money::create('160', Currency::CODE_KES);
     $moneyUSD = Money::create('2.0', Currency::CODE_USD);
     verify($this->currencyService->convertToUSD($money, $exchangeRate))->equals($moneyUSD);
     // convert from USD
     $money = Money::create('240', Currency::CODE_KES);
     $moneyUSD = Money::create('3.0', Currency::CODE_USD);
     verify($this->currencyService->convertFromUSD($moneyUSD, Currency::create(Currency::CODE_KES), $exchangeRate))->equals($money);
     $failed = false;
     try {
         $money = Money::create('160', Currency::CODE_XOF);
         $this->currencyService->convertToUSD($money, $exchangeRate);
     } catch (\Zidisha\Currency\Exception\InvalidCurrencyExchangeException $e) {
         $failed = true;
     }
     verify($failed)->true();
     $failed = false;
     try {
         $this->currencyService->convertFromUSD($moneyUSD, Currency::create(Currency::CODE_XOF), $exchangeRate);
     } catch (\Zidisha\Currency\Exception\InvalidCurrencyExchangeException $e) {
         $failed = true;
     }
     verify($failed)->true();
 }
Esempio n. 3
0
 public function getStart()
 {
     $payment = new Zidisha\Payment\Payment();
     $payment->setAmount(Money::create(10));
     $payment->setTransactionFee(Money::create(5));
     $payment->setDonationAmount(Money::create(5));
     $payment->setTotalAmount(Money::create(20));
     $payment->save();
     return $this->payPalService->makePayment($payment);
 }
Esempio n. 4
0
 public function validateDonationCreditAmount($attribute, $value, $parameters)
 {
     $amount = Money::create($this->data['amount']);
     $donationAmount = Money::create($this->data['donationAmount']);
     $donationCreditAmount = Money::create($this->data['donationCreditAmount']);
     $currentBalance = Money::create($this->data['currentBalance']);
     $newBalance = Money::create($amount->greaterThan($currentBalance) ? 0 : $currentBalance->subtract($amount));
     $amountDifference = $donationAmount->greaterThan($newBalance) ? $donationAmount->subtract($newBalance) : Money::create(0);
     return $donationCreditAmount->equals($amountDifference);
 }
Esempio n. 5
0
 public function addLenderInviteTransaction(ConnectionInterface $con, Invite $invite)
 {
     $amount = Money::create(25);
     $transactionLender = new InviteTransaction();
     $transactionLender->setLender($invite->getLender())->setAmount($amount)->setDescription('Lender invite credit')->setTransactionDate(new \DateTime())->setType(Transaction::LENDER_INVITE_INVITER);
     $transactionLender->save($con);
     $transactionInvitee = new InviteTransaction();
     $transactionInvitee->setLender($invite->getInvitee())->setAmount($amount)->setDescription('Lender invite credit')->setTransactionDate(new \DateTime())->setType(Transaction::LENDER_INVITE_INVITEE);
     $transactionInvitee->save($con);
 }
Esempio n. 6
0
 public function getCurrentBalance()
 {
     if ($this->currentBalance === null) {
         if (!\Auth::check()) {
             $this->currentBalance = Money::create(0);
         } else {
             $this->currentBalance = TransactionQuery::create()->filterByUserId(\Auth::user()->getId())->getTotalAmount();
         }
     }
     return $this->currentBalance;
 }
Esempio n. 7
0
 public function getPayment()
 {
     if (!\Auth::user()) {
         \App::abort(404, 'Fatal Error');
     }
     $lender = \Auth::user()->getLender();
     $data = $this->getData();
     $placeBidPayment = new BidPayment();
     $placeBidPayment->setCreditAmount(Money::create($data['creditAmount']))->setDonationAmount(Money::create($data['donationAmount']))->setDonationCreditAmount(Money::create($data['donationCreditAmount']))->setTransactionFee(Money::create($data['transactionFee']))->setTotalAmount(Money::create($data['totalAmount']))->setLoan($this->loan)->setAmount(Money::create($data['amount']))->setInterestRate($data['interestRate'])->setLender($lender);
     return $placeBidPayment;
 }
Esempio n. 8
0
 public function getPayment()
 {
     if (!\Auth::user()) {
         \App::abort(404, 'Fatal Error');
     }
     $lender = \Auth::user()->getLender();
     $data = $this->getData();
     $giftCardData = \Session::get('giftCard');
     $giftCardTransaction = $this->giftCardService->addGiftCardTransaction($lender, [$giftCardData]);
     $giftCardPayment = new GiftCardPayment();
     $giftCardPayment->setCreditAmount(Money::create($data['creditAmount']))->setAmount(Money::create($data['amount']))->setDonationAmount(Money::create($data['donationAmount']))->setDonationCreditAmount(Money::create($data['donationCreditAmount']))->setTransactionFee(Money::create($data['transactionFee']))->setTotalAmount(Money::create($data['totalAmount']))->setGiftCardTransaction($giftCardTransaction)->setLender($lender);
     return $giftCardPayment;
 }
Esempio n. 9
0
 public function getTransactionHistory()
 {
     $currentBalance = $this->transactionQuery->filterByUserId(Auth::getUser()->getId())->getTotalAmount();
     $page = Request::query('page') ?: 1;
     $currentBalancePageObj = DB::select('SELECT SUM(amount) AS total
          FROM transactions
          WHERE id IN (SELECT id
                       FROM transactions WHERE user_id = ?
                       ORDER BY transaction_date DESC, transactions.id DESC
                       OFFSET ?)', array(Auth::getUser()->getId(), ($page - 1) * 50));
     $currentBalancePage = Money::create($currentBalancePageObj[0]->total);
     $paginator = $this->transactionQuery->create()->orderByTransactionDate('desc')->orderById('desc')->filterByUserId(Auth::getUser()->getId())->paginate($page, 50);
     return View::make('lender.history', compact('paginator', 'currentBalance', 'currentBalancePage'));
 }
Esempio n. 10
0
 public function addGiftCardTransaction(Lender $lender, array $giftCards)
 {
     $giftCardTransaction = new GiftCardTransaction();
     PropelDB::transaction(function ($con) use($lender, $giftCards, $giftCardTransaction) {
         $giftCardTransaction->setLender($lender)->setDate(new \DateTime())->setTransactionType("Gift Card");
         foreach ($giftCards as $data) {
             $data += ['recipientEmail' => null, 'recipientName' => null, 'fromName' => null, 'message' => null, 'confirmationEmail' => null];
             $amount = Money::create($data['amount'], 'USD');
             $faker = Faker::create();
             $giftCard = new GiftCard();
             $giftCard->setLender($lender)->setTemplate($data['template'])->setOrderType($data['orderType'])->setCardAmount($amount)->setRecipientEmail($data['recipientEmail'])->setRecipientName($data['recipientName'])->setFromName($data['fromName'])->setMessage($data['message'])->setDate(new \DateTime())->setExpireDate(strtotime('+1 year'))->setCardCode($faker->creditCardNumber)->setConfirmationEmail($data['confirmationEmail']);
             $giftCardTransaction->setAmount($giftCardTransaction->getAmount()->add($amount))->setTotalCards($giftCardTransaction->getTotalCards() + 1)->addGiftCard($giftCard);
         }
         $giftCardTransaction->save($con);
     });
     return $giftCardTransaction;
 }
Esempio n. 11
0
 /**
  * @param Money $money
  * @return $this|Bid
  */
 public function setAcceptedAmount($money)
 {
     return parent::setAcceptedAmount($money->getAmount());
 }
Esempio n. 12
0
 protected function generateLoanInstallments(Loan $loan)
 {
     $calculator = new Calculator\InstallmentCalculator($loan);
     $nativeInstallmentAmount = $calculator->installmentAmount();
     $installmentCount = $loan->getInstallmentCount();
     $installments = [];
     $graceInstallment = new Installment();
     $graceInstallment->setLoan($loan)->setBorrower($loan->getBorrower())->setNativeAmount(Money::create(0))->setDueDate($calculator->installmentGraceDate());
     $installments[] = $graceInstallment;
     for ($count = 1; $count <= $installmentCount; $count++) {
         $installment = new Installment();
         $installment->setLoan($loan)->setBorrower($loan->getBorrower())->setNativeAmount($nativeInstallmentAmount)->setDueDate($calculator->nthInstallmentDate($count));
         $installments[] = $installment;
     }
     return $installments;
 }
Esempio n. 13
0
 /**
  * @return Money
  */
 public function getTotalBidAmount()
 {
     $total = $this->select(array('total'))->withColumn('SUM(bid_amount)', 'total')->findOne();
     return Money::valueOf($total, Currency::valueOf('USD'));
 }
Esempio n. 14
0
 public function getLenderInviteCredit()
 {
     return $this->amount->multiply($this->share);
 }
Esempio n. 15
0
 public function getPaypalTransactionFee()
 {
     return Money::create(parent::getPaypalTransactionFee(), 'USD');
 }
Esempio n. 16
0
 /**
  * @param $bids
  * @return array Bid
  */
 public function loanRepayments($bids)
 {
     $installmentPayments = [];
     $totalAmount = Money::create(0);
     /* @var $bid Bid */
     foreach ($bids as $bid) {
         $lender = $bid->getLender();
         if (isset($installmentPayments[$lender->getId()])) {
             $installmentPayment = $installmentPayments[$lender->getId()];
         } else {
             $installmentPayment = new LoanRepayment($lender);
         }
         $installmentPayment->addBid($bid);
         // TODO why is this not equal to $loan->getAmount()
         $totalAmount = $totalAmount->add($bid->getAcceptedAmount());
     }
     /* @var $installmentPayment LoanRepayment */
     foreach ($installmentPayments as $installmentPayment) {
         $share = $installmentPayment->getTotalAcceptedAmount()->divide($totalAmount);
         $installmentPayment->setShare($share);
     }
     return $installmentPayments;
 }
Esempio n. 17
0
 /**
  * @param Payment $payment
  * @return PaymentDetailsType
  */
 protected function setPaypalCheckoutCart(Payment $payment)
 {
     $paymentDetail = new PaymentDetailsType();
     if ($payment->getCreditAmount()->greaterThan(Money::create(0))) {
         $itemDetail = new PaymentDetailsItemType();
         $itemDetail->Name = 'Lend To Zidisha';
         $itemDetail->Amount = new BasicAmountType('USD', $payment->getCreditAmount()->round(2)->getAmount());
         $itemDetail->Quantity = '1';
         $itemDetail->ItemCategory = 'Digital';
         $paymentDetail->PaymentDetailsItem[] = $itemDetail;
     }
     if ($payment->getDonationAmount()->greaterThan(Money::create(0))) {
         $itemDetail = new PaymentDetailsItemType();
         $itemDetail->Name = 'Donation To Zidisha';
         $itemDetail->Amount = new BasicAmountType('USD', $payment->getDonationAmount()->round(2)->getAmount());
         $itemDetail->Quantity = '1';
         $itemDetail->ItemCategory = 'Digital';
         $paymentDetail->PaymentDetailsItem[] = $itemDetail;
     }
     if ($payment->getTransactionFee()->greaterThan(Money::create(0))) {
         $itemDetail = new PaymentDetailsItemType();
         $itemDetail->Name = ' Zidisha Transaction Fee';
         $itemDetail->Amount = new BasicAmountType('USD', $payment->getTransactionFee()->round(2)->getAmount());
         $itemDetail->Quantity = '1';
         $itemDetail->ItemCategory = 'Digital';
         $paymentDetail->PaymentDetailsItem[] = $itemDetail;
     }
     //Add this item to payment and set the order amount
     $paymentDetail->OrderTotal = new BasicAmountType('USD', $payment->getTotalAmount()->round(2)->getAmount());
     $paymentDetail->NotifyURL = $this->getIpnUrl();
     //Type of Payment (https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECRelatedAPIOps/)
     $paymentDetail->PaymentAction = 'Sale';
     return $paymentDetail;
 }
Esempio n. 18
0
 public function getCurrentBalance()
 {
     return Money::create(0);
 }
Esempio n. 19
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     try {
         $settings = Setting::getAll();
     } catch (\Exception $e) {
         $settings = [];
     }
     $model = $this->argument('model');
     $size = $this->argument('size');
     $faker = Faker::create();
     $countries = [['KE', 'Kenya', 'KES', '1000'], ['BJ', 'Benin', 'XOF', '0'], ['BF', 'Burkina Faso', 'XOF', '0'], ['GH', 'Ghana', 'GHS', '0'], ['ID', 'Indonesia', 'IDR', '0'], ['SN', 'Senegal', 'XOF', '0'], ['IN', 'India', 'INR', '0']];
     $temp = true;
     $allCity = [];
     if ($model == 'new') {
         $this->line('Rebuild database');
         DB::statement('drop schema public cascade');
         DB::statement('create schema public');
         exec('rm -rf app/database/migrations');
         exec('./propel diff');
         exec('./propel migrate');
         exec('./propel build');
         $this->line('Delete loans index');
         exec("curl -XDELETE 'http://*****:*****@mail.com';
         $user = new \Zidisha\User\User();
         $user->setUsername($userName);
         $user->setPassword($password);
         $user->setEmail($email);
         $user->setRole('admin');
         $user->setLastLoginAt(new Carbon());
         $user->save();
         $user = new \Zidisha\User\User();
         $user->setUsername('YC');
         $user->setPassword('1234567890');
         $user->setEmail('*****@*****.**');
         $user->setLastLoginAt(new Carbon());
         $user->save();
     }
     if ($model == "Language") {
         $languages = [['in', 'Bahasa Indonesia', true], ['fr', 'Français', true], ['hi', 'Hindi', false], ['en', 'English', false]];
         foreach ($languages as $language) {
             $lang = new Language();
             $lang->setLanguageCode($language[0]);
             $lang->setName($language[1]);
             $lang->setActive($language[2]);
             $lang->save();
         }
     }
     if ($model == "CategoryTranslation") {
         $allCategories = CategoryQuery::create()->filterByAdminOnly(false)->find();
         $allLanguages = \Zidisha\Country\LanguageQuery::create()->filterByActive(true)->find();
         foreach ($allCategories as $Category) {
             foreach ($allLanguages as $language) {
                 $translation = new CategoryTranslation();
                 $translation->setCategory($Category)->setLanguage($language)->setTranslation($Category->getName() . $language->getLanguageCode());
                 $translation->save();
             }
         }
     }
     if ($model == "ExchangeRate") {
         foreach (['KES' => 80, 'XOF' => 20, 'GHS' => 50, 'IDR' => 40, 'INR' => 80] as $currencyCode => $rate) {
             $dateMonthAgo = new DateTime();
             $dateMonthAgo->modify('-1 month');
             $dateNow = new DateTime();
             $dateNow->modify('-1 second');
             $exchangeRate = new \Zidisha\Currency\ExchangeRate();
             $exchangeRate->setCurrencyCode($currencyCode)->setRate($rate - 5)->setStartDate($dateMonthAgo)->setEndDate($dateNow);
             $exchangeRate->save();
             $exchangeRate = new \Zidisha\Currency\ExchangeRate();
             $exchangeRate->setCurrencyCode($currencyCode)->setRate($rate)->setStartDate($dateNow);
             $exchangeRate->save();
         }
     }
     for ($i = 1; $i <= $size; $i++) {
         if ($model == "Invite") {
             do {
                 $lender = $allLenders[array_rand($allLenders->getData())];
                 $invitee = $allLenders[array_rand($allLenders->getData())];
             } while ($lender->getId() == $invitee->getId());
             $lenderInvite = new Invite();
             $lenderInvite->setLender($lender);
             if (is_int($i / 4)) {
                 $lenderInvite->setEmail($faker->email);
             } else {
                 $lenderInvite->setInvitee($invitee);
                 $lenderInvite->setInvited(true);
                 $lenderInvite->setEmail($invitee->getUser()->getEmail());
             }
             $lenderInvite->save();
         }
         if ($model == "Lender") {
             $userName = '******' . $i;
             $password = '******';
             $email = 'lender' . $i . '@mail.com';
             $oneCountry = $allCountries[array_rand($allCountries->getData())];
             $user = new \Zidisha\User\User();
             $user->setUsername($userName);
             $user->setPassword($password);
             $user->setEmail($email);
             $user->setRole('lender');
             if ($i < 5) {
                 $user->setLastLoginAt(new Carbon('first day of July 2013'));
             } elseif ($i < 10) {
                 $user->setLastLoginAt(new Carbon('first day of June 2013'));
             } else {
                 $user->setLastLoginAt(new Carbon());
             }
             $firstName = 'lender' . $i;
             $lastName = 'last' . $i;
             $lender = new \Zidisha\Lender\Lender();
             $lender->setFirstName($firstName);
             $lender->setLastName($lastName);
             $lender->setCountry($oneCountry);
             $lender->setUser($user);
             $lender_profile = new \Zidisha\Lender\Profile();
             $lender_profile->setAboutMe($faker->paragraph(7));
             $lender_profile->setLender($lender);
             $lender_profile->save();
         }
         if ($model == "Borrower") {
             $userName = '******' . $i;
             $password = '******';
             $email = 'borrower' . $i . '@mail.com';
             $isMentor = $randArray[array_rand($randArray)];
             if ($i <= 40 && $isMentor) {
                 $oneCountry = $allCountries[3];
             } else {
                 $oneCountry = $allCountries[array_rand($allCountries->getData())];
             }
             $user = new \Zidisha\User\User();
             $user->setUsername($userName);
             $user->setPassword($password);
             $user->setEmail($email);
             $user->setLastLoginAt(new Carbon());
             $user->setRole('borrower');
             $firstName = 'borrower' . $i;
             $lastName = 'last' . $i;
             $borrower = new \Zidisha\Borrower\Borrower();
             $borrower->setFirstName($firstName);
             $borrower->setLastName($lastName);
             if ($isMentor) {
                 $oneCountry = $allCountries[2];
             }
             $borrower->setCountry($oneCountry);
             $borrower->setUser($user);
             $borrower->setVerified($faker->boolean());
             foreach (['communityLeader', 'familyMember', 'familyMember', 'familyMember', 'neighbor', 'neighbor', 'neighbor'] as $contactType) {
                 $contact = new \Zidisha\Borrower\Contact();
                 $contact->setPhoneNumber($faker->numberBetween(100000000, 1000000000))->setFirstName($faker->firstName)->setLastName($faker->lastName)->setDescription($faker->sentence())->setType($contactType);
                 $borrower->addContact($contact);
             }
             $borrower_profile = new \Zidisha\Borrower\Profile();
             $borrower_profile->setAboutMe($faker->paragraph(7));
             $borrower_profile->setAboutBusiness($faker->paragraph(7));
             $borrower_profile->setAddress($faker->paragraph(3));
             $borrower_profile->setAddressInstructions($faker->paragraph(6));
             if ($isMentor) {
                 $borrower_profile->setCity("Experimento");
             } elseif ($i <= 20) {
                 $city = $faker->city;
                 array_push($allCity, $city);
                 $borrower_profile->setCity($city);
             } else {
                 $borrower_profile->setCity($allCity[array_rand($allCity)]);
             }
             $borrower_profile->setPhoneNumber($faker->phoneNumber);
             $borrower_profile->setAlternatePhoneNumber($faker->phoneNumber);
             $borrower_profile->setNationalIdNumber($faker->randomNumber(10));
             $borrower_profile->setBorrower($borrower);
             if ($i <= 40) {
                 $user->setSubRole('volunteerMentor');
                 $mentor = new VolunteerMentor();
                 $borrower->setCountry($allCountries[2]);
                 $mentor->setBorrowerVolunteer($borrower)->setCountry($borrower->getCountry())->setStatus(1)->setGrantDate(new \DateTime());
             } else {
                 $allMentors = VolunteerMentorQuery::create()->find();
                 $oneMentor = $allMentors[array_rand($allMentors->getData())];
                 $borrower->setVolunteerMentor($oneMentor);
             }
             $borrower_profile->save();
             $joinLog = new JoinLog();
             $joinLog->setIpAddress($faker->ipv4)->setVerificationCode($faker->randomNumber(20))->setBorrower($borrower);
             if ($borrower->getVerified()) {
                 $joinLog->setVerifiedAt(new \DateTime());
             }
             $joinLog->save();
         }
         if ($model == "Country") {
             if ($i > sizeof($countries)) {
                 continue;
             }
             $oneCountry = $countries[$i - 1];
             $country = new Country();
             $country->setName($oneCountry[1]);
             $country->setCountryCode($oneCountry[0]);
             $country->setContinentCode('AF');
             $country->setDialingCode('000');
             $country->SetRegistrationFee($oneCountry[3]);
             $country->SetBorrowerCountry(true);
             $country->setCurrencyCode($oneCountry[2]);
             $country->setPhoneNumberLength(9);
             $country->setInstallmentPeriod($faker->randomElement([Loan::WEEKLY_INSTALLMENT, Loan::MONTHLY_INSTALLMENT]));
             if ($i < 3) {
                 $language = \Zidisha\Country\LanguageQuery::create()->filterByLanguageCode('fr')->findOne();
                 $country->setLanguage($language);
             } elseif ($i > 2) {
                 $language = \Zidisha\Country\LanguageQuery::create()->filterByLanguageCode('in')->findOne();
                 $country->setLanguage($language);
             }
             $country->save();
         }
         if ($model == "Category") {
             if ($i >= 17) {
                 continue;
             }
             $oneCategory = $categories[$i - 1];
             $category = new Category();
             $category->setName($oneCategory[0]);
             $category->setWhatDescription($oneCategory[1]);
             $category->setWhyDescription($oneCategory[2]);
             $category->setHowDescription($oneCategory[3]);
             $category->setAdminOnly($oneCategory[4]);
             $category->save();
         }
         if ($model == "Loan") {
             if ($i >= 30) {
                 $installmentDay = $i - (int) (25 - $i);
                 $amount = 30 + $i * 100;
             } else {
                 $installmentDay = $i;
                 $amount = 30 + $i * 200;
             }
             $loanCategory = $allCategories[array_rand($allCategories)];
             $status = floatval($size / 7);
             if ($i > 50 && $i < 55) {
                 $borrower = $allBorrowers[50];
             } else {
                 $borrower = $allBorrowers[$i - 1];
             }
             $data = array();
             $data['summary'] = $faker->sentence(8);
             $data['proposal'] = $faker->paragraph(7);
             $data['nativeAmount'] = $amount;
             $data['currencyCode'] = 'KES';
             $data['amount'] = $amount / 2;
             $installmentAmount = (int) $data['amount'] / 12;
             $data['installmentAmount'] = $installmentAmount;
             $data['registrationFeeRate'] = '5';
             $data['applicationDate'] = new \DateTime();
             $data['installmentDay'] = $installmentDay;
             $data['categoryId'] = $loanCategory->getId();
             $data['amountRaised'] = 40;
             if ($i < $status) {
                 $data['amountRaised'] = 0;
                 $loanService->applyForLoan($borrower, $data);
                 continue;
             }
             $Loan = Loan::createFromData($data);
             $Loan->setCategory($loanCategory);
             $Loan->setBorrower($borrower);
             $Stage = new Stage();
             $Stage->setLoan($Loan);
             $Stage->setBorrower($borrower);
             if ($i < $status * 3) {
                 $borrower->setLoanStatus(Loan::FUNDED);
                 $borrower->setActiveLoan($Loan);
                 $Loan->setStatus(Loan::FUNDED);
                 $Loan->setNativeDisbursedAmount($amount);
                 $Loan->setDisbursedDate(new \DateTime());
                 $Stage->setStatus(Loan::FUNDED);
             } elseif ($i < $status * 4) {
                 $borrower->setLoanStatus(Loan::ACTIVE);
                 $borrower->setActiveLoan($Loan);
                 $Loan->setStatus(Loan::ACTIVE);
                 $Loan->setAmountRaised($amount - $amount / 3);
                 $Loan->setDisbursedDate(new \DateTime());
                 $Stage->setStatus(Loan::ACTIVE);
             } elseif ($i < $status * 5) {
                 $borrower->setLoanStatus(Loan::REPAID);
                 $borrower->setActiveLoan($Loan);
                 $Loan->setNativeDisbursedAmount($amount);
                 $Loan->setDisbursedDate(strtotime("-1 year"));
                 $Loan->setStatus(Loan::REPAID);
                 $Stage->setStatus(Loan::REPAID);
             } elseif ($i < $status * 6) {
                 $borrower->setLoanStatus(Loan::DEFAULTED);
                 $borrower->setActiveLoan($Loan);
                 $Loan->setStatus(Loan::DEFAULTED);
                 $Stage->setStatus(Loan::DEFAULTED);
             } elseif ($i < $status * 7) {
                 $borrower->setLoanStatus(Loan::CANCELED);
                 $borrower->setActiveLoan($Loan);
                 $Loan->setStatus(Loan::CANCELED);
                 $Stage->setStatus(Loan::CANCELED);
             } else {
                 $borrower->setLoanStatus(Loan::EXPIRED);
                 $borrower->setActiveLoan($Loan);
                 $Loan->setStatus(Loan::EXPIRED);
                 $Stage->setStatus(Loan::EXPIRED);
             }
             $Stage->setStartDate(new \DateTime());
             $Stage->save();
             $borrower->save();
             $loanService->addToLoanIndex($Loan);
         }
         if ($model == "Transaction") {
             $oneLender = $allLenders[array_rand($allLenders->getData())];
             $oneLoan = $allLoans[array_rand($allLoans->getData())];
             $transaction = new Transaction();
             $transaction->setUser($oneLender->getUser());
             $transaction->setAmount(Money::create(rand(-100, 200), 'USD'));
             $transaction->setLoan($oneLoan);
             $transaction->setDescription('description');
             $transaction->setTransactionDate(new \DateTime());
             $transaction->setType(Transaction::FUND_WITHDRAW);
             $transaction->save();
             if ($temp == true) {
                 $yc = \Zidisha\User\UserQuery::create()->findOneById(2);
                 $transaction = new Transaction();
                 $transaction->setUser($yc);
                 $transaction->setAmount(Money::create(10000, 'USD'));
                 $transaction->setDescription($faker->sentence(4));
                 $transaction->setTransactionDate(new \DateTime());
                 $transaction->setType(Transaction::DONATE_BY_ADMIN);
                 $transaction->save();
                 $temp = false;
             }
         }
         if ($model == "Bid") {
             $openLoans = LoanQuery::create()->filterByStatus(0)->find();
             $oneLoan = $openLoans[array_rand($openLoans->getData())];
             $oneLender = $allLenders[array_rand($allLenders->getData())];
             $oneBid = new Bid();
             $oneBid->setBidDate(new \DateTime());
             $oneBid->setBidAmount(Money::create(rand(0, 30), 'USD'));
             $oneBid->setInterestRate(rand(0, 15));
             $oneBid->setLoan($oneLoan);
             $oneBid->setLender($oneLender);
             $oneBid->setBorrower($oneLoan->getBorrower());
             $oneBid->save();
         }
         if ($model == "Comment") {
             $borrower = $allBorrowers[array_rand($allBorrowers)];
             $user = $allBorrowers[array_rand($allBorrowers)];
             $isTranslated = $randArray[array_rand($randArray)];
             $comment = new Comment();
             $comment->setBorrower($borrower)->setUser($user->getUser())->setMessage($faker->paragraph(3))->setLevel(0);
             if ($isTranslated) {
                 $comment->setMessageTranslation($faker->paragraph(3))->setTranslatorId(1);
             } elseif ($i < 100) {
                 $comment->setUser($borrower->getUser());
             }
             $comment->save();
         }
         if ($model == "GiftCard") {
             $lender = $allLenders[array_rand($allLenders->getData())];
             $amount = Money::create(rand(15, 1000), 'USD');
             $faker = Faker::create();
             $isClaimed = $randArray[array_rand($randArray)];
             $giftCard = new GiftCard();
             $giftCard->setLender($lender)->setOrderType(array_rand([0, 1]))->setCardAmount($amount)->setFromName($lender->getName())->setMessage($faker->sentence(10))->setRecipientEmail($faker->email)->setDate(new \DateTime())->setExpireDate(strtotime('+1 year'))->setCardCode($faker->creditCardNumber);
             if ($isClaimed) {
                 $recipient = $allLenders[array_rand($allLenders->getData())];
                 $giftCard->setClaimed(1)->setRecipientName($recipient->getName())->setRecipient($recipient);
             }
             $giftCard->save();
         }
         if ($model == "LenderGroup") {
             $leader = $allLenders[array_rand($allLenders->getData())];
             $group = new LendingGroup();
             $group->setCreator($leader)->setLeader($leader)->setCreator($leader)->setAbout($faker->paragraph(2))->setName($faker->sentence(2));
             $groupMember = new LendingGroupMember();
             $groupMember->setMember($leader)->setLendingGroup($group);
             $groupMember->save();
         }
         if ($model == "LenderGroupMember") {
             $member = $allLenders[array_rand($allLenders->getData())];
             $group = $allGroups[array_rand($allGroups->getData())];
             $groupMember = new LendingGroupMember();
             $groupMember->setMember($member)->setLendingGroup($group);
             $groupMember->save();
         }
     }
 }
Esempio n. 20
0
 public function maximumAmount()
 {
     // TODO getCurrentCreditLimit
     return Money::create(10000, $this->currency);
 }
Esempio n. 21
0
 public function getNativeTotalAmount()
 {
     $total = $this->select(array('total'))->withColumn('SUM(native_amount)', 'total')->findOne();
     // Todo currency
     return Money::create($total, 'USD');
 }
Esempio n. 22
0
 public function calculateAmountRaised(Money $totalBidAmount)
 {
     if ($totalBidAmount->lessThan($this->getAmount())) {
         $percentAmountRaised = $totalBidAmount->divide($this->getAmount()->getAmount())->multiply(100)->round(2)->getAmount();
     } else {
         $percentAmountRaised = 100;
     }
     return $this->setAmountRaised($percentAmountRaised);
 }
Esempio n. 23
0
 public function getNativeAmounts(Currency $currency)
 {
     $result = $this->select(['totalAmount', 'paidAmount'])->withColumn('SUM(amount)', 'totalAmount')->withColumn('SUM(paid_amount)', 'paidAmount')->findOne();
     return ['totalAmount' => Money::create($result['totalAmount'], $currency), 'paidAmount' => Money::create($result['paidAmount'], $currency)];
 }
Esempio n. 24
0
 public function testRefundLenders(UnitTester $I)
 {
     $method = new ReflectionMethod($this->loanService, 'refundLenders');
     $method->setAccessible(true);
     $con = Propel::getWriteConnection(TransactionTableMap::DATABASE_NAME);
     $con->beginTransaction();
     $loan = \Zidisha\Loan\LoanQuery::create()->findOneById(5);
     $lender1 = \Zidisha\Lender\LenderQuery::create()->findOneById(203);
     $lender2 = \Zidisha\Lender\LenderQuery::create()->findOneById(204);
     $lender3 = \Zidisha\Lender\LenderQuery::create()->findOneById(205);
     try {
         $this->transactionService->addPlaceBidTransaction($con, Money::create(50), $loan, $lender1);
         $this->transactionService->addPlaceBidTransaction($con, Money::create(30), $loan, $lender2);
         $this->transactionService->addPlaceBidTransaction($con, Money::create(40), $loan, $lender3);
         $this->transactionService->addOutBidTransaction($con, Money::create(20), $loan, $lender1);
         $this->transactionService->addUpdateBidTransaction($con, Money::create(10), $loan, $lender2);
         $this->transactionService->addOutBidTransaction($con, Money::create(10), $loan, $lender1);
         $refunds = $method->invoke($this->loanService, $con, $loan, Loan::EXPIRED);
         verify($refunds[$lender1->getId()]['refundAmount'])->equals(Money::create(20));
         verify($refunds[$lender2->getId()]['refundAmount'])->equals(Money::create(40));
         verify($refunds[$lender3->getId()]['refundAmount'])->equals(Money::create(40));
         $lender1VerifyRefund = \Zidisha\Balance\TransactionQuery::create()->filterByUserId($lender1->getId())->filterByType(Transaction::LOAN_OUTBID)->filterBySubType(Transaction::LOAN_BID_EXPIRED)->count();
         $lender2VerifyRefund = \Zidisha\Balance\TransactionQuery::create()->filterByUserId($lender2->getId())->filterByType(Transaction::LOAN_OUTBID)->filterBySubType(Transaction::LOAN_BID_EXPIRED)->count();
         $lender3VerifyRefund = \Zidisha\Balance\TransactionQuery::create()->filterByUserId($lender1->getId())->filterByType(Transaction::LOAN_OUTBID)->filterBySubType(Transaction::LOAN_BID_EXPIRED)->count();
         verify($lender1VerifyRefund)->equals(1);
         verify($lender2VerifyRefund)->equals(1);
         verify($lender3VerifyRefund)->equals(1);
         $con->rollBack();
     } catch (\Exception $e) {
         $con->rollBack();
         throw $e;
     }
 }
Esempio n. 25
0
 public function getCardAmount()
 {
     return Money::create(parent::getCardAmount(), 'USD');
 }
Esempio n. 26
0
 public function addRepayment(Loan $loan, \Datetime $date, Money $amount, BorrowerPayment $borrowerPayment = null)
 {
     // Divide the payment in the lenders and the web site fee
     // 1. Get the web site fee %
     // 2. Get who all lended and how much
     // 3. substract he website fee out of this installment
     // 4. remaining money should be divided in lenders according to their proportion and added
     // 5. If the loan gets completed with this payment set the loan status to complete
     $calculator = $this->getRepaymentCalculator($loan, $amount);
     if ($calculator->unpaidAmount()->isNegative()) {
         throw new \Exception('Unpaid amount is negative');
     }
     $con = Propel::getWriteConnection(TransactionTableMap::DATABASE_NAME);
     $con->beginTransaction();
     $refundThreshold = $this->currencyService->convertFromUSD(Money::create(1), $loan->getCurrency(), $date);
     $refundAmount = $calculator->refundAmount($refundThreshold);
     if ($refundAmount->isPositive()) {
         $this->addBorrowerRefund($con, $loan, $refundAmount);
         $amount = $amount->subtract($refundAmount);
         $calculator->setRepaymentAmount($amount);
     }
     $this->transactionService->addInstallmentTransaction($con, $amount, $loan, $date);
     $nativeFeeAmount = $calculator->installmentServiceFee();
     $feeAmount = $this->currencyService->convertToUSD($nativeFeeAmount, $date);
     $this->transactionService->addInstallmentFeeTransaction($con, $loan, $feeAmount, $date);
     $bids = BidQuery::create()->filterByLoan($loan)->filterByActive(true)->find();
     $loanRepayments = $calculator->loanRepayments($bids);
     /** @var $loanRepayment LoanRepayment */
     foreach ($loanRepayments as $loanRepayment) {
         $lender = $loanRepayment->getLender();
         $nativeLenderAmount = $loanRepayment->getAmount();
         $nativeLenderInviteCredit = $loanRepayment->getLenderInviteCredit();
         if ($nativeLenderAmount->isPositive()) {
             $lenderAmount = $this->currencyService->convertToUSD($nativeLenderAmount, $date);
             $this->transactionService->addRepaymentTransaction($con, $lenderAmount, $loan, $lender, $date);
         }
         if ($nativeLenderInviteCredit->isPositive()) {
             $lenderInviteCredit = $this->currencyService->convertToUSD($nativeLenderInviteCredit, $date);
             $this->transactionService->addLenderInviteCreditRepaymentTransaction($con, $lenderInviteCredit, $loan, $date);
         }
     }
     $updatedInstallments = $this->updateInstallmentSchedule($con, $loan, $amount, $date);
     // TODO
     // $database->setOntimeRepayCredit($rest4, $borrowerid, $amount);
     // TODO
     // $database->loanpaidback($borrowerid,$loanid);
     // TODO emails/sms
 }
Esempio n. 27
0
 /**
  * @param Money $money
  * @return $this|Installment
  */
 public function setNativePaidAmount($money)
 {
     return parent::setNativePaidAmount($money->getAmount());
 }
Esempio n. 28
0
 public function getNativeTotalAmount(Currency $currency)
 {
     $total = $this->select(array('total'))->withColumn('SUM(amount * exchangeRate)', 'total')->findOne();
     return Money::create($total, $currency);
 }