fix(权限): 供应商登录使用钉钉当前组织
供应商登录使用钉钉当前组织部门,HR 副本保留为兼容回退。 Co-authored-by: 苏木 <594326199@qq.com> Co-committed-by: 苏木 <594326199@qq.com>
This commit is contained in:
parent
64c50ba414
commit
29d19aaa34
@ -32,6 +32,7 @@ class DingTalkClosedAccess
|
||||
$supplierRosters = $roster ? [] : app(SupplierPortalAccess::class)->resolveAll(
|
||||
(string) ($profile['dingtalk_user_id'] ?? ''),
|
||||
(string) ($profile['union_id'] ?? ''),
|
||||
(array) ($profile['department_ids'] ?? []),
|
||||
);
|
||||
if (! $roster && $supplierRosters === []) {
|
||||
$this->audit('login_denied', 'denied', null, null, $profile['union_id'] ?? null, $request, [
|
||||
|
||||
@ -109,7 +109,8 @@ class DingTalkOAuthClient
|
||||
* nickname: string|null,
|
||||
* email: string|null,
|
||||
* mobile: string|null,
|
||||
* active: bool
|
||||
* active: bool,
|
||||
* department_ids: list<string>
|
||||
* }
|
||||
*/
|
||||
public function enterpriseUser(array $oauthProfile): array
|
||||
@ -120,7 +121,7 @@ class DingTalkOAuthClient
|
||||
}
|
||||
|
||||
$enterpriseProfile = Cache::remember(
|
||||
'dingtalk:enterprise-user:' . hash('sha256', $unionId),
|
||||
'dingtalk:enterprise-user:v2:' . hash('sha256', $unionId),
|
||||
now()->addMinutes(max(
|
||||
1,
|
||||
(int) config('dingtalk.enterprise_user_cache_minutes', 10),
|
||||
@ -195,6 +196,7 @@ class DingTalkOAuthClient
|
||||
'email' => $this->nullableString($detail['email'] ?? null),
|
||||
'mobile' => $this->nullableString($detail['mobile'] ?? null),
|
||||
'active' => $active === true,
|
||||
'department_ids' => $this->departmentIds($detail['dept_id_list'] ?? []),
|
||||
];
|
||||
},
|
||||
);
|
||||
@ -206,6 +208,60 @@ class DingTalkOAuthClient
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the current DingTalk department ancestry for a member.
|
||||
*
|
||||
* This is separate from the upstream HR replica: supplier organization
|
||||
* members can appear in DingTalk before HR data catches up.
|
||||
*
|
||||
* @param list<int|string> $departmentIds
|
||||
* @return list<array{Id:int,parent_id:int,name:string,depth:int}>
|
||||
*/
|
||||
public function departmentLineage(array $departmentIds): array
|
||||
{
|
||||
$departmentIds = array_slice(array_values(array_unique(array_filter(
|
||||
array_map(static fn (mixed $id): string => trim((string) $id), $departmentIds),
|
||||
static fn (string $id): bool => ctype_digit($id) && (int) $id > 0,
|
||||
))), 0, 64);
|
||||
if ($departmentIds === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$lineage = [];
|
||||
$seen = [];
|
||||
$queue = array_map(static fn (string $id): array => [(int) $id, 0], $departmentIds);
|
||||
|
||||
while ($queue !== []) {
|
||||
[$departmentId, $depth] = array_shift($queue);
|
||||
if (isset($seen[$departmentId])) {
|
||||
continue;
|
||||
}
|
||||
if ($depth >= 20) {
|
||||
throw new RuntimeException('DingTalk department hierarchy is too deep.');
|
||||
}
|
||||
|
||||
$seen[$departmentId] = true;
|
||||
$department = $this->departmentDetail($departmentId);
|
||||
$realDepartmentId = (int) ($department['dept_id'] ?? $departmentId);
|
||||
$lineage[$realDepartmentId] = [
|
||||
'Id' => $realDepartmentId,
|
||||
'parent_id' => (int) ($department['parent_id'] ?? 0),
|
||||
'name' => trim((string) ($department['name'] ?? '')),
|
||||
'depth' => $depth,
|
||||
];
|
||||
if (count($lineage) > 256) {
|
||||
throw new RuntimeException('DingTalk department hierarchy is too large.');
|
||||
}
|
||||
|
||||
$parentId = (int) ($department['parent_id'] ?? 0);
|
||||
if ($parentId > 1 && ! isset($seen[$parentId])) {
|
||||
$queue[] = [$parentId, $depth + 1];
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($lineage);
|
||||
}
|
||||
|
||||
public function appAccessToken(): string
|
||||
{
|
||||
if ($this->cachedAppAccessToken !== null) {
|
||||
@ -249,6 +305,62 @@ class DingTalkOAuthClient
|
||||
return max(3, min(30, (int) config('dingtalk.timeout', 10)));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function departmentDetail(int $departmentId): array
|
||||
{
|
||||
return Cache::remember(
|
||||
'dingtalk:department:v1:' . $departmentId,
|
||||
now()->addMinutes(max(
|
||||
1,
|
||||
(int) config('dingtalk.enterprise_user_cache_minutes', 10),
|
||||
)),
|
||||
function () use ($departmentId): array {
|
||||
$appToken = $this->appAccessToken();
|
||||
|
||||
try {
|
||||
$response = Http::asJson()
|
||||
->acceptJson()
|
||||
->timeout($this->timeout())
|
||||
->withQueryParameters(['access_token' => $appToken])
|
||||
->post(
|
||||
$this->configuredString('dingtalk.department_detail_url'),
|
||||
['dept_id' => $departmentId],
|
||||
)
|
||||
->throw();
|
||||
} catch (RequestException $exception) {
|
||||
throw new RuntimeException(
|
||||
'DingTalk department detail lookup failed.',
|
||||
0,
|
||||
$exception,
|
||||
);
|
||||
}
|
||||
|
||||
$detail = $response->json('result');
|
||||
if ((int) $response->json('errcode', -1) !== 0 || ! is_array($detail)) {
|
||||
throw new RuntimeException('DingTalk department detail was unavailable.');
|
||||
}
|
||||
|
||||
return $detail;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function departmentIds(mixed $value): array
|
||||
{
|
||||
$parts = is_array($value) ? $value : preg_split(
|
||||
'/[\[\]\/>,,;;||\s]+/u',
|
||||
trim((string) $value),
|
||||
-1,
|
||||
PREG_SPLIT_NO_EMPTY,
|
||||
);
|
||||
|
||||
return array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $id): string => is_scalar($id) ? trim((string) $id) : '',
|
||||
is_array($parts) ? $parts : [],
|
||||
), static fn (string $id): bool => ctype_digit($id) && (int) $id > 0)));
|
||||
}
|
||||
|
||||
protected function nullableString(mixed $value): ?string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
@ -9,7 +9,9 @@ use App\Models\Auth\User;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
|
||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery;
|
||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 钉钉企业组织中的供应商成员映射。
|
||||
@ -26,6 +28,7 @@ class SupplierPortalAccess
|
||||
public function __construct(
|
||||
private readonly UpstreamReadOnlyQueryFactory $queries,
|
||||
private readonly SupplierManagementMirrorRepository $suppliers,
|
||||
private readonly ?DingTalkOAuthClient $dingTalk = null,
|
||||
) {
|
||||
}
|
||||
|
||||
@ -34,18 +37,22 @@ class SupplierPortalAccess
|
||||
return $user->created_from === self::CREATED_FROM;
|
||||
}
|
||||
|
||||
/** @return array{supplier_name:string,supplier_code:string,dingtalk_group_id:int,dingtalk_group_name:string}|null */
|
||||
public function resolve(string $userId, string $unionId = ''): ?array
|
||||
/**
|
||||
* @param list<int|string> $currentDepartmentIds
|
||||
* @return array{supplier_name:string,supplier_code:string,dingtalk_group_id:int,dingtalk_group_name:string}|null
|
||||
*/
|
||||
public function resolve(string $userId, string $unionId = '', array $currentDepartmentIds = []): ?array
|
||||
{
|
||||
$resolved = $this->resolveAll($userId, $unionId);
|
||||
$resolved = $this->resolveAll($userId, $unionId, $currentDepartmentIds);
|
||||
|
||||
return count($resolved) === 1 ? $resolved[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int|string> $currentDepartmentIds
|
||||
* @return list<array{supplier_name:string,supplier_code:string,dingtalk_group_id:int,dingtalk_group_name:string}>
|
||||
*/
|
||||
public function resolveAll(string $userId, string $unionId = ''): array
|
||||
public function resolveAll(string $userId, string $unionId = '', array $currentDepartmentIds = []): array
|
||||
{
|
||||
$userId = trim($userId);
|
||||
$unionId = trim($unionId);
|
||||
@ -53,6 +60,20 @@ class SupplierPortalAccess
|
||||
return [];
|
||||
}
|
||||
|
||||
$currentDepartmentIds = $this->departmentIds($currentDepartmentIds);
|
||||
if ($currentDepartmentIds !== [] && $this->dingTalk !== null) {
|
||||
try {
|
||||
$resolved = $this->resolveFromAncestors(
|
||||
$this->dingTalk->departmentLineage($currentDepartmentIds),
|
||||
);
|
||||
if ($resolved !== []) {
|
||||
return $resolved;
|
||||
}
|
||||
} catch (Throwable) {
|
||||
// Preserve the existing HR fallback when the department API is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
$query = $this->queries->forSource('operations_replica');
|
||||
$employees = $query->select(
|
||||
'SELECT TOP (2) userid, unionid, name, active, dept_id_list
|
||||
@ -73,18 +94,16 @@ class SupplierPortalAccess
|
||||
return [];
|
||||
}
|
||||
|
||||
$placeholders = implode(',', array_fill(0, count($departmentIds), '?'));
|
||||
$ancestors = $query->select(
|
||||
'WITH lineage AS (
|
||||
SELECT Id, parent_id, name, 0 AS depth FROM rpt.hr_groups WHERE Id IN ('.$placeholders.')
|
||||
UNION ALL
|
||||
SELECT parent.Id, parent.parent_id, parent.name, child.depth + 1
|
||||
FROM rpt.hr_groups parent JOIN lineage child ON parent.Id = child.parent_id
|
||||
WHERE child.depth < 20
|
||||
) SELECT TOP (256) Id, parent_id, name, depth FROM lineage',
|
||||
$departmentIds,
|
||||
);
|
||||
if ($ancestors === [] || count($ancestors) >= 256
|
||||
return $this->resolveFromAncestors($this->hrAncestors($query, $departmentIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $ancestors
|
||||
* @return list<array{supplier_name:string,supplier_code:string,dingtalk_group_id:int,dingtalk_group_name:string}>
|
||||
*/
|
||||
private function resolveFromAncestors(array $ancestors): array
|
||||
{
|
||||
if ($ancestors === [] || count($ancestors) > 256
|
||||
|| array_filter($ancestors, static fn (array $row): bool => (int) ($row['depth'] ?? 0) >= 20)) {
|
||||
return [];
|
||||
}
|
||||
@ -136,6 +155,26 @@ class SupplierPortalAccess
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $departmentIds
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function hrAncestors(UpstreamReadOnlyQuery $query, array $departmentIds): array
|
||||
{
|
||||
$placeholders = implode(',', array_fill(0, count($departmentIds), '?'));
|
||||
|
||||
return $query->select(
|
||||
'WITH lineage AS (
|
||||
SELECT Id, parent_id, name, 0 AS depth FROM rpt.hr_groups WHERE Id IN ('.$placeholders.')
|
||||
UNION ALL
|
||||
SELECT parent.Id, parent.parent_id, parent.name, child.depth + 1
|
||||
FROM rpt.hr_groups parent JOIN lineage child ON parent.Id = child.parent_id
|
||||
WHERE child.depth < 20
|
||||
) SELECT TOP (256) Id, parent_id, name, depth FROM lineage',
|
||||
$departmentIds,
|
||||
);
|
||||
}
|
||||
|
||||
public function bind(User $user, int $companyId, array $resolved): SupplierPortalIdentity
|
||||
{
|
||||
$this->bindMany($user, $companyId, [$resolved]);
|
||||
@ -260,9 +299,28 @@ class SupplierPortalAccess
|
||||
return null;
|
||||
}
|
||||
|
||||
$currentDepartmentIds = [];
|
||||
if ($this->dingTalk !== null) {
|
||||
try {
|
||||
$profile = $this->dingTalk->enterpriseUser([
|
||||
'union_id' => (string) $dingTalk->union_id,
|
||||
'open_id' => $dingTalk->open_id,
|
||||
'nickname' => $dingTalk->nickname,
|
||||
]);
|
||||
if (($profile['active'] ?? false) !== true
|
||||
|| (string) ($profile['dingtalk_user_id'] ?? '') !== (string) $dingTalk->dingtalk_user_id) {
|
||||
return null;
|
||||
}
|
||||
$currentDepartmentIds = $this->departmentIds($profile['department_ids'] ?? []);
|
||||
} catch (Throwable) {
|
||||
// HR fallback keeps existing sessions working during a DingTalk outage.
|
||||
}
|
||||
}
|
||||
|
||||
$resolved = $this->resolveAll(
|
||||
(string) $dingTalk->dingtalk_user_id,
|
||||
(string) $dingTalk->union_id,
|
||||
$currentDepartmentIds,
|
||||
);
|
||||
|
||||
if ($resolved === []) {
|
||||
@ -281,18 +339,25 @@ class SupplierPortalAccess
|
||||
|
||||
private function departmentIds(mixed $value): array
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') {
|
||||
if (is_array($value)) {
|
||||
$parts = $value;
|
||||
} else {
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') {
|
||||
return [];
|
||||
}
|
||||
$parts = json_decode($value, true);
|
||||
if (! is_array($parts)) {
|
||||
$parts = preg_split('/[\[\]\/>,,;;||\s]+/u', $value, -1, PREG_SPLIT_NO_EMPTY);
|
||||
}
|
||||
}
|
||||
if (! is_array($parts) || $parts === []) {
|
||||
return [];
|
||||
}
|
||||
$parts = json_decode($value, true);
|
||||
if (! is_array($parts)) {
|
||||
$parts = preg_split('/[\[\]\/>,,;;||\s]+/u', $value, -1, PREG_SPLIT_NO_EMPTY);
|
||||
}
|
||||
|
||||
return array_values(array_filter(array_map(
|
||||
return array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $id): string => is_scalar($id) ? trim((string) $id) : '',
|
||||
is_array($parts) ? $parts : [],
|
||||
), static fn (string $id): bool => ctype_digit($id) && (int) $id > 0));
|
||||
$parts,
|
||||
), static fn (string $id): bool => ctype_digit($id) && (int) $id > 0)));
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,6 +39,10 @@ return [
|
||||
'app_token_url' => env('DINGTALK_APP_TOKEN_URL', 'https://oapi.dingtalk.com/gettoken'),
|
||||
'user_by_union_id_url' => env('DINGTALK_USER_BY_UNION_ID_URL', 'https://oapi.dingtalk.com/topapi/user/getbyunionid'),
|
||||
'user_detail_url' => env('DINGTALK_USER_DETAIL_URL', 'https://oapi.dingtalk.com/topapi/v2/user/get'),
|
||||
'department_detail_url' => env(
|
||||
'DINGTALK_DEPARTMENT_DETAIL_URL',
|
||||
'https://oapi.dingtalk.com/topapi/v2/department/get'
|
||||
),
|
||||
'robot' => [
|
||||
// 企业内部应用机器人编码通常与应用 Client ID 相同,也允许单独覆盖。
|
||||
'code' => env('DINGTALK_ROBOT_CODE', env('DINGTALK_CLIENT_ID')),
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
供应商人员与财务人员使用不同的准入来源:
|
||||
|
||||
- 财务人员继续按 `hr_flowerName_book`、任职登记和财务部门范围核验。
|
||||
- 供应商人员按当前有效的 `hr_employee` 企业成员、`hr_employee.dept_id_list` 与 `hr_groups` 祖先组织核验,不要求进入财务花名册。
|
||||
- 供应商人员优先按钉钉应用返回的当前有效企业成员及其 `dept_id_list`,通过钉钉部门接口实时核对部门祖先;HR `hr_employee` 与 `hr_groups` 保留为兼容回退,不要求进入财务花名册。这样供应商成员不必等待 HR 副本同步。
|
||||
- 部门祖先名称必须与共享供应商主档中的供应商名称精确匹配且唯一;同名多供应商、同一员工命中多个供应商或组织循环时拒绝登录。
|
||||
- 首次登录自动创建 `dingtalk_supplier_portal` 普通账号,并写入 `supplier_portal_identities`。不创建财务角色、不创建供应商联系人、不授予财务页面权限。
|
||||
- 供应商账号只允许“供应商对账 → 厂家端数据”及其模板、上传、确认、异议和导出接口。服务端始终覆盖请求中的供应商参数,并校验退货明细属于绑定供应商。
|
||||
|
||||
@ -40,6 +40,7 @@ class DingTalkLoginTest extends FeatureTestCase
|
||||
'dingtalk.app_token_url' => 'https://oapi.dingtalk.test/gettoken',
|
||||
'dingtalk.user_by_union_id_url' => 'https://oapi.dingtalk.test/topapi/user/getbyunionid',
|
||||
'dingtalk.user_detail_url' => 'https://oapi.dingtalk.test/topapi/v2/user/get',
|
||||
'dingtalk.department_detail_url' => 'https://oapi.dingtalk.test/topapi/v2/department/get',
|
||||
'dingtalk.limited_login_user_ids' => [],
|
||||
]);
|
||||
app('url')->forceRootUrl(config('app.url'));
|
||||
@ -148,6 +149,41 @@ class DingTalkLoginTest extends FeatureTestCase
|
||||
Http::assertSentCount(3);
|
||||
}
|
||||
|
||||
public function test_department_lineage_uses_current_dingtalk_organization(): void
|
||||
{
|
||||
Cache::flush();
|
||||
Http::fake(function (ClientRequest $request) {
|
||||
$url = $request->url();
|
||||
if (Str::startsWith($url, 'https://oapi.dingtalk.test/gettoken?')) {
|
||||
return Http::response([
|
||||
'errcode' => 0,
|
||||
'access_token' => 'app-access-token-not-persisted',
|
||||
]);
|
||||
}
|
||||
if (Str::startsWith($url, 'https://oapi.dingtalk.test/topapi/v2/department/get?')) {
|
||||
return match ((int) $request['dept_id']) {
|
||||
55248182 => Http::response([
|
||||
'errcode' => 0,
|
||||
'result' => ['dept_id' => 55248182, 'parent_id' => 900, 'name' => '雅梵家具'],
|
||||
]),
|
||||
900 => Http::response([
|
||||
'errcode' => 0,
|
||||
'result' => ['dept_id' => 900, 'parent_id' => 1, 'name' => '供应商'],
|
||||
]),
|
||||
default => Http::response([], 404),
|
||||
};
|
||||
}
|
||||
|
||||
return Http::response([], 404);
|
||||
});
|
||||
|
||||
$lineage = app(DingTalkOAuthClient::class)->departmentLineage(['55248182']);
|
||||
|
||||
$this->assertSame(['雅梵家具', '供应商'], array_column($lineage, 'name'));
|
||||
$this->assertSame([0, 1], array_column($lineage, 'depth'));
|
||||
Http::assertSentCount(3);
|
||||
}
|
||||
|
||||
public function test_bound_active_enterprise_identity_logs_in_without_storing_access_tokens(): void
|
||||
{
|
||||
Http::preventStrayRequests();
|
||||
@ -419,7 +455,7 @@ class DingTalkLoginTest extends FeatureTestCase
|
||||
$supplierAccess = $this->mock(SupplierPortalAccess::class);
|
||||
$supplierAccess->shouldReceive('resolveAll')
|
||||
->once()
|
||||
->with('ding-user-1', 'union-supplier')
|
||||
->with('ding-user-1', 'union-supplier', ['902833372'])
|
||||
->andReturn([
|
||||
[
|
||||
'supplier_name' => '晨丰',
|
||||
@ -462,7 +498,11 @@ class DingTalkLoginTest extends FeatureTestCase
|
||||
});
|
||||
|
||||
Http::preventStrayRequests();
|
||||
Http::fake($this->dingtalkResponses('union-supplier', 'open-supplier'));
|
||||
Http::fake($this->dingtalkResponses(
|
||||
'union-supplier',
|
||||
'open-supplier',
|
||||
departmentIds: ['902833372'],
|
||||
));
|
||||
$state = $this->startAuthorization();
|
||||
$this->get(route('login.dingtalk.callback', ['code' => 'fake-code', 'state' => $state]))
|
||||
->assertRedirect(route('business.supplier-portal.home', ['company_id' => $this->company->id]));
|
||||
@ -915,9 +955,10 @@ class DingTalkLoginTest extends FeatureTestCase
|
||||
?string $email = 'finance@example.test',
|
||||
?string $mobile = null,
|
||||
bool $active = true,
|
||||
bool $enterpriseMember = true
|
||||
bool $enterpriseMember = true,
|
||||
array $departmentIds = ['ding-user-department']
|
||||
): callable {
|
||||
return function (ClientRequest $request) use ($unionId, $openId, $email, $mobile, $active, $enterpriseMember) {
|
||||
return function (ClientRequest $request) use ($unionId, $openId, $email, $mobile, $active, $enterpriseMember, $departmentIds) {
|
||||
$url = $request->url();
|
||||
|
||||
return match (true) {
|
||||
@ -946,6 +987,7 @@ class DingTalkLoginTest extends FeatureTestCase
|
||||
'email' => $email,
|
||||
'mobile' => $mobile,
|
||||
'active' => $active,
|
||||
'dept_id_list' => $departmentIds,
|
||||
],
|
||||
]),
|
||||
default => Http::response([], 404),
|
||||
|
||||
@ -2,8 +2,11 @@
|
||||
|
||||
namespace Tests\Unit\Auth;
|
||||
|
||||
use App\Models\Auth\DingTalkIdentity;
|
||||
use App\Models\Auth\SupplierPortalIdentity;
|
||||
use App\Models\Auth\SupplierPortalSupplier;
|
||||
use App\Models\Common\Company;
|
||||
use App\Services\Auth\DingTalkOAuthClient;
|
||||
use App\Services\Auth\SupplierPortalAccess;
|
||||
use Mockery;
|
||||
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
|
||||
@ -164,4 +167,97 @@ class SupplierPortalAccessTest extends TestCase
|
||||
'supplier_name' => '鸣飞家具',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_current_dingtalk_departments_resolve_when_hr_employee_is_missing(): void
|
||||
{
|
||||
$factory = Mockery::mock(UpstreamReadOnlyQueryFactory::class);
|
||||
$factory->shouldNotReceive('forSource');
|
||||
$suppliers = Mockery::mock(SupplierManagementMirrorRepository::class);
|
||||
$suppliers->shouldReceive('suppliersByNames')->once()
|
||||
->with(['雅梵家具', '供应商'])
|
||||
->andReturn([(object) [
|
||||
'Id' => 121,
|
||||
'scmcode' => 'YF-001',
|
||||
'scmname' => '雅梵家具',
|
||||
]]);
|
||||
$dingTalk = Mockery::mock(DingTalkOAuthClient::class);
|
||||
$dingTalk->shouldReceive('departmentLineage')->once()
|
||||
->with(['55248182'])
|
||||
->andReturn([
|
||||
['Id' => 55248182, 'parent_id' => 900, 'name' => '雅梵家具', 'depth' => 0],
|
||||
['Id' => 900, 'parent_id' => 1, 'name' => '供应商', 'depth' => 1],
|
||||
]);
|
||||
|
||||
$resolved = (new SupplierPortalAccess($factory, $suppliers, $dingTalk))
|
||||
->resolve('ding-supplier', 'union-supplier', ['55248182']);
|
||||
|
||||
$this->assertSame('雅梵家具', $resolved['supplier_name']);
|
||||
$this->assertSame('YF-001', $resolved['supplier_code']);
|
||||
$this->assertSame(55248182, $resolved['dingtalk_group_id']);
|
||||
}
|
||||
|
||||
public function test_dingtalk_department_outage_falls_back_to_hr_access(): void
|
||||
{
|
||||
$query = Mockery::mock(UpstreamReadOnlyQuery::class);
|
||||
$query->shouldReceive('select')->twice()->andReturnUsing(function (string $sql): array {
|
||||
if (str_contains($sql, 'hr_employee')) {
|
||||
return [['userid' => 'ding-supplier', 'unionid' => 'union-supplier', 'active' => 1, 'dept_id_list' => '55248182']];
|
||||
}
|
||||
|
||||
return [['Id' => 55248182, 'parent_id' => 900, 'name' => '晨丰', 'depth' => 0]];
|
||||
});
|
||||
$factory = Mockery::mock(UpstreamReadOnlyQueryFactory::class);
|
||||
$factory->shouldReceive('forSource')->once()->andReturn($query);
|
||||
$suppliers = Mockery::mock(SupplierManagementMirrorRepository::class);
|
||||
$suppliers->shouldReceive('suppliersByNames')->once()
|
||||
->with(['晨丰'])
|
||||
->andReturn([(object) ['Id' => 9, 'scmcode' => 'CF-001', 'scmname' => '晨丰']]);
|
||||
$dingTalk = Mockery::mock(DingTalkOAuthClient::class);
|
||||
$dingTalk->shouldReceive('departmentLineage')->once()
|
||||
->andThrow(new \RuntimeException('department outage'));
|
||||
|
||||
$resolved = (new SupplierPortalAccess($factory, $suppliers, $dingTalk))
|
||||
->resolve('ding-supplier', 'union-supplier', ['55248182']);
|
||||
|
||||
$this->assertSame('晨丰', $resolved['supplier_name']);
|
||||
}
|
||||
|
||||
public function test_supplier_session_revalidation_uses_current_dingtalk_departments(): void
|
||||
{
|
||||
$user = user_model_class()::query()->firstOrFail();
|
||||
$user->forceFill(['created_from' => SupplierPortalAccess::CREATED_FROM])->save();
|
||||
$company = $user->companies()->enabled()->firstOrFail();
|
||||
app()->instance(Company::class, $company);
|
||||
DingTalkIdentity::create([
|
||||
'user_id' => $user->id,
|
||||
'union_id' => 'union-supplier',
|
||||
'dingtalk_user_id' => 'ding-supplier',
|
||||
]);
|
||||
|
||||
$factory = Mockery::mock(UpstreamReadOnlyQueryFactory::class);
|
||||
$factory->shouldNotReceive('forSource');
|
||||
$suppliers = Mockery::mock(SupplierManagementMirrorRepository::class);
|
||||
$suppliers->shouldReceive('suppliersByNames')->once()
|
||||
->andReturn([(object) ['Id' => 9, 'scmcode' => 'CF-001', 'scmname' => '晨丰']]);
|
||||
$dingTalk = Mockery::mock(DingTalkOAuthClient::class);
|
||||
$dingTalk->shouldReceive('enterpriseUser')->once()
|
||||
->andReturn([
|
||||
'dingtalk_user_id' => 'ding-supplier',
|
||||
'active' => true,
|
||||
'department_ids' => ['55248182'],
|
||||
]);
|
||||
$dingTalk->shouldReceive('departmentLineage')->once()
|
||||
->with(['55248182'])
|
||||
->andReturn([['Id' => 55248182, 'parent_id' => 900, 'name' => '晨丰', 'depth' => 0]]);
|
||||
|
||||
$mapping = (new SupplierPortalAccess($factory, $suppliers, $dingTalk))->revalidate($user);
|
||||
|
||||
$this->assertNotNull($mapping);
|
||||
$this->assertDatabaseHas('supplier_portal_suppliers', [
|
||||
'company_id' => $company->id,
|
||||
'user_id' => $user->id,
|
||||
'supplier_name' => '晨丰',
|
||||
'supplier_code' => 'CF-001',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user