Бартер: начало.
This commit is contained in:
parent
198092b44a
commit
2760e17c6b
@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Battles;
|
||||
use Battles\Database\DBPDO;
|
||||
|
||||
class Item
|
||||
{
|
||||
protected int $item_id;
|
||||
@ -108,7 +110,7 @@ class Item
|
||||
/** Рассчёт стоимости предмета в зависимости от его характеристик.
|
||||
* @return int
|
||||
*/
|
||||
private function calculateItemCost(): int
|
||||
protected function calculateItemCost(): int
|
||||
{
|
||||
$sum_stats =
|
||||
$this->add_strength +
|
||||
@ -188,4 +190,9 @@ class Item
|
||||
}
|
||||
return $str;
|
||||
}
|
||||
|
||||
public static function getItemById($item_id): Item
|
||||
{
|
||||
return new Item(DBPDO::$db->ofetch('select * from items where id = ?', $item_id));
|
||||
}
|
||||
}
|
@ -9,6 +9,7 @@ class ShopItem extends Item
|
||||
{
|
||||
private const NO_ITEMS_IN_STOCK = "Товара нет в наличии!";
|
||||
private const NO_MONEY = "У вас нет денег!";
|
||||
private const NO_BARTER_ITEMS = 'У вас нет требуемых предметов!';
|
||||
private const BUTTON = [
|
||||
'setmarket' => 'Сдать в магазин',
|
||||
'unsetmarket' => 'Снять с продажи',
|
||||
@ -50,6 +51,8 @@ SQL;
|
||||
private ?int $shop_item_quantity;
|
||||
private ?int $price;
|
||||
public static string $status = '';
|
||||
private ?string $jsonBarterList;
|
||||
private int $offerId;
|
||||
|
||||
public function __construct($row, $operationType = null)
|
||||
{
|
||||
@ -60,32 +63,60 @@ SQL;
|
||||
$this->price = $row->price ?? null;
|
||||
$this->shop_item_quantity = $row->shop_item_quantity ?? null;
|
||||
$this->item_id = $row->item_id ?? $row->id;
|
||||
$this->jsonBarterList = $row->barter_items_list_json;
|
||||
$this->offerId = $row->offer_id; // Ид позиции в магазине.
|
||||
}
|
||||
|
||||
public function printInfo(): string
|
||||
{
|
||||
//$this->printAllInfo();
|
||||
$str = $this->getAllInfo();
|
||||
if ($this->optype === 'buyshop' && $this->shop_item_quantity > 0 && $this->shop_item_quantity < 20) {
|
||||
$str .= "<div style='margin-top: 9px; font-style: italic;'>На складе осталось $this->shop_item_quantity единиц товара!</div>";
|
||||
if ($this->optype === 'buyshop') {
|
||||
$str .= $this->getLowItemQuantityNote();
|
||||
$str .= $this->getBarterList();
|
||||
}
|
||||
if ($this->optype === 'sellshop') {
|
||||
if ($this->getSellPriceMean() < 50) {
|
||||
$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>";
|
||||
$str .= $this->getTextBasedOnPrice();
|
||||
}
|
||||
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
|
||||
{
|
||||
if (!$this->image) {
|
||||
@ -94,47 +125,77 @@ SQL;
|
||||
return "<img src='/i/sh/$this->image' class='item-wrap-normal' alt=''>";
|
||||
}
|
||||
|
||||
//todo наличка после покупки отображается с задержкой.
|
||||
public static function buyItem($id, User $buyer)
|
||||
{
|
||||
$db = new DBPDO();
|
||||
$check = $db->ofetch("select * from trade_offers where shop_item_id = ?", $id);
|
||||
if (empty($check->shop_item_quantity) || empty($check->shop_item_id)) {
|
||||
self::$status = self::NO_ITEMS_IN_STOCK;
|
||||
$check = DBPDO::$db->ofetch("select * from trade_offers where shop_item_id = ?", $id);
|
||||
$item = new Item(DBPDO::$db->fetch('select * from items where id = ?', $id));
|
||||
$price = $item->calculateItemCost();
|
||||
|
||||
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 БАРТЕР!
|
||||
if (isset($check->barter_item_list_json)) {
|
||||
self::$status = "Работаем по бартеру!";
|
||||
}
|
||||
DBPDO::$db->execute(self::BUY_QUERY, [$buyer->getId(), $check->shop_item_id]);
|
||||
$deloText = $buyer->getLogin() . " купил товар «" . Item::getItemById($item->item_id)->name . "» id:(" . $item->item_id . ") в магазине за " . $price . ".";
|
||||
GameLogs::addUserLog($buyer->getId(), $deloText);
|
||||
self::$status = "Предмет " . $item->name . " куплен за " . $price . ".";
|
||||
}
|
||||
|
||||
$db->execute(self::BUY_QUERY, [$buyer->getId(), $check->shop_item_id]);
|
||||
$item = $db->ofetch("select item_id, name, price from inventory where item_id = ?", $db->lastInsertId());
|
||||
if (empty($item->item_id) || empty($item->name)) {
|
||||
self::$status = 'Запрос в базу не прошёл.';
|
||||
} else {
|
||||
$user = new User($_SESSION['uid']);
|
||||
// Если не хватает налички, снимаем с банка с комиссией.
|
||||
if ($user->getMoney() < $item->price) {
|
||||
try {
|
||||
$bank = new Bank($buyer->getId());
|
||||
$bank->withdrawMoney($item->price);
|
||||
} catch (GameException $e) {
|
||||
self::$status = 'Банковская ошибка! ' . self::NO_MONEY;
|
||||
}
|
||||
} else {
|
||||
$user->setMoney($user->getMoney() - $item->price);
|
||||
$user->saveMoney();
|
||||
private static function checkAndRemoveBarteredItems(string $json_list, int $user_id): bool
|
||||
{
|
||||
if (empty($json_list)) {
|
||||
return true;
|
||||
}
|
||||
$allowItemRemove = true;
|
||||
foreach (json_decode($json_list) as $item) {
|
||||
$row = DBPDO::$db->ofetch('select sum(1) as s from inventory where name = ? and owner_id = ?', [Item::getItemById($item->item_id)->name, $user_id]);
|
||||
if ($row->s < $item->quantity) {
|
||||
$allowItemRemove = false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($check->shop_item_quantity != -1) {
|
||||
$db->execute("update trade_offers set shop_item_quantity = shop_item_quantity -1 where shop_item_id = ?", $check->shop_item_id);
|
||||
if (!$allowItemRemove) {
|
||||
self::$status = self::NO_BARTER_ITEMS;
|
||||
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)
|
||||
@ -186,7 +247,7 @@ SQL;
|
||||
$button_name = self::BUTTON[$this->optype];
|
||||
return <<<FORM
|
||||
<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">
|
||||
</form>
|
||||
FORM;
|
||||
|
Loading…
Reference in New Issue
Block a user