110 lines
3.3 KiB
PHP
110 lines
3.3 KiB
PHP
<?php
|
|
|
|
namespace Modules\EcommerceFinance\Services;
|
|
|
|
use Illuminate\Database\ConnectionInterface;
|
|
use Illuminate\Database\DatabaseManager;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Modules\EcommerceFinance\Support\OaProcessTime;
|
|
use RuntimeException;
|
|
|
|
class DingTalkProcessInstanceDailyBudget
|
|
{
|
|
public const TABLE = 'ding_process_api_daily_usage';
|
|
|
|
private readonly ConnectionInterface $connection;
|
|
|
|
public function __construct(DatabaseManager $database)
|
|
{
|
|
$this->connection = $database->connection(
|
|
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
|
);
|
|
}
|
|
|
|
public function limit(): int
|
|
{
|
|
return min(
|
|
max((int) config('dingtalk.process_daily_call_limit', 20000), 1),
|
|
20000,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Atomically reserve part of today's OA process-instance budget.
|
|
* The returned number is the maximum number of HTTP requests allowed now.
|
|
*/
|
|
public function reserve(int $requestedCalls): int
|
|
{
|
|
if ($requestedCalls <= 0) {
|
|
return 0;
|
|
}
|
|
|
|
$this->ensureTableExists();
|
|
|
|
return (int) $this->connection->transaction(function () use ($requestedCalls): int {
|
|
$now = OaProcessTime::now();
|
|
$usageDate = $now->toDateString();
|
|
|
|
$this->connection->table(self::TABLE)->insertOrIgnore([
|
|
'usage_date' => $usageDate,
|
|
'reserved_calls' => 0,
|
|
'created_at' => $now,
|
|
'updated_at' => $now,
|
|
]);
|
|
|
|
$row = $this->connection->table(self::TABLE)
|
|
->where('usage_date', $usageDate)
|
|
->lockForUpdate()
|
|
->first();
|
|
if ($row === null) {
|
|
throw new RuntimeException('OA 流程 API 日限额记录创建失败。');
|
|
}
|
|
|
|
$used = max(0, (int) ($row->reserved_calls ?? 0));
|
|
$granted = min($requestedCalls, max(0, $this->limit() - $used));
|
|
if ($granted <= 0) {
|
|
return 0;
|
|
}
|
|
|
|
$this->connection->table(self::TABLE)
|
|
->where('usage_date', $usageDate)
|
|
->update([
|
|
'reserved_calls' => $used + $granted,
|
|
'updated_at' => $now,
|
|
]);
|
|
|
|
return $granted;
|
|
}, 3);
|
|
}
|
|
|
|
/** @return array{date:string,used:int,limit:int,remaining:int} */
|
|
public function usage(): array
|
|
{
|
|
$usageDate = OaProcessTime::now()->toDateString();
|
|
$used = 0;
|
|
if (Schema::connection($this->connection->getName())->hasTable(self::TABLE)) {
|
|
$used = max(0, (int) (
|
|
$this->connection->table(self::TABLE)
|
|
->where('usage_date', $usageDate)
|
|
->value('reserved_calls')
|
|
?? 0
|
|
));
|
|
}
|
|
$limit = $this->limit();
|
|
|
|
return [
|
|
'date' => $usageDate,
|
|
'used' => $used,
|
|
'limit' => $limit,
|
|
'remaining' => max(0, $limit - $used),
|
|
];
|
|
}
|
|
|
|
private function ensureTableExists(): void
|
|
{
|
|
if (! Schema::connection($this->connection->getName())->hasTable(self::TABLE)) {
|
|
throw new RuntimeException('OA 流程 API 日限额表尚未迁移。');
|
|
}
|
|
}
|
|
}
|