PartialPayment.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. // Copyright 2019 Hackware SpA <human@hackware.cl>
  3. // This file is part of "Hackware Web Services Wallet" and licensed under
  4. // the terms of the GNU Affero General Public License version 3, or (at your
  5. // option) a later version. You should have received a copy of this license
  6. // along with the software. If not, see <https://www.gnu.org/licenses/>.
  7. namespace Hawese\Wallet;
  8. use Hawese\Core\Exceptions\ModelObjectNotFoundException;
  9. class PartialPayment extends TableModel
  10. {
  11. const AMOUNT_P = 8;
  12. public static $table = 'partial_payments';
  13. public static $attributes = [
  14. 'transaction_id' => [ // foreign and primary! o_O
  15. 'required', 'integer', 'min:1', 'exists:transactions,id'
  16. ],
  17. 'amount' => ['required', 'regex:/^-?\d{1,8}(?:\.\d{1,8})?$/'],
  18. 'created_at' => ['nullable', 'date'],
  19. 'updated_at' => ['nullable', 'date']
  20. ];
  21. public static $primary_key = 'transaction_id';
  22. protected static $incrementing = false;
  23. public static $foreign_keys = ['transaction_id' => Transaction::class];
  24. /**
  25. * Updates or create an initial PartialPayment.
  26. */
  27. public static function addOrCreate(
  28. int $transaction_id,
  29. string $amount
  30. ): self {
  31. try {
  32. $partial_payment = self::find($transaction_id);
  33. $partial_payment->amount = bcadd(
  34. $partial_payment->amount,
  35. $amount,
  36. self::AMOUNT_P
  37. );
  38. $partial_payment->update(['amount']);
  39. } catch (ModelObjectNotFoundException $e) {
  40. $partial_payment = new self([
  41. 'transaction_id' => $transaction_id,
  42. 'amount' => $amount,
  43. ]);
  44. $partial_payment->insert();
  45. }
  46. return $partial_payment;
  47. }
  48. }