TeamMemberBatchExcelHelper.cs 14.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
using System.Globalization;
using ClosedXML.Excel;
using FoodLabeling.Application.Contracts.Dtos.TeamMember;

namespace FoodLabeling.Application.Helpers;

/// <summary>
/// Team Member 批量导入 Excel(列名与 Account Management 表格对齐,兼容常见别名)
/// </summary>
public static class TeamMemberBatchExcelHelper
{
    /// <summary>导入/下载模板表头(与 PDF 导出 Region 列对齐)</summary>
    public static readonly string[] ImportTemplateHeaders =
    {
        "Name",
        "User Name",
        "Password",
        "Email",
        "Phone",
        "Role Id",
        "Role Name",
        "Region",
        "Assigned Location Ids",
        "Status"
    };

    /// <summary>生成批量导入模板 xlsx(含 Region 可选列说明行)</summary>
    public static MemoryStream BuildImportTemplateWorkbook()
    {
        var ms = new MemoryStream();
        using var wb = new XLWorkbook();
        var ws = wb.AddWorksheet("TeamMembers");
        for (var i = 0; i < ImportTemplateHeaders.Length; i++)
        {
            ws.Cell(1, i + 1).Value = ImportTemplateHeaders[i];
            ws.Cell(1, i + 1).Style.Font.Bold = true;
        }

        ws.Cell(2, 1).Value = "John Doe";
        ws.Cell(2, 2).Value = "john.doe";
        ws.Cell(2, 3).Value = "ChangeMe123!";
        ws.Cell(2, 4).Value = "john@example.com";
        ws.Cell(2, 5).Value = "789654444";
        ws.Cell(2, 6).Value = "";
        ws.Cell(2, 7).Value = "Staff";
        ws.Cell(2, 8).Value = "";
        ws.Cell(2, 9).Value = "LOC001;LOC002";
        ws.Cell(2, 10).Value = "TRUE";

        ws.Cell(3, 7).Value = "(Role Name 与系统角色名一致;Company Admin 可只填 Region 或留空由 Company 规则处理)";
        ws.Cell(4, 8).Value = "(可选)Region 名称或 fl_group.Id,多个用 ; 分隔";
        ws.Cell(5, 9).Value = "(可选)门店 LocationCode 或 location.Id(Guid),多个用 ; 分隔;与 Region 至少填一项";

        ws.Columns().AdjustToContents();
        wb.SaveAs(ms);
        ms.Position = 0;
        return ms;
    }

    /// <summary>
    /// 从上传的 Excel 解析为创建入参列表(行号从 2 起为数据行)。
    /// </summary>
    /// <param name="stream">xlsx 流</param>
    /// <param name="maxRows">最多数据行</param>
    /// <param name="roleNameToId">角色名(忽略大小写、去空白)到角色 Id</param>
    /// <param name="defaultPassword">未填 Password 列时使用</param>
    /// <param name="parseErrors">表头或解析错误</param>
    public static List<(int RowNumber, TeamMemberCreateInputVo Input)> ParseImportWorkbook(
        Stream stream,
        int maxRows,
        IReadOnlyDictionary<string, Guid> roleNameToId,
        string defaultPassword,
        out List<TeamMemberBatchImportErrorDto> parseErrors)
    {
        parseErrors = new List<TeamMemberBatchImportErrorDto>();
        var result = new List<(int, TeamMemberCreateInputVo)>();

        if (string.IsNullOrWhiteSpace(defaultPassword))
        {
            parseErrors.Add(new TeamMemberBatchImportErrorDto
            {
                RowNumber = 0,
                Message = "未配置默认导入密码 FoodLabeling:BatchImport:TeamMemberImportDefaultPassword"
            });
            return result;
        }

        using var wb = new XLWorkbook(stream);
        var ws = wb.Worksheets.FirstOrDefault();
        if (ws is null)
        {
            parseErrors.Add(new TeamMemberBatchImportErrorDto { RowNumber = 0, Message = "Excel 中无工作表" });
            return result;
        }

        var headerRow = ws.Row(1);
        if (!headerRow.CellsUsed().Any())
        {
            parseErrors.Add(new TeamMemberBatchImportErrorDto { RowNumber = 1, Message = "表头为空" });
            return result;
        }

        var colMap = BuildHeaderColumnMap(headerRow);
        if (!colMap.ContainsKey("fullname") || !colMap.ContainsKey("email"))
        {
            parseErrors.Add(new TeamMemberBatchImportErrorDto
            {
                RowNumber = 1,
                Message = "未找到「Name」与「Email」列(或同义表头),请使用官方模板"
            });
            return result;
        }

        var lastRow = ws.LastRowUsed()?.RowNumber() ?? 1;
        var dataRowCount = 0;
        for (var rowNum = 2; rowNum <= lastRow; rowNum++)
        {
            if (dataRowCount >= maxRows)
            {
                parseErrors.Add(new TeamMemberBatchImportErrorDto
                {
                    RowNumber = rowNum,
                    Message = $"已超过单次导入上限 {maxRows} 行,后续行已忽略"
                });
                break;
            }

            var fullName = GetCellByField(colMap, ws, rowNum, "fullname");
            var email = GetCellByField(colMap, ws, rowNum, "email");
            if (string.IsNullOrWhiteSpace(fullName) && string.IsNullOrWhiteSpace(email) && IsRowEmpty(colMap, ws, rowNum))
            {
                continue;
            }

            dataRowCount++;
            var errPrefix = $"第 {rowNum} 行";
            try
            {
                var input = BuildCreateInputFromRow(
                    colMap,
                    ws,
                    rowNum,
                    roleNameToId,
                    defaultPassword,
                    out var rowErrs,
                    out var userNameHint);
                if (rowErrs.Count > 0)
                {
                    foreach (var e in rowErrs)
                    {
                        parseErrors.Add(new TeamMemberBatchImportErrorDto
                        {
                            RowNumber = rowNum,
                            UserName = userNameHint,
                            Message = $"{errPrefix}:{e}"
                        });
                    }

                    continue;
                }

                result.Add((rowNum, input!));
            }
            catch (Exception ex)
            {
                parseErrors.Add(new TeamMemberBatchImportErrorDto
                {
                    RowNumber = rowNum,
                    Message = $"{errPrefix}:{ex.Message}"
                });
            }
        }

        return result;
    }

    private static Dictionary<string, int> BuildHeaderColumnMap(IXLRow headerRow)
    {
        var map = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
        foreach (var cell in headerRow.CellsUsed())
        {
            var key = NormalizeHeaderKey(cell.GetString());
            if (string.IsNullOrEmpty(key))
            {
                continue;
            }

            var field = MapHeaderToField(key);
            if (field is null)
            {
                continue;
            }

            if (!map.ContainsKey(field))
            {
                map[field] = cell.Address.ColumnNumber;
            }
        }

        return map;
    }

    private static string? MapHeaderToField(string normalizedHeader)
    {
        return normalizedHeader switch
        {
            "name" or "fullname" or "姓名" or "成员姓名" => "fullname",
            "email" or "邮箱" or "e-mail" => "email",
            "username" or "login" or "userid" or "账号" or "用户名" => "username",
            "password" or "pwd" or "密码" => "password",
            "phone" or "mobile" or "电话" or "手机" => "phone",
            "role" or "rolename" or "角色" => "rolename",
            "roleid" or "角色id" => "roleid",
            "region" or "regions" or "group" or "groupname" or "groupid" or "区域" => "regions",
            "assignedlocations" or "assignedlocationids" or "locationids" or "locationcodes" or
                "locations" or "location" or "分配门店" or "门店" or "门店id" => "locations",
            "status" or "active" or "state" or "启用" => "status",
            _ => null
        };
    }

    private static string NormalizeHeaderKey(string raw)
    {
        var s = raw.Trim();
        if (s.Length > 0 && s[0] == '\uFEFF')
        {
            s = s.TrimStart('\uFEFF');
        }

        s = s.Trim().TrimStart('*');
        return string.Concat(s.Where(c => !char.IsWhiteSpace(c))).ToLowerInvariant();
    }

    private static bool IsRowEmpty(Dictionary<string, int> colMap, IXLWorksheet ws, int rowNum)
    {
        foreach (var col in colMap.Values)
        {
            var t = ws.Cell(rowNum, col).GetString().Trim();
            if (!string.IsNullOrEmpty(t))
            {
                return false;
            }
        }

        return true;
    }

    private static string GetCellByField(Dictionary<string, int> colMap, IXLWorksheet ws, int row, string field)
    {
        if (!colMap.TryGetValue(field, out var col))
        {
            return string.Empty;
        }

        return ws.Cell(row, col).GetString().Trim();
    }

    private static TeamMemberCreateInputVo? BuildCreateInputFromRow(
        Dictionary<string, int> colMap,
        IXLWorksheet ws,
        int rowNum,
        IReadOnlyDictionary<string, Guid> roleNameToId,
        string defaultPassword,
        out List<string> errors,
        out string? userNameHint)
    {
        errors = new List<string>();
        userNameHint = null;

        var fullName = GetCellByField(colMap, ws, rowNum, "fullname");
        var email = GetCellByField(colMap, ws, rowNum, "email");
        var userName = GetCellByField(colMap, ws, rowNum, "username");
        var password = GetCellByField(colMap, ws, rowNum, "password");
        var phoneStr = GetCellByField(colMap, ws, rowNum, "phone");
        var roleIdCell = GetCellByField(colMap, ws, rowNum, "roleid");
        var roleName = GetCellByField(colMap, ws, rowNum, "rolename");
        var regionsCell = GetCellByField(colMap, ws, rowNum, "regions");
        var locationsCell = GetCellByField(colMap, ws, rowNum, "locations");
        var statusStr = GetCellByField(colMap, ws, rowNum, "status");

        if (string.IsNullOrWhiteSpace(fullName))
        {
            errors.Add("Name 不能为空");
        }

        if (string.IsNullOrWhiteSpace(email))
        {
            errors.Add("Email 不能为空");
        }

        var login = string.IsNullOrWhiteSpace(userName) ? email.Trim() : userName.Trim();
        userNameHint = login;

        if (string.IsNullOrWhiteSpace(login))
        {
            errors.Add("登录账号不能为空(可填 UserName 列,否则使用 Email)");
        }

        var pwd = string.IsNullOrWhiteSpace(password) ? defaultPassword : password.Trim();
        if (string.IsNullOrWhiteSpace(pwd))
        {
            errors.Add("Password 不能为空且未配置默认密码");
        }

        long? phone = null;
        if (!string.IsNullOrWhiteSpace(phoneStr))
        {
            if (!long.TryParse(RegexDigitsOnly(phoneStr), NumberStyles.Integer, CultureInfo.InvariantCulture,
                    out var p))
            {
                errors.Add("Phone 格式不正确(需为数字)");
            }
            else
            {
                phone = p;
            }
        }

        Guid? roleIdResolved = null;
        if (Guid.TryParse(roleIdCell?.Trim(), out var roleGuid))
        {
            roleIdResolved = roleGuid;
        }
        else if (string.IsNullOrWhiteSpace(roleName))
        {
            errors.Add("Role Name 不能为空(或填写有效的 Role Id Guid)");
        }
        else if (!roleNameToId.TryGetValue(NormalizeRoleKey(roleName), out var rid))
        {
            errors.Add($"未找到角色「{roleName.Trim()}」,请与系统角色名称一致");
        }
        else
        {
            roleIdResolved = rid;
        }

        var regionTokens = SplitMultiValueTokens(regionsCell);
        var locationTokens = SplitMultiValueTokens(locationsCell);
        var isCompanyAdmin = TeamMemberRoleHelper.IsCompanyAdminRoleName(roleName);

        if (regionTokens.Count == 0 && locationTokens.Count == 0 && !isCompanyAdmin)
        {
            errors.Add("Region 与 Assigned Location Ids 至少填一项(均可留空时仅适用于 Company Admin 且已在 Web 端配置 Company)");
        }

        if (errors.Count > 0)
        {
            return null;
        }

        var state = ParseBool(statusStr, defaultValue: true);
        return new TeamMemberCreateInputVo
        {
            FullName = fullName.Trim(),
            Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim(),
            UserName = login,
            Password = pwd,
            Phone = phone,
            RoleId = roleIdResolved,
            RegionIds = regionTokens,
            LocationIds = locationTokens,
            State = state
        };
    }

    public static string NormalizeRoleKey(string roleName)
    {
        return string.Concat(roleName.Trim().Where(c => !char.IsWhiteSpace(c))).ToLowerInvariant();
    }

    /// <summary>
    /// 拆分单元格为多个 token(门店/区域等;后续由服务层解析为 Id)。
    /// </summary>
    public static List<string> SplitMultiValueTokens(string cell)
    {
        if (string.IsNullOrWhiteSpace(cell))
        {
            return new List<string>();
        }

        return cell
            .Split(new[] { ';', '|', '\n', '\r', ',' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(x => x.Trim())
            .Where(x => !string.IsNullOrEmpty(x))
            .ToList();
    }

    /// <summary>
    /// 兼容旧调用。
    /// </summary>
    public static List<string> SplitLocationTokens(string locationsCell) => SplitMultiValueTokens(locationsCell);

    private static string RegexDigitsOnly(string s)
    {
        return new string(s.Where(char.IsDigit).ToArray());
    }

    private static bool ParseBool(string? raw, bool defaultValue)
    {
        if (string.IsNullOrWhiteSpace(raw))
        {
            return defaultValue;
        }

        var s = raw.Trim();
        if (bool.TryParse(s, out var b))
        {
            return b;
        }

        if (int.TryParse(s, out var n))
        {
            return n != 0;
        }

        if (string.Equals(s, "active", StringComparison.OrdinalIgnoreCase) ||
            string.Equals(s, "是", StringComparison.Ordinal) ||
            string.Equals(s, "Y", StringComparison.OrdinalIgnoreCase) ||
            string.Equals(s, "Yes", StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        if (string.Equals(s, "inactive", StringComparison.OrdinalIgnoreCase) ||
            string.Equals(s, "否", StringComparison.Ordinal) ||
            string.Equals(s, "N", StringComparison.OrdinalIgnoreCase) ||
            string.Equals(s, "No", StringComparison.OrdinalIgnoreCase))
        {
            return false;
        }

        return defaultValue;
    }
}