Бартер: начало.

This commit is contained in:
Igor Barkov (iwork) 2021-08-30 19:30:56 +03:00
parent 198092b44a
commit 2760e17c6b
2 changed files with 117 additions and 49 deletions

View File

@ -1,6 +1,8 @@
<?php <?php
namespace Battles; namespace Battles;
use Battles\Database\DBPDO;
class Item class Item
{ {
protected int $item_id; protected int $item_id;
@ -108,7 +110,7 @@ class Item
/** Рассчёт стоимости предмета в зависимости от его характеристик. /** Рассчёт стоимости предмета в зависимости от его характеристик.
* @return int * @return int
*/ */
private function calculateItemCost(): int protected function calculateItemCost(): int
{ {
$sum_stats = $sum_stats =
$this->add_strength + $this->add_strength +
@ -188,4 +190,9 @@ class Item
} }
return $str; return $str;
} }
public static function getItemById($item_id): Item
{
return new Item(DBPDO::$db->ofetch('select * from items where id = ?', $item_id));
}
} }

View File

@ -9,6 +9,7 @@ class ShopItem extends Item
{ {
private const NO_ITEMS_IN_STOCK = "Товара нет в наличии!"; private const NO_ITEMS_IN_STOCK = "Товара нет в наличии!";
private const NO_MONEY = "У вас нет денег!"; private const NO_MONEY = "У вас нет денег!";
private const NO_BARTER_ITEMS = 'У вас нет требуемых предметов!';
private const BUTTON = [ private const BUTTON = [
'setmarket' => 'Сдать в магазин', 'setmarket' => 'Сдать в магазин',
'unsetmarket' => 'Снять с продажи', 'unsetmarket' => 'Снять с продажи',
@ -50,6 +51,8 @@ SQL;
private ?int $shop_item_quantity; private ?int $shop_item_quantity;
private ?int $price; private ?int $price;
public static string $status = ''; public static string $status = '';
private ?string $jsonBarterList;
private int $offerId;
public function __construct($row, $operationType = null) public function __construct($row, $operationType = null)
{ {
@ -60,32 +63,60 @@ SQL;
$this->price = $row->price ?? null; $this->price = $row->price ?? null;
$this->shop_item_quantity = $row->shop_item_quantity ?? null; $this->shop_item_quantity = $row->shop_item_quantity ?? null;
$this->item_id = $row->item_id ?? $row->id; $this->item_id = $row->item_id ?? $row->id;
$this->jsonBarterList = $row->barter_items_list_json;
$this->offerId = $row->offer_id; // Ид позиции в магазине.
} }
public function printInfo(): string public function printInfo(): string
{ {
//$this->printAllInfo();
$str = $this->getAllInfo(); $str = $this->getAllInfo();
if ($this->optype === 'buyshop' && $this->shop_item_quantity > 0 && $this->shop_item_quantity < 20) { if ($this->optype === 'buyshop') {
$str .= "<div style='margin-top: 9px; font-style: italic;'>На складе осталось $this->shop_item_quantity единиц товара!</div>"; $str .= $this->getLowItemQuantityNote();
$str .= $this->getBarterList();
} }
if ($this->optype === 'sellshop') { if ($this->optype === 'sellshop') {
if ($this->getSellPriceMean() < 50) { $str .= $this->getTextBasedOnPrice();
$goods = 'этот хлам';
} elseif ($this->getSellPriceMean() < 100) {
$goods = 'этот посредственный товар';
} elseif ($this->getSellPriceMean() < 500) {
$goods = 'этот неплохой предмет';
} elseif ($this->getSellPriceMean() < 1000) {
$goods = 'эту отличную штуку';
} else {
$goods = 'это превосходное изделие';
}
$str .= "<div style='margin-top: 9px; font-style: italic;'>В среднем за $goods можно выручить <span class='success'>{$this->getSellPriceMean()}</span> кр.</div>";
} }
return $str; return $str;
} }
private function getBarterList(): string
{
if (!$this->jsonBarterList) {
return '';
}
$str = '<div><br>Помимо денег требуются следующие товары:';
foreach (json_decode($this->jsonBarterList) as $item) {
$str .= '<br>↣ ' . Item::getItemById($item->item_id)->name . ', ' . $item->quantity . ' шт.';
}
$str .= '</div>';
return $str;
}
private function getLowItemQuantityNote(): string
{
if ($this->shop_item_quantity < 1 || $this->shop_item_quantity > 19) {
return '';
}
return "<div style='margin-top: 9px; font-style: italic;'>На складе осталось $this->shop_item_quantity единиц товара!</div>";
}
private function getTextBasedOnPrice(): string
{
if ($this->getSellPriceMean() < 50) {
$goods = 'этот хлам';
} elseif ($this->getSellPriceMean() < 100) {
$goods = 'этот посредственный товар';
} elseif ($this->getSellPriceMean() < 500) {
$goods = 'этот неплохой предмет';
} elseif ($this->getSellPriceMean() < 1000) {
$goods = 'эту отличную штуку';
} else {
$goods = 'это превосходное изделие';
}
return "<div style='margin-top: 9px; font-style: italic;'>В среднем за $goods можно выручить <span class='success'>{$this->getSellPriceMean()}</span> кр.</div>";
}
public function printImage(): string public function printImage(): string
{ {
if (!$this->image) { if (!$this->image) {
@ -94,47 +125,77 @@ SQL;
return "<img src='/i/sh/$this->image' class='item-wrap-normal' alt=''>"; return "<img src='/i/sh/$this->image' class='item-wrap-normal' alt=''>";
} }
//todo наличка после покупки отображается с задержкой.
public static function buyItem($id, User $buyer) public static function buyItem($id, User $buyer)
{ {
$db = new DBPDO(); $check = DBPDO::$db->ofetch("select * from trade_offers where shop_item_id = ?", $id);
$check = $db->ofetch("select * from trade_offers where shop_item_id = ?", $id); $item = new Item(DBPDO::$db->fetch('select * from items where id = ?', $id));
if (empty($check->shop_item_quantity) || empty($check->shop_item_id)) { $price = $item->calculateItemCost();
self::$status = self::NO_ITEMS_IN_STOCK;
if (
!self::checkAndRemoveBarteredItems($check->barter_item_list_json, $buyer->getId()) ||
!self::checkAndPayTheBills($price, $buyer) ||
!self::checkAndChangeRemainingItems($check->shop_item_quantity, $check->shop_item_id)
) {
return;
} }
// TODO БАРТЕР! DBPDO::$db->execute(self::BUY_QUERY, [$buyer->getId(), $check->shop_item_id]);
if (isset($check->barter_item_list_json)) { $deloText = $buyer->getLogin() . " купил товар «" . Item::getItemById($item->item_id)->name . "» id:(" . $item->item_id . ") в магазине за " . $price . ".";
self::$status = "Работаем по бартеру!"; GameLogs::addUserLog($buyer->getId(), $deloText);
} self::$status = "Предмет " . $item->name . " куплен за " . $price . ".";
}
$db->execute(self::BUY_QUERY, [$buyer->getId(), $check->shop_item_id]); private static function checkAndRemoveBarteredItems(string $json_list, int $user_id): bool
$item = $db->ofetch("select item_id, name, price from inventory where item_id = ?", $db->lastInsertId()); {
if (empty($item->item_id) || empty($item->name)) { if (empty($json_list)) {
self::$status = 'Запрос в базу не прошёл.'; return true;
} else { }
$user = new User($_SESSION['uid']); $allowItemRemove = true;
// Если не хватает налички, снимаем с банка с комиссией. foreach (json_decode($json_list) as $item) {
if ($user->getMoney() < $item->price) { $row = DBPDO::$db->ofetch('select sum(1) as s from inventory where name = ? and owner_id = ?', [Item::getItemById($item->item_id)->name, $user_id]);
try { if ($row->s < $item->quantity) {
$bank = new Bank($buyer->getId()); $allowItemRemove = false;
$bank->withdrawMoney($item->price);
} catch (GameException $e) {
self::$status = 'Банковская ошибка! ' . self::NO_MONEY;
}
} else {
$user->setMoney($user->getMoney() - $item->price);
$user->saveMoney();
} }
} }
if (!$allowItemRemove) {
if ($check->shop_item_quantity != -1) { self::$status = self::NO_BARTER_ITEMS;
$db->execute("update trade_offers set shop_item_quantity = shop_item_quantity -1 where shop_item_id = ?", $check->shop_item_id); return false;
} }
foreach (json_decode($json_list) as $item) {
DBPDO::$db->execute('delete from inventory where name = ? and owner_id = ? limit ?', [Item::getItemById($item->item_id)->name, $user_id, $item->quantity]);
}
return true;
$deloText = $buyer->getLogin() . " купил товар «" . $item->name . "» id:(" . $item->item_id . ") в магазине за " . $item->price . "."; }
GameLogs::addUserLog($buyer->getId(), $deloText);
self::$status = "Предмет " . $item->name . " куплен за " . $item->price . "."; private static function checkAndPayTheBills(int $price, User $user): bool
{
if ($user->getMoney() > $price) {
$user->setMoney($user->getMoney() - $price);
$user->saveMoney();
return true;
}
try {
$bank = new Bank($user->getId());
$bank->withdrawMoney($price);
return true;
} catch (GameException $e) {
self::$status = 'Банковская ошибка! ' . self::NO_MONEY;
return false;
}
}
private static function checkAndChangeRemainingItems(int $current_quantity, $item_id): bool
{
if (empty($current_quantity)) {
self::$status = self::NO_ITEMS_IN_STOCK;
return false;
}
if ($current_quantity === -1) {
return true;
}
DBPDO::$db->execute("update trade_offers set shop_item_quantity = shop_item_quantity -1 where shop_item_quantity != -1 and shop_item_id = ? ", $item_id);
return true;
} }
public static function sellItem($id, User $seller, $bankTrade = 0) public static function sellItem($id, User $seller, $bankTrade = 0)
@ -186,7 +247,7 @@ SQL;
$button_name = self::BUTTON[$this->optype]; $button_name = self::BUTTON[$this->optype];
return <<<FORM return <<<FORM
<form method="post">$str <form method="post">$str
<input type="hidden" name="itemId" value="$this->item_id"> <input type="hidden" name="itemId" value="$this->offerId">
<br><input type="submit" name="$this->optype" value="$button_name"> <br><input type="submit" name="$this->optype" value="$button_name">
</form> </form>
FORM; FORM;