سلام و عرض ادب خدمت استاد گرامی و دوستان عزیزم
من بخش افزودن محصول رو با کمک هوش مصنوعی طراحی و پیادهسازی کردم و تصاویرش رو در ادامه قرار میدم.
از اونجایی که سعی کردم طراحی این بخش کاربرپسند باشه و فرایند ثبت محصول رو سادهتر کنه، گفتم اون رو با دوستان به اشتراک بذارم تا اگر کسی تمایل داشت، بتونه ازش ایده بگیره یا در پروژه خودش استفاده کنه.
البته در پیادهسازی این بخش از JavaScript هم استفاده شده؛ بنابراین دوستانی که تسلط کافی به JavaScript ندارند، میتونند طبق روشی که استاد گرامی آموزش دادند، کارشون رو پیش ببرند.
امیدوارم براتون مفید باشه.




ویرایش و حذف رو توی یک صفحه انجام دادم که صفحات بیشتری نداشته باشیم. یک view به اسم CreateEdit ایجاد کردم و همه تب ها رو توی اون قرار دادم البته که میتونین هر کدوم از صفحات رو به صورت Partial طراحی کنین.
1. کدهای صفحه CreateEdit
@using Domain.ViewModels.Product
@using System.Text.Json
@model AdminCreateProductViewModel
@{
ViewData["Title"] = Model.IsNew ? "افزودن محصول" : "ویرایش محصول";
var editorConfig = new
{
productId = Model.ProductId ?? 0,
categoryTree = Model.CategoryTree,
selectedCategoryId = Model.CategoryId,
colors = Model.AllColors,
selectedTags = Model.SelectedTags,
urls = new
{
index = Url.Action("Index", "Products", new { area = "Admin" }),
getTags = Url.Action("GetTags", "Products", new { area = "Admin" }),
saveBasicInfo = Url.Action("SaveBasicInfo", "Products", new { area = "Admin" }),
createColor = Url.Action("CreateColor", "Products", new { area = "Admin" }),
addColor = Url.Action("AddColor", "Products", new { area = "Admin" }),
removeColor = Url.Action("RemoveColor", "Products", new { area = "Admin" }),
addGallery = Url.Action("AddGallery", "Products", new { area = "Admin" }),
removeGallery = Url.Action("RemoveGallery", "Products", new { area = "Admin" }),
addFeature = Url.Action("AddFeature", "Products", new { area = "Admin" }),
removeFeature = Url.Action("RemoveFeature", "Products", new { area = "Admin" }),
createTag = Url.Action("CreateTag", "Products", new { area = "Admin" })
}
};
var editorConfigJson = JsonSerializer.Serialize(
editorConfig,
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
var productImage = string.IsNullOrWhiteSpace(Model.ImageName)
? Url.Content("~/Uploads/UserProfile/NoPhoto.jpg")
: Url.Content("~/Uploads/Products/" + Model.ImageName);
}
<link rel="stylesheet" href="~/Admin/css/product-editor.css" asp-append-version="true" />
<div class="product-page" dir="rtl">
<div class="page-heading">
<div>
<div class="eyebrow">مدیریت فروشگاه / محصولات</div>
<h1 class="page-title">@(Model.IsNew ? "افزودن محصول جدید" : "ویرایش محصول")</h1>
<p class="page-subtitle">اطلاعات محصول، تنوع رنگ، تصاویر و ویژگیها را یکجا مدیریت کنید.</p>
</div>
<div class="heading-actions">
<a asp-area="Admin" asp-controller="Products" asp-action="Index" class="btn soft-btn">
<i class="bx bx-arrow-back me-1"></i>
بازگشت به محصولات
</a>
<button type="button" id="btnTopSave" class="btn btn-primary">
<i class="bx bx-save me-1"></i>
ذخیره اطلاعات پایه
</button>
</div>
</div>
<div class="hero-card">
<div class="hero-product">
<div class="hero-product-icon"><i class="bx bx-package"></i></div>
<div>
<p class="hero-product-title" id="heroProductTitle">
@(Model.IsNew ? "محصول هنوز ذخیره نشده است" : Model.Title)
</p>
<p class="hero-product-meta" id="heroProductMeta">
@(Model.IsNew ? "برای فعال شدن بخشهای دیگر، ابتدا اطلاعات پایه را ذخیره کنید." : "ویرایش محصول ثبتشده")
</p>
</div>
</div>
<span id="productStatusPill" class="status-pill @(Model.IsNew ? "is-draft" : "")">
@(Model.IsNew ? "پیشنویس" : "فعال")
</span>
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-icon"><i class="bx bx-palette"></i></div>
<div>
<p class="stat-label">تنوع رنگ</p>
<p class="stat-value" id="colorsCount">@Model.Colors.Count</p>
</div>
</div>
<div class="stat-card">
<div class="stat-icon"><i class="bx bx-images"></i></div>
<div>
<p class="stat-label">تصاویر گالری</p>
<p class="stat-value" id="galleryCount">@Model.Gallery.Count</p>
</div>
</div>
<div class="stat-card">
<div class="stat-icon"><i class="bx bx-list-ul"></i></div>
<div>
<p class="stat-label">ویژگیها</p>
<p class="stat-value" id="featuresCount">@Model.Features.Count</p>
</div>
</div>
<div class="stat-card">
<div class="stat-icon"><i class="bx bx-purchase-tag-alt"></i></div>
<div>
<p class="stat-label">قیمت پایه</p>
<p class="stat-value" id="basePricePreview">@Model.Price.ToString("N0") تومان</p>
</div>
</div>
</div>
<form id="productAntiForgery">@Html.AntiForgeryToken()</form>
<input type="hidden" id="productId" value="@(Model.ProductId ?? 0)" />
<div id="globalProductAlert" class="product-alert" role="alert"></div>
@if (Model.IsNew)
{
<div id="newProductHint" class="alert alert-info d-flex align-items-center gap-2 mb-3">
<i class="bx bx-info-circle fs-5"></i>
<span>ابتدا اطلاعات پایه را ذخیره کنید؛ سپس تبهای رنگ، گالری و ویژگی برای شما فعال میشوند.</span>
</div>
}
<div class="editor-card">
<div class="product-tabs" role="tablist">
<button type="button" class="product-tab active" data-tab-target="tab-basic">
<span class="tab-number">۱</span>
اطلاعات پایه
</button>
<button type="button" class="product-tab" data-tab-target="tab-colors" @(Model.IsNew ? "disabled" : "")>
<span class="tab-number">۲</span>
رنگها
</button>
<button type="button" class="product-tab" data-tab-target="tab-gallery" @(Model.IsNew ? "disabled" : "")>
<span class="tab-number">۳</span>
گالری تصاویر
</button>
<button type="button" class="product-tab" data-tab-target="tab-features" @(Model.IsNew ? "disabled" : "")>
<span class="tab-number">۴</span>
ویژگیها
</button>
</div>
<section id="tab-basic" class="tab-pane active" role="tabpanel">
<div class="section-intro">
<div>
<h2 class="section-title">مشخصات اصلی محصول</h2>
<p class="section-description">عنوان، دستهبندی، قیمت، وضعیت و توضیحات محصول را وارد کنید.</p>
</div>
<span class="badge bg-label-primary">مرحله ۱ از ۴</span>
</div>
<div id="basicInfoAlert" class="product-alert" role="alert"></div>
@* <div asp-validation-summary="ModelOnly" class="product-alert" role="alert"></div> *@
<div class="row g-4">
<div class="col-lg-8">
<div class="row g-3">
<div class="col-12">
<label class="form-label" for="Title">نام محصول <span class="text-danger">*</span></label>
<input id="Title" class="form-control" value="@Model.Title" placeholder="مثلا: ساعت هوشمند سامسونگ" />
</div>
<div class="col-md-6">
<label class="form-label" for="Price">قیمت پایه <span class="text-danger">*</span></label>
<div class="input-group">
<input id="Price" type="number" min="1" class="form-control" value="@(Model.Price > 0 ? Model.Price.ToString(System.Globalization.CultureInfo.InvariantCulture) : "")" placeholder="۰" />
<span class="input-group-text">تومان</span>
</div>
</div>
<div class="col-md-6">
<label class="form-label" for="Count">موجودی اولیه</label>
<input id="Count" type="number" min="0" class="form-control" value="@Model.Count" placeholder="۰" />
</div>
<div class="col-12">
<label class="form-label">دستهبندی محصول <span class="text-danger">*</span></label>
<div id="categoryContainer"></div>
<input type="hidden" id="CategoryId" value="@Model.CategoryId" />
<div class="field-hint">آخرین سطح انتخابشده بهعنوان دستهبندی محصول ثبت میشود.</div>
</div>
<div class="col-12">
<div class="d-flex align-items-center justify-content-between mb-2">
<label class="form-label mb-0">برچسبها</label>
</div>
<div>
<input id="TagifyCustomInlineSuggestion" class="form-control" autocomplete="off" placeholder="برچسب را بنویسید و با Enter اضافه کنید..." />
</div>
<div class="field-hint">برچسبهای موجود را انتخاب کنید یا با دکمه بالا مورد جدید بسازید.</div>
</div>
<div class="col-12">
<label class="form-label" for="ShortDiscription">توضیح کوتاه</label>
<textarea id="ShortDiscription" class="form-control" placeholder="یک معرفی کوتاه و کاربردی برای کارت محصول...">@Model.ShortDiscription</textarea>
</div>
<div class="col-md-6">
<label class="form-label" for="Review">نقد و بررسی</label>
<textarea id="Review" class="form-control" placeholder="نکات مهم و تجربه استفاده از محصول...">@Model.Review</textarea>
</div>
<div class="col-md-6">
<label class="form-label" for="DetailReview">بررسی تخصصی</label>
<textarea id="DetailReview" class="form-control" placeholder="مشخصات فنی و توضیحات کامل...">@Model.DetailReview</textarea>
</div>
<div class="col-12">
<div class="switch-line">
<div>
<div class="form-check">
<input id="IsActive" class="form-check-input" type="checkbox" @(Model.IsActive ? "checked" : "") />
<label class="form-check-label" for="IsActive">نمایش محصول در فروشگاه</label>
</div>
<div class="field-hint mb-0 me-4">در صورت غیرفعال بودن، محصول در سایت نمایش داده نمیشود.</div>
</div>
<i class="bx bx-show-alt text-primary fs-4"></i>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="image-uploader">
<label class="form-label">تصویر اصلی محصول</label>
<div class="image-preview">
<img id="productImagePreview" src="@productImage" alt="پیشنمایش تصویر محصول" />
</div>
<label class="upload-label" for="ImageFile">
<i class="bx bx-cloud-upload"></i>
انتخاب تصویر اصلی
<input id="ImageFile" type="file" accept="image/jpeg,image/png,image/webp,image/gif" />
</label>
<div class="field-hint">فرمتهای مجاز: JPG، PNG، WEBP و GIF</div>
</div>
</div>
</div>
</section>
<section id="tab-colors" class="tab-pane" role="tabpanel">
<div class="section-intro">
<div>
<h2 class="section-title">تنوع رنگ و موجودی</h2>
<p class="section-description">رنگ را از لیست انتخاب کنید یا همانجا رنگ جدید بسازید.</p>
</div>
<span class="badge bg-label-primary">مرحله ۲ از ۴</span>
</div>
<div id="colorsAlert" class="product-alert" role="alert"></div>
<div class="card border-0 bg-light-subtle mb-4">
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-xl-5">
<div class="d-flex align-items-center justify-content-between mb-2">
<label class="form-label mb-0" for="colorSelect">رنگ محصول</label>
<button type="button" class="inline-action" data-modal-open="createColorModal">
<i class="bx bx-plus-circle"></i>
رنگ جدید
</button>
</div>
<div class="input-group">
<span id="selectedColorSwatch" class="input-group-text bg-white">
<span class="color-swatch" style="background-color:#64748b"></span>
</span>
<select id="colorSelect" class="form-select">
<option value="">انتخاب رنگ از لیست</option>
@foreach (var color in Model.AllColors)
{
<option value="@color.Id" data-code="@color.Code">@color.Name</option>
}
</select>
</div>
</div>
<div class="col-md-4 col-xl-3">
<label class="form-label" for="colorPrice">قیمت این رنگ</label>
<div class="input-group">
<input id="colorPrice" type="number" min="0" class="form-control" placeholder="اختیاری" />
<span class="input-group-text">تومان</span>
</div>
</div>
<div class="col-md-4 col-xl-2">
<label class="form-label" for="colorQuantity">موجودی</label>
<input id="colorQuantity" type="number" min="0" class="form-control" value="0" />
</div>
<div class="col-md-4 col-xl-2">
<div class="switch-line mb-0">
<div class="form-check">
<input id="colorIsDefault" class="form-check-input" type="checkbox" />
<label class="form-check-label" for="colorIsDefault">پیشفرض</label>
</div>
</div>
</div>
<div class="col-12 d-flex justify-content-end">
<button type="button" id="btnAddColor" class="btn btn-primary">
<i class="bx bx-plus me-1"></i>
افزودن تنوع رنگ
</button>
</div>
</div>
</div>
</div>
<div class="table-wrap">
<table class="table" id="colorsTable">
<thead>
<tr>
<th>رنگ</th>
<th>قیمت اختصاصی</th>
<th>موجودی</th>
<th>وضعیت</th>
<th class="text-end">عملیات</th>
</tr>
</thead>
<tbody id="colorsBody">
@if (Model.Colors.Count == 0)
{
<tr id="colorsEmptyRow">
<td colspan="5" class="empty-state">
<i class="bx bx-palette"></i>
هنوز تنوع رنگی برای این محصول ثبت نشده است.
</td>
</tr>
}
@foreach (var color in Model.Colors)
{
<tr data-id="@color.Id" data-default="@color.IsDefault.ToString().ToLowerInvariant()">
<td>
<span class="color-name">
<span class="color-swatch" style="background-color:@color.ColorCode"></span>
@color.ColorName
</span>
</td>
<td class="muted-cell">@(color.Price > 0 ? color.Price.ToString("N0") + " تومان" : "قیمت پایه")</td>
<td>@color.Quantity.ToString("N0")</td>
<td>
<span class="badge @(color.IsDefault ? "bg-label-success" : "bg-label-secondary")">
@(color.IsDefault ? "رنگ پیشفرض" : "فعال")
</span>
</td>
<td class="text-end">
<button type="button" class="danger-btn js-remove-color" data-id="@color.Id">
<i class="bx bx-trash"></i>
حذف
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</section>
<section id="tab-gallery" class="tab-pane" role="tabpanel">
<div class="section-intro">
<div>
<h2 class="section-title">گالری تصاویر</h2>
<p class="section-description">چند تصویر انتخاب کنید، پیشنمایش را ببینید و همه را به گالری محصول اضافه کنید.</p>
</div>
<span class="badge bg-label-primary">مرحله ۳ از ۴</span>
</div>
<div id="galleryAlert" class="product-alert" role="alert"></div>
<div class="gallery-dropzone">
<div class="gallery-dropzone-icon"><i class="bx bx-images"></i></div>
<div class="gallery-dropzone-copy">
<strong>تصاویر گالری را انتخاب کنید</strong>
<span>امکان انتخاب همزمان چند تصویر وجود دارد.</span>
</div>
<label class="btn btn-outline-primary mb-0" for="galleryFiles">
انتخاب تصاویر
<input id="galleryFiles" type="file" accept="image/jpeg,image/png,image/webp,image/gif" multiple hidden />
</label>
</div>
<div class="row g-3 align-items-end mt-1">
<div class="col-md-8">
<label class="form-label" for="galleryAlt">متن جایگزین تصاویر</label>
<input id="galleryAlt" class="form-control" placeholder="مثلا: نمای روبهروی محصول" />
</div>
<div class="col-md-4">
<button type="button" id="btnAddGallery" class="btn btn-primary w-100">
<i class="bx bx-upload me-1"></i>
افزودن تصاویر انتخابشده
</button>
</div>
</div>
<div id="pendingGallery" class="gallery-grid"></div>
<div id="galleryGrid" class="gallery-grid">
@if (Model.Gallery.Count == 0)
{
<div id="galleryEmptyState" class="empty-state border rounded-3 w-100" style="grid-column:1/-1;">
<i class="bx bx-image-alt"></i>
هنوز تصویری به گالری اضافه نشده است.
</div>
}
@foreach (var image in Model.Gallery)
{
<div class="gallery-card" data-id="@image.Id">
<img src="/Uploads/Products/@image.ImageName" alt="@image.Alt" />
<div class="gallery-card-body">
<small title="@image.Alt">@image.Alt</small>
<button type="button" class="danger-btn js-remove-gallery" data-id="@image.Id">
<i class="bx bx-trash"></i>
حذف تصویر
</button>
</div>
</div>
}
</div>
</section>
<section id="tab-features" class="tab-pane" role="tabpanel">
<div class="section-intro">
<div>
<h2 class="section-title">ویژگیهای محصول</h2>
<p class="section-description">مشخصات کلیدی محصول را بهصورت نام و مقدار اضافه کنید.</p>
</div>
<span class="badge bg-label-primary">مرحله ۴ از ۴</span>
</div>
<div id="featuresAlert" class="product-alert" role="alert"></div>
<div class="card border-0 bg-light-subtle mb-4">
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-md-5">
<label class="form-label" for="featureName">نام ویژگی</label>
<input id="featureName" class="form-control" placeholder="مثلا: جنس بدنه" />
</div>
<div class="col-md-5">
<label class="form-label" for="featureValue">مقدار ویژگی</label>
<input id="featureValue" class="form-control" placeholder="مثلا: آلومینیوم" />
</div>
<div class="col-md-2">
<button type="button" id="btnAddFeature" class="btn btn-primary w-100">
<i class="bx bx-plus me-1"></i>
افزودن
</button>
</div>
</div>
</div>
</div>
<div class="table-wrap">
<table class="table" id="featuresTable">
<thead>
<tr>
<th>نام ویژگی</th>
<th>مقدار</th>
<th class="text-end">عملیات</th>
</tr>
</thead>
<tbody id="featuresBody">
@if (Model.Features.Count == 0)
{
<tr id="featuresEmptyRow">
<td colspan="3" class="empty-state">
<i class="bx bx-list-ul"></i>
هنوز ویژگیای برای این محصول ثبت نشده است.
</td>
</tr>
}
@foreach (var feature in Model.Features)
{
<tr data-id="@feature.Id">
<td class="fw-semibold">@feature.Name</td>
<td class="muted-cell">@feature.Value</td>
<td class="text-end">
<button type="button" class="danger-btn js-remove-feature" data-id="@feature.Id">
<i class="bx bx-trash"></i>
حذف
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</section>
<div class="footer-actions">
<div class="right-actions">
<button type="button" class="btn soft-btn" id="btnPreviousTab">
<i class="bx bx-right-arrow-alt me-1"></i>
مرحله قبل
</button>
<button type="button" class="btn btn-primary" id="btnNextTab">
مرحله بعد
<i class="bx bx-left-arrow-alt ms-1"></i>
</button>
</div>
<div class="left-actions">
<a asp-area="Admin" asp-controller="Products" asp-action="Index" class="btn soft-btn">انصراف</a>
<button type="button" class="btn btn-success" id="btnFinish">
<i class="bx bx-check me-1"></i>
ذخیره نهایی
</button>
</div>
</div>
</div>
</div>
<div id="createColorModal" class="product-modal" aria-hidden="true">
<div class="product-modal-dialog">
<div class="product-modal-header">
<h3 class="product-modal-title">افزودن رنگ جدید به لیست</h3>
<button type="button" class="product-modal-close" data-modal-close aria-label="بستن">×</button>
</div>
<div class="product-modal-body">
<div id="createColorError" class="product-alert error"></div>
<div class="mb-3">
<label class="form-label" for="newColorName">نام رنگ</label>
<input id="newColorName" class="form-control" placeholder="مثلا: سبز زیتونی" />
</div>
<div>
<label class="form-label" for="newColorCode">کد رنگ</label>
<input id="newColorCode" type="color" class="form-control form-control-color" value="#64748b" />
</div>
</div>
<div class="product-modal-footer">
<button type="button" class="btn soft-btn" data-modal-close>انصراف</button>
<button type="button" id="btnSaveNewColor" class="btn btn-primary">
<i class="bx bx-save me-1"></i>
افزودن رنگ
</button>
</div>
</div>
</div>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script src="https://cdn.ckeditor.com/4.22.1/standard/ckeditor.js"></script>
<script>
window.productEditorConfig = @Html.Raw(editorConfigJson);
</script>
<script src="~/Admin/js/product-editor.js" asp-append-version="true"></script>
}
2 . کدهای ProductsController
public class ProductsController : AdminBaseController
{
private readonly ICategoryService _categoryService;
private readonly IProductService _productService;
public ProductsController(
ICategoryService categoryService,
IProductService productService)
{
_categoryService = categoryService;
_productService = productService;
}
[HttpGet]
public async Task<IActionResult> Index()
{
var model = await _productService.GetProductsAsync();
return View(model);
}
[HttpGet]
public async Task<IActionResult> CreateEdit(int? id, string? tab)
{
AdminCreateProductViewModel model;
if (id.HasValue)
{
model = await _productService.GetForEditAsync(id.Value);
if (model == null)
{
return NotFound();
}
}
else
{
model = new AdminCreateProductViewModel();
}
model.CategoryTree = await _categoryService.GetTreeAsync();
model.AllColors = await _productService.GetColorsAsync();
model.Tags = JsonSerializer.Serialize(model.SelectedTags.Select(x => new { value = x }));
ViewData["ActiveTab"] = tab is "tab-colors" or "tab-gallery" or "tab-features"
? tab
: "tab-basic";
return View("CreateEdit", model);
}
[HttpGet]
public async Task<IActionResult> GetTags()
{
var tags = await _productService.GetTags();
return Json(tags.Select(x => new
{
id = x.TagId,
value = x.Title
}));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateEdit(AdminCreateProductViewModel model, bool next = false)
{
if (!ModelState.IsValid)
{
await PopulateProductEditorAsync(model);
return View("CreateEdit", model);
}
var result = await _productService.SaveBasicInfoAsync(new SaveProductBasicInfoViewModel
{
ProductId = model.ProductId,
Title = model.Title,
Price = model.Price,
CategoryId = model.CategoryId,
Count = model.Count,
ShortDiscription = model.ShortDiscription,
Review = model.Review,
DetailReview = model.DetailReview,
Tags = model.Tags,
IsActive = model.IsActive,
ImageFile = model.ImageFile
});
if (!result.IsSuccess)
{
ModelState.AddModelError(string.Empty, result.Message);
await PopulateProductEditorAsync(model);
return View("CreateEdit", model);
}
return RedirectToAction(nameof(CreateEdit), new
{
id = result.ProductId,
tab = next ? "tab-colors" : "tab-basic"
});
}
[HttpGet]
public async Task<IActionResult> GetColors()
{
return Json(await _productService.GetColorsAsync());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SaveBasicInfo([FromForm] SaveProductBasicInfoViewModel model)
{
if (!ModelState.IsValid)
return InvalidModelState();
return Json(await _productService.SaveBasicInfoAsync(model));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateColor([FromForm] CreateColorViewModel model)
{
if (!ModelState.IsValid)
return InvalidModelState();
return Json(await _productService.CreateColorAsync(model));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddColor([FromForm] AddProductColorViewModel model)
{
if (!ModelState.IsValid)
return InvalidModelState();
return Json(await _productService.AddColorAsync(model));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveColor(int productId, int id)
{
return Json(await _productService.RemoveColorAsync(productId, id));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddGallery([FromForm] AddProductGalleryViewModel model)
{
if (!ModelState.IsValid)
return InvalidModelState();
return Json(await _productService.AddGalleryAsync(model));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveGallery(int productId, int id)
{
return Json(await _productService.RemoveGalleryAsync(productId, id));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddFeature([FromForm] AddProductFeatureViewModel model)
{
if (!ModelState.IsValid)
return InvalidModelState();
return Json(await _productService.AddFeatureAsync(model));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveFeature(int productId, int id)
{
return Json(await _productService.RemoveFeatureAsync(productId, id));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateTag([FromForm] CreateTagViewModel model)
{
if (!ModelState.IsValid)
return InvalidModelState();
return Json(await _productService.CreateTagAsync(model));
}
private BadRequestObjectResult InvalidModelState()
{
var message = string.Join(" ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage)
.Where(x => !string.IsNullOrWhiteSpace(x)));
return BadRequest(new
{
isSuccess = false,
message = string.IsNullOrWhiteSpace(message)
? "اطلاعات ارسالشده معتبر نیست."
: message
});
}
private async Task PopulateProductEditorAsync(AdminCreateProductViewModel model)
{
model.CategoryTree = await _categoryService.GetTreeAsync();
model.AllColors = await _productService.GetColorsAsync();
}
}3. کدهای ProductService
public class ProductService : IProductService
{
private readonly IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public async Task<IEnumerable<ProductTagEntity>> GetTags() =>
await _productRepository.GetTags();
public async Task<List<ColorListItemViewModel>> GetColorsAsync()
{
var colors = await _productRepository.GetColorsAsync();
return colors.Select(MapColor).ToList();
}
public async Task<AdminCreateProductViewModel?> GetForEditAsync(int id)
{
var product = await _productRepository.GetProductForEditAsync(id);
if (product == null)
return null;
return new AdminCreateProductViewModel
{
ProductId = product.Id,
CategoryId = product.CategoryId,
Title = product.Title,
Price = product.Price,
ShortDiscription = product.ShortDiscription,
Review = product.Review,
DetailReview = product.DetailReview,
ImageName = product.ImageName,
IsActive = product.IsActive,
Count = product.Count,
SelectedTags = product.ProductTags?
.Select(x => x.TagTitle)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList() ?? new(),
Colors = product.ProductColors?
.Where(x => !x.IsDeleted)
.Select(MapProductColor)
.ToList() ?? new(),
Gallery = product.ProductGalleries?
.Where(x => !x.IsDeleted)
.Select(MapGallery)
.ToList() ?? new(),
Features = product.ProductFeatures?
.Where(x => !x.IsDeleted)
.Select(MapFeature)
.ToList() ?? new()
};
}
public async Task<List<ProductListItemViewModel>> GetProductsAsync()
{
var products = await _productRepository.GetProductsAsync();
return products.Select(x => new ProductListItemViewModel
{
ProductId = x.Id,
Title = x.Title,
ImageName = x.ImageName,
Price = x.Price,
Count = x.Count,
IsActive = x.IsActive
}).ToList();
}
public async Task<ProductSaveResultViewModel> SaveBasicInfoAsync(SaveProductBasicInfoViewModel model)
{
if (string.IsNullOrWhiteSpace(model.Title))
return ProductFailure("عنوان محصول الزامی است.");
if (model.CategoryId <= 0)
return ProductFailure("انتخاب دستهبندی الزامی است.");
if (model.Price <= 0)
return ProductFailure("قیمت باید بزرگتر از صفر باشد.");
try
{
Product? product = null;
if (model.ProductId.HasValue && model.ProductId.Value > 0)
product = await _productRepository.GetProductForEditAsync(model.ProductId.Value);
var isNew = product == null;
product ??= new Product
{
CreateDate = DateTime.Now,
ProductColors = new List<ProductColor>(),
ProductFeatures = new List<ProductFeature>(),
ProductGalleries = new List<ProductGallery>(),
ProductTags = new List<ProductTag>()
};
product.CategoryId = model.CategoryId;
product.Title = model.Title.Trim();
product.Price = model.Price;
product.ShortDiscription = model.ShortDiscription;
product.Review = model.Review;
product.DetailReview = model.DetailReview;
product.IsActive = model.IsActive;
product.Count = Math.Max(0, model.Count);
product.UpdateDate = isNew ? null : DateTime.Now;
if (model.ImageFile != null)
{
if (!model.ImageFile.ImageValidate())
return ProductFailure("فرمت تصویر محصول معتبر نیست.");
if (!string.IsNullOrWhiteSpace(product.ImageName))
FileUploader.DeleteFile(product.ImageName, "Products");
product.ImageName = await FileUploader.SaveFileAsync(model.ImageFile, "Products");
}
if (isNew)
_productRepository.Add(product);
else
_productRepository.Update(product);
await _productRepository.SaveAsync();
await ReplaceProductTagsAsync(product, model.Tags);
await _productRepository.SaveAsync();
return new ProductSaveResultViewModel
{
IsSuccess = true,
ProductId = product.Id,
Message = isNew ? "اطلاعات پایه محصول ذخیره شد." : "تغییرات محصول ذخیره شد."
};
}
catch
{
return ProductFailure("هنگام ذخیره محصول خطایی رخ داد.");
}
}
public async Task<EntityMutationResult<ColorListItemViewModel>> CreateColorAsync(CreateColorViewModel model)
{
var name = model.Name?.Trim();
var code = NormalizeColorCode(model.Code);
if (string.IsNullOrWhiteSpace(name))
return MutationFailure<ColorListItemViewModel>("نام رنگ الزامی است.");
if (code == null)
return MutationFailure<ColorListItemViewModel>("کد رنگ معتبر نیست.");
if (await _productRepository.ColorExistsAsync(name))
return MutationFailure<ColorListItemViewModel>("این رنگ قبلا در لیست ثبت شده است.");
var color = new Color
{
Name = name,
Code = code,
CreateDate = DateTime.Now
};
_productRepository.AddColor(color);
await _productRepository.SaveAsync();
return new EntityMutationResult<ColorListItemViewModel>
{
IsSuccess = true,
Message = "رنگ جدید به لیست اضافه شد.",
Data = MapColor(color)
};
}
public async Task<EntityMutationResult<ProductColorViewModel>> AddColorAsync(AddProductColorViewModel model)
{
var product = await _productRepository.GetProductForEditAsync(model.ProductId);
var color = await _productRepository.GetColorAsync(model.ColorId);
if (product == null)
return MutationFailure<ProductColorViewModel>("محصول پیدا نشد.");
if (color == null)
return MutationFailure<ProductColorViewModel>("رنگ انتخابشده پیدا نشد.");
if (product.ProductColors?.Any(x =>
!x.IsDeleted && string.Equals(x.Name, color.Name, StringComparison.OrdinalIgnoreCase)) == true)
{
return MutationFailure<ProductColorViewModel>("این رنگ قبلا برای محصول انتخاب شده است.");
}
if (model.IsDefault)
{
foreach (var item in product.ProductColors ?? Enumerable.Empty<ProductColor>())
item.IsDefault = false;
}
var productColor = new ProductColor
{
ProductId = model.ProductId,
Name = color.Name,
Code = color.Code,
Price = Math.Max(0, model.Price),
Quantity = Math.Max(0, model.Quantity),
IsDefault = model.IsDefault,
CreateDate = DateTime.Now
};
_productRepository.AddProductColor(productColor);
await _productRepository.SaveAsync();
var result = MapProductColor(productColor);
result.ColorId = color.Id;
return new EntityMutationResult<ProductColorViewModel>
{
IsSuccess = true,
Message = "رنگ به محصول اضافه شد.",
Data = result
};
}
public async Task<OperationResult> RemoveColorAsync(int productId, int id)
{
var color = await _productRepository.GetProductColorAsync(productId, id);
if (color == null)
return Failure("رنگ محصول پیدا نشد.");
color.IsDeleted = true;
color.DeleteDate = DateTime.Now;
color.UpdateDate = DateTime.Now;
_productRepository.UpdateProductColor(color);
await _productRepository.SaveAsync();
return Success("رنگ از محصول حذف شد.");
}
public async Task<EntityMutationResult<ProductGalleryViewModel>> AddGalleryAsync(AddProductGalleryViewModel model)
{
var product = await _productRepository.GetProductForEditAsync(model.ProductId);
if (product == null)
return MutationFailure<ProductGalleryViewModel>("محصول پیدا نشد.");
if (model.Image == null || model.Image.Length == 0)
return MutationFailure<ProductGalleryViewModel>("انتخاب تصویر الزامی است.");
if (!model.Image.ImageValidate())
return MutationFailure<ProductGalleryViewModel>("فرمت تصویر گالری معتبر نیست.");
var gallery = new ProductGallery
{
ProductId = model.ProductId,
Alt = string.IsNullOrWhiteSpace(model.Alt) ? product.Title : model.Alt.Trim(),
ImageName = await FileUploader.SaveFileAsync(model.Image, "Products"),
CreateDate = DateTime.Now
};
_productRepository.AddProductGallery(gallery);
await _productRepository.SaveAsync();
return new EntityMutationResult<ProductGalleryViewModel>
{
IsSuccess = true,
Message = "تصویر به گالری اضافه شد.",
Data = MapGallery(gallery)
};
}
public async Task<OperationResult> RemoveGalleryAsync(int productId, int id)
{
var gallery = await _productRepository.GetProductGalleryAsync(productId, id);
if (gallery == null)
return Failure("تصویر گالری پیدا نشد.");
FileUploader.DeleteFile(gallery.ImageName, "Products");
gallery.IsDeleted = true;
gallery.DeleteDate = DateTime.Now;
gallery.UpdateDate = DateTime.Now;
_productRepository.UpdateProductGallery(gallery);
await _productRepository.SaveAsync();
return Success("تصویر از گالری حذف شد.");
}
public async Task<EntityMutationResult<ProductFeatureViewModel>> AddFeatureAsync(AddProductFeatureViewModel model)
{
var product = await _productRepository.GetProductForEditAsync(model.ProductId);
if (product == null)
return MutationFailure<ProductFeatureViewModel>("محصول پیدا نشد.");
if (string.IsNullOrWhiteSpace(model.Name) || string.IsNullOrWhiteSpace(model.Value))
return MutationFailure<ProductFeatureViewModel>("نام و مقدار ویژگی را وارد کنید.");
var feature = new ProductFeature
{
ProductId = model.ProductId,
Name = model.Name.Trim(),
Value = model.Value.Trim(),
CreateDate = DateTime.Now
};
_productRepository.AddProductFeature(feature);
await _productRepository.SaveAsync();
return new EntityMutationResult<ProductFeatureViewModel>
{
IsSuccess = true,
Message = "ویژگی محصول اضافه شد.",
Data = MapFeature(feature)
};
}
public async Task<OperationResult> RemoveFeatureAsync(int productId, int id)
{
var feature = await _productRepository.GetProductFeatureAsync(productId, id);
if (feature == null)
return Failure("ویژگی محصول پیدا نشد.");
feature.IsDeleted = true;
feature.DeleteDate = DateTime.Now;
feature.UpdateDate = DateTime.Now;
_productRepository.UpdateProductFeature(feature);
await _productRepository.SaveAsync();
return Success("ویژگی از محصول حذف شد.");
}
public async Task<EntityMutationResult<object>> CreateTagAsync(CreateTagViewModel model)
{
var title = model.Title?.Trim();
if (string.IsNullOrWhiteSpace(title))
return MutationFailure<object>("عنوان برچسب الزامی است.");
var existing = (await _productRepository.GetTags())
.FirstOrDefault(x => string.Equals(x.Title, title, StringComparison.OrdinalIgnoreCase));
if (existing != null)
{
return new EntityMutationResult<object>
{
IsSuccess = true,
Message = "این برچسب قبلا در لیست وجود دارد.",
Data = new { id = existing.TagId, value = existing.Title }
};
}
var tag = new ProductTagEntity
{
Title = title,
Slug = AddSlug.GenerateSlug(title)
};
_productRepository.AddTag(tag);
await _productRepository.SaveAsync();
return new EntityMutationResult<object>
{
IsSuccess = true,
Message = "برچسب جدید به لیست اضافه شد.",
Data = new { id = tag.TagId, value = tag.Title }
};
}
private async Task ReplaceProductTagsAsync(Product product, string? rawTags)
{
foreach (var oldTag in product.ProductTags?.ToList() ?? new List<ProductTag>())
_productRepository.RemoveProductTag(oldTag);
var tagTitles = ParseTags(rawTags).ToList();
if (tagTitles.Count == 0)
return;
var tags = (await _productRepository.GetTags()).ToList();
var newTags = tagTitles
.Where(title => !tags.Any(tag =>
string.Equals(tag.Title, title, StringComparison.OrdinalIgnoreCase)))
.Select(title => new ProductTagEntity
{
Title = title,
Slug = AddSlug.GenerateSlug(title)
})
.ToList();
foreach (var newTag in newTags)
_productRepository.AddTag(newTag);
tags.AddRange(newTags);
foreach (var title in tagTitles)
{
var existing = tags.FirstOrDefault(x =>
string.Equals(x.Title, title, StringComparison.OrdinalIgnoreCase));
_productRepository.AddProductTag(new ProductTag
{
ProductId = product.Id,
TagTitle = existing!.Title
});
}
}
}4. کدهای ProductRepository
public class ProductRepository : IProductRepository
{
public ProductRepository(AppDbContext context) : base(context)
{
}
public async Task<IEnumerable<Tag>> GetTags()
{
return await _context.Tags
.AsNoTracking()
.OrderBy(x => x.Title)
.ToListAsync();
}
public async Task<List<Color>> GetColorsAsync()
{
return await _context.Colors
.AsNoTracking()
.Where(x => !x.IsDeleted)
.OrderBy(x => x.Name)
.ToListAsync();
}
public async Task<Product?> GetProductForEditAsync(int id)
{
return await _context.Products
.Include(x => x.ProductColors!)
.Include(x => x.ProductFeatures)
.Include(x => x.ProductGalleries)
.Include(x => x.ProductTags)
.SingleOrDefaultAsync(x => x.Id == id && !x.IsDeleted);
}
public async Task<List<Product>> GetProductsAsync()
{
return await _context.Products
.AsNoTracking()
.Where(x => !x.IsDeleted)
.OrderByDescending(x => x.Id)
.ToListAsync();
}
public async Task<Color?> GetColorAsync(int id)
{
return await _context.Colors
.SingleOrDefaultAsync(x => x.Id == id && !x.IsDeleted);
}
public async Task<Tag?> GetTagAsync(int id)
{
return await _context.Tags.SingleOrDefaultAsync(x => x.TagId == id);
}
public async Task<bool> ColorExistsAsync(string name)
{
return await _context.Colors.AnyAsync(x => !x.IsDeleted && x.Name == name);
}
public async Task<bool> TagExistsAsync(string title)
{
return await _context.Tags.AnyAsync(x => x.Title == title);
}
public async Task<bool> ProductColorExistsAsync(int productId, int colorId)
{
var color = await GetColorAsync(colorId);
if (color == null)
{
return false;
}
return await _context.ProductColors
.AnyAsync(x => x.ProductId == productId && x.Name == color.Name && !x.IsDeleted);
}
public async Task<ProductColor?> GetProductColorAsync(int productId, int id)
{
return await _context.ProductColors
.SingleOrDefaultAsync(x => x.ProductId == productId && x.Id == id && !x.IsDeleted);
}
public async Task<ProductGallery?> GetProductGalleryAsync(int productId, int id)
{
return await _context.ProductGalleries
.SingleOrDefaultAsync(x => x.ProductId == productId && x.Id == id && !x.IsDeleted);
}
public async Task<ProductFeature?> GetProductFeatureAsync(int productId, int id)
{
return await _context.ProductFeatures
.SingleOrDefaultAsync(x => x.ProductId == productId && x.Id == id && !x.IsDeleted);
}
public void AddColor(Color color) => _context.Colors.Add(color);
public void AddTag(Tag tag) => _context.Tags.Add(tag);
public void AddProductColor(ProductColor color) => _context.ProductColors.Add(color);
public void AddProductGallery(ProductGallery gallery) => _context.ProductGalleries.Add(gallery);
public void AddProductFeature(ProductFeature feature) => _context.ProductFeatures.Add(feature);
public void AddProductTag(ProductTag tag) => _context.ProductTags.Add(tag);
public void UpdateProductColor(ProductColor color) => _context.ProductColors.Update(color);
public void UpdateProductGallery(ProductGallery gallery) => _context.ProductGalleries.Update(gallery);
public void UpdateProductFeature(ProductFeature feature) => _context.ProductFeatures.Update(feature);
public void RemoveProductColor(ProductColor color) => _context.ProductColors.Remove(color);
public void RemoveProductGallery(ProductGallery gallery) => _context.ProductGalleries.Remove(gallery);
public void RemoveProductFeature(ProductFeature feature) => _context.ProductFeatures.Remove(feature);
public void RemoveProductTag(ProductTag tag) => _context.ProductTags.Remove(tag);
}5.کدهای product-editor.js
(function (window, document) {
function init(config) {
if (!document.querySelector('.product-page')) return;
config = config || {};
const state = {
id: Number(document.getElementById('productId')?.value || config.productId || 0),
activeTab: 'tab-basic',
colors: config.colors || [],
pendingGallery: []
};
const categoryTree = config.categoryTree || [];
const selectedCategoryId = Number(config.selectedCategoryId || 0);
const token = config.token || document.querySelector('#productAntiForgery input[name="__RequestVerificationToken"]')?.value || '';
const urls = config.urls || {};
let tagify = null;
const editorIds = ['ShortDiscription', 'Review', 'DetailReview'];
const $ = (id) => document.getElementById(id);
const tabs = [...document.querySelectorAll('.product-tab')];
const panes = [...document.querySelectorAll('.tab-pane')];
const escapeHtml = (value) => String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
const valueOf = (object, camel, pascal) => object?.[camel] ?? object?.[pascal];
function showAlert(elementId, message, type = 'error') {
const element = $(elementId);
if (!element) return;
element.className = `product-alert ${type} show`;
element.textContent = message || '';
}
function hideAlert(elementId) {
const element = $(elementId);
if (element) element.className = 'product-alert';
}
function notify(message, type = 'success') {
if (window.toastr) {
window.toastr[type === 'error' ? 'error' : 'success'](message);
} else {
showAlert('globalProductAlert', message, type);
}
}
function setBusy(button, busy, busyText = 'در حال ذخیره...') {
if (!button) return;
if (busy) {
button.dataset.originalText = button.innerHTML;
button.disabled = true;
button.innerHTML = `<span class="spinner-border spinner-border-sm me-1"></span>${busyText}`;
} else {
button.disabled = false;
if (button.dataset.originalText) button.innerHTML = button.dataset.originalText;
}
}
async function post(url, formData) {
if (!(formData instanceof FormData)) {
const data = new FormData();
Object.entries(formData || {}).forEach(([key, value]) => data.append(key, value));
formData = data;
}
if (!formData.has('__RequestVerificationToken')) {
formData.append('__RequestVerificationToken', token);
}
const response = await fetch(url, {
method: 'POST',
headers: {
'RequestVerificationToken': token,
'Accept': 'application/json'
},
body: formData
});
let result = null;
try {
result = await response.json();
} catch {
result = { isSuccess: false, message: 'پاسخ نامعتبر از سرور دریافت شد.' };
}
if (!response.ok) {
throw new Error(valueOf(result, 'message', 'Message') || 'عملیات انجام نشد.');
}
if (valueOf(result, 'isSuccess', 'IsSuccess') === false) {
throw new Error(valueOf(result, 'message', 'Message') || 'عملیات انجام نشد.');
}
return result;
}
function activateTab(tabId) {
const button = tabs.find(x => x.dataset.tabTarget === tabId);
if (!button || button.disabled) return;
state.activeTab = tabId;
tabs.forEach(x => x.classList.toggle('active', x === button));
panes.forEach(x => x.classList.toggle('active', x.id === tabId));
window.scrollTo({ top: document.querySelector('.editor-card').offsetTop - 20, behavior: 'smooth' });
}
function enableProductTabs() {
tabs.filter(x => x.dataset.tabTarget !== 'tab-basic').forEach(x => x.disabled = false);
$('newProductHint')?.remove();
$('productStatusPill')?.classList.remove('is-draft');
if ($('productStatusPill')) $('productStatusPill').textContent = 'فعال';
}
function updateProductHeader() {
const title = $('Title').value.trim();
$('heroProductTitle').textContent = title || 'محصول بدون عنوان';
$('heroProductMeta').textContent = state.id
? `شناسه محصول: ${state.id}`
: 'اطلاعات پایه هنوز ذخیره نشده است';
$('basePricePreview').textContent = Number($('Price').value || 0).toLocaleString('fa-IR') + ' تومان';
}
function getChildren(node) {
return valueOf(node, 'children', 'Children') || [];
}
function getNodeId(node) {
return Number(valueOf(node, 'id', 'Id'));
}
function getNodeName(node) {
return valueOf(node, 'name', 'Name') || '';
}
function createCategorySelect(items, level) {
const select = document.createElement('select');
select.className = 'form-select mt-2 category-level';
select.dataset.level = level;
select.innerHTML = '<option value="">انتخاب دستهبندی</option>';
(items || []).forEach(item => {
const option = document.createElement('option');
option.value = getNodeId(item);
option.textContent = getNodeName(item);
select.appendChild(option);
});
$('categoryContainer').appendChild(select);
return select;
}
function findNode(items, id) {
for (const item of items || []) {
if (getNodeId(item) === Number(id)) return item;
const result = findNode(getChildren(item), id);
if (result) return result;
}
return null;
}
function findPath(items, id, path = []) {
for (const item of items || []) {
const nextPath = [...path, item];
if (getNodeId(item) === Number(id)) return nextPath;
const result = findPath(getChildren(item), id, nextPath);
if (result) return result;
}
return null;
}
function initializeCategories() {
const container = $('categoryContainer');
container.innerHTML = '';
const path = selectedCategoryId > 0 ? findPath(categoryTree, selectedCategoryId) : null;
if (!path || path.length === 0) {
createCategorySelect(categoryTree, 0);
return;
}
let items = categoryTree;
path.forEach((node, index) => {
const select = createCategorySelect(items, index);
select.value = getNodeId(node);
items = getChildren(node);
});
if (items.length) createCategorySelect(items, path.length);
$('CategoryId').value = selectedCategoryId;
}
$('categoryContainer').addEventListener('change', (event) => {
if (!event.target.classList.contains('category-level')) return;
const select = event.target;
const level = Number(select.dataset.level);
const selectedId = Number(select.value || 0);
[...document.querySelectorAll('.category-level')].forEach(item => {
if (Number(item.dataset.level) > level) item.remove();
});
$('CategoryId').value = selectedId || '';
const node = findNode(categoryTree, selectedId);
if (node && getChildren(node).length) createCategorySelect(getChildren(node), level + 1);
});
function initializeTags() {
const tagInput = $('TagifyCustomInlineSuggestion');
if (!tagInput || !window.Tagify) return null;
const tagify = new Tagify(tagInput, {
whitelist: [],
enforceWhitelist: false,
addTagOnBlur: true,
maxTags: 20,
dropdown: {
classname: 'tags-inline',
maxItems: 30,
enabled: 0,
closeOnSelect: false
}
});
const selectedTags = (config.selectedTags || [])
.map(tag => typeof tag === 'string' ? tag : valueOf(tag, 'value', 'Value'))
.filter(tag => tag && String(tag).trim())
.map(tag => ({ value: String(tag).trim() }));
if (selectedTags.length) tagify.addTags(selectedTags);
fetch(urls.getTags)
.then(response => {
if (!response.ok) throw new Error('Error loading tags');
return response.json();
})
.then(tags => {
tagify.settings.whitelist = tags || [];
})
.catch(error => console.error('Failed to load tags:', error));
return tagify;
}
function initializeEditors() {
if (!window.CKEDITOR) return;
editorIds.forEach(id => {
const element = $(id);
if (!element || window.CKEDITOR.instances[id]) return;
window.CKEDITOR.replace(id, {
language: 'fa',
contentsLangDirection: 'rtl'
});
});
}
function getEditorValue(id) {
const editor = window.CKEDITOR?.instances?.[id];
return editor ? editor.getData() : $(id)?.value || '';
}
function renderColorOptions(selectedId = '') {
const select = $('colorSelect');
select.innerHTML = '<option value="">انتخاب رنگ از لیست</option>' +
state.colors.map(color => {
const id = valueOf(color, 'id', 'Id');
const name = valueOf(color, 'name', 'Name');
const code = valueOf(color, 'code', 'Code') || '#64748b';
return `<option value="${id}" data-code="${escapeHtml(code)}">${escapeHtml(name)}</option>`;
}).join('');
if (selectedId) select.value = selectedId;
updateColorSwatch();
}
function updateColorSwatch() {
const option = $('colorSelect').selectedOptions[0];
const code = option?.dataset.code || '#64748b';
$('selectedColorSwatch').innerHTML = `<span class="color-swatch" style="background-color:${escapeHtml(code)}"></span>`;
}
function renderColorRow(color) {
$('colorsEmptyRow')?.remove();
const id = valueOf(color, 'id', 'Id');
const name = valueOf(color, 'colorName', 'ColorName') || valueOf(color, 'name', 'Name');
const code = valueOf(color, 'colorCode', 'ColorCode') || valueOf(color, 'code', 'Code') || '#64748b';
const price = Number(valueOf(color, 'price', 'Price') || 0);
const quantity = Number(valueOf(color, 'quantity', 'Quantity') || 0);
const isDefault = Boolean(valueOf(color, 'isDefault', 'IsDefault'));
const row = document.createElement('tr');
row.dataset.id = id;
row.dataset.default = isDefault;
row.innerHTML = `
<td><span class="color-name"><span class="color-swatch" style="background-color:${escapeHtml(code)}"></span>${escapeHtml(name)}</span></td>
<td class="muted-cell">${price > 0 ? price.toLocaleString('fa-IR') + ' تومان' : 'قیمت پایه'}</td>
<td>${quantity.toLocaleString('fa-IR')}</td>
<td><span class="badge ${isDefault ? 'bg-label-success' : 'bg-label-secondary'}">${isDefault ? 'رنگ پیشفرض' : 'فعال'}</span></td>
<td class="text-end"><button type="button" class="danger-btn js-remove-color" data-id="${id}"><i class="bx bx-trash"></i>حذف</button></td>
`;
if (isDefault) {
[...$('colorsBody').querySelectorAll('tr[data-id]')].forEach(existing => {
existing.dataset.default = 'false';
const badge = existing.querySelector('.badge');
if (badge) {
badge.className = 'badge bg-label-secondary';
badge.textContent = 'فعال';
}
});
}
$('colorsBody').appendChild(row);
$('colorsCount').textContent = $('colorsBody').querySelectorAll('tr[data-id]').length;
}
$('colorSelect').addEventListener('change', updateColorSwatch);
$('btnAddColor').addEventListener('click', async () => {
hideAlert('colorsAlert');
if (!state.id) {
showAlert('colorsAlert', 'ابتدا اطلاعات پایه محصول را ذخیره کنید.');
activateTab('tab-basic');
return;
}
const colorId = Number($('colorSelect').value || 0);
if (!colorId) {
showAlert('colorsAlert', 'یک رنگ از لیست انتخاب کنید.');
return;
}
const button = $('btnAddColor');
setBusy(button, true, 'در حال افزودن...');
try {
const data = new FormData();
data.append('ProductId', state.id);
data.append('ColorId', colorId);
data.append('Price', $('colorPrice').value || '0');
data.append('Quantity', $('colorQuantity').value || '0');
data.append('IsDefault', $('colorIsDefault').checked ? 'true' : 'false');
const result = await post(urls.addColor, data);
renderColorRow(valueOf(result, 'data', 'Data'));
$('colorPrice').value = '';
$('colorQuantity').value = '0';
$('colorIsDefault').checked = false;
notify(valueOf(result, 'message', 'Message') || 'رنگ اضافه شد.');
} catch (error) {
showAlert('colorsAlert', error.message);
} finally {
setBusy(button, false);
}
});
$('colorsBody').addEventListener('click', async event => {
const button = event.target.closest('.js-remove-color');
if (!button) return;
if (!confirm('این رنگ از محصول حذف شود؟')) return;
try {
const data = new FormData();
data.append('productId', state.id);
data.append('id', button.dataset.id);
const result = await post(urls.removeColor, data);
button.closest('tr').remove();
if (!$('colorsBody').querySelector('tr[data-id]')) {
$('colorsBody').innerHTML = '<tr id="colorsEmptyRow"><td colspan="5" class="empty-state"><i class="bx bx-palette"></i>هنوز تنوع رنگی برای این محصول ثبت نشده است.</td></tr>';
}
$('colorsCount').textContent = $('colorsBody').querySelectorAll('tr[data-id]').length;
notify(valueOf(result, 'message', 'Message') || 'رنگ حذف شد.');
} catch (error) {
showAlert('colorsAlert', error.message);
}
});
$('btnSaveNewColor').addEventListener('click', async () => {
hideAlert('createColorError');
const name = $('newColorName').value.trim();
if (!name) {
showAlert('createColorError', 'نام رنگ را وارد کنید.');
return;
}
const button = $('btnSaveNewColor');
setBusy(button, true, 'در حال افزودن...');
try {
const data = new FormData();
data.append('Name', name);
data.append('Code', $('newColorCode').value);
const result = await post(urls.createColor, data);
const color = valueOf(result, 'data', 'Data');
state.colors.push(color);
renderColorOptions(valueOf(color, 'id', 'Id'));
closeModal('createColorModal');
$('newColorName').value = '';
notify(valueOf(result, 'message', 'Message') || 'رنگ جدید اضافه شد.');
} catch (error) {
showAlert('createColorError', error.message);
} finally {
setBusy(button, false);
}
});
function renderPendingGallery() {
$('pendingGallery').innerHTML = state.pendingGallery.map((item, index) => `
<div class="gallery-card">
<span class="pending-label">در انتظار آپلود</span>
<img src="${item.preview}" alt="${escapeHtml(item.file.name)}" />
<div class="gallery-card-body">
<small title="${escapeHtml(item.file.name)}">${escapeHtml(item.file.name)}</small>
<button type="button" class="danger-btn js-remove-pending" data-index="${index}">
<i class="bx bx-x"></i>
حذف از صف
</button>
</div>
</div>
`).join('');
}
$('galleryFiles').addEventListener('change', event => {
state.pendingGallery.forEach(item => URL.revokeObjectURL(item.preview));
state.pendingGallery = [...event.target.files].map(file => ({
file,
preview: URL.createObjectURL(file)
}));
renderPendingGallery();
});
$('pendingGallery').addEventListener('click', event => {
const button = event.target.closest('.js-remove-pending');
if (!button) return;
const index = Number(button.dataset.index);
URL.revokeObjectURL(state.pendingGallery[index].preview);
state.pendingGallery.splice(index, 1);
renderPendingGallery();
});
function appendGalleryCard(image) {
$('galleryEmptyState')?.remove();
const id = valueOf(image, 'id', 'Id');
const imageName = valueOf(image, 'imageName', 'ImageName');
const alt = valueOf(image, 'alt', 'Alt') || '';
const card = document.createElement('div');
card.className = 'gallery-card';
card.dataset.id = id;
card.innerHTML = `
<img src="/Uploads/Products/${encodeURIComponent(imageName)}" alt="${escapeHtml(alt)}" />
<div class="gallery-card-body">
<small title="${escapeHtml(alt)}">${escapeHtml(alt)}</small>
<button type="button" class="danger-btn js-remove-gallery" data-id="${id}">
<i class="bx bx-trash"></i>
حذف تصویر
</button>
</div>
`;
$('galleryGrid').appendChild(card);
}
$('btnAddGallery').addEventListener('click', async () => {
hideAlert('galleryAlert');
if (!state.id) {
showAlert('galleryAlert', 'ابتدا اطلاعات پایه محصول را ذخیره کنید.');
activateTab('tab-basic');
return;
}
if (!state.pendingGallery.length) {
showAlert('galleryAlert', 'حداقل یک تصویر انتخاب کنید.');
return;
}
const button = $('btnAddGallery');
setBusy(button, true, 'در حال آپلود...');
try {
const alt = $('galleryAlt').value.trim();
for (const item of state.pendingGallery) {
const data = new FormData();
data.append('ProductId', state.id);
data.append('Alt', alt);
data.append('Image', item.file, item.file.name);
const result = await post(urls.addGallery, data);
appendGalleryCard(valueOf(result, 'data', 'Data'));
}
state.pendingGallery.forEach(item => URL.revokeObjectURL(item.preview));
state.pendingGallery = [];
$('galleryFiles').value = '';
$('galleryAlt').value = '';
renderPendingGallery();
$('galleryCount').textContent = $('galleryGrid').querySelectorAll('.gallery-card').length;
notify('تصاویر با موفقیت به گالری اضافه شدند.');
} catch (error) {
showAlert('galleryAlert', error.message);
} finally {
setBusy(button, false);
}
});
$('galleryGrid').addEventListener('click', async event => {
const button = event.target.closest('.js-remove-gallery');
if (!button) return;
if (!confirm('این تصویر از گالری حذف شود؟')) return;
try {
const data = new FormData();
data.append('productId', state.id);
data.append('id', button.dataset.id);
const result = await post(urls.removeGallery, data);
button.closest('.gallery-card').remove();
if (!$('galleryGrid').querySelector('.gallery-card')) {
$('galleryGrid').innerHTML = '<div id="galleryEmptyState" class="empty-state border rounded-3 w-100" style="grid-column:1/-1;"><i class="bx bx-image-alt"></i>هنوز تصویری به گالری اضافه نشده است.</div>';
}
$('galleryCount').textContent = $('galleryGrid').querySelectorAll('.gallery-card').length;
notify(valueOf(result, 'message', 'Message') || 'تصویر حذف شد.');
} catch (error) {
showAlert('galleryAlert', error.message);
}
});
function renderFeatureRow(feature) {
$('featuresEmptyRow')?.remove();
const id = valueOf(feature, 'id', 'Id');
const name = valueOf(feature, 'name', 'Name');
const value = valueOf(feature, 'value', 'Value');
const row = document.createElement('tr');
row.dataset.id = id;
row.innerHTML = `
<td class="fw-semibold">${escapeHtml(name)}</td>
<td class="muted-cell">${escapeHtml(value)}</td>
<td class="text-end"><button type="button" class="danger-btn js-remove-feature" data-id="${id}"><i class="bx bx-trash"></i>حذف</button></td>
`;
$('featuresBody').appendChild(row);
$('featuresCount').textContent = $('featuresBody').querySelectorAll('tr[data-id]').length;
}
$('btnAddFeature').addEventListener('click', async () => {
hideAlert('featuresAlert');
if (!state.id) {
showAlert('featuresAlert', 'ابتدا اطلاعات پایه محصول را ذخیره کنید.');
activateTab('tab-basic');
return;
}
const name = $('featureName').value.trim();
const value = $('featureValue').value.trim();
if (!name || !value) {
showAlert('featuresAlert', 'نام و مقدار ویژگی را وارد کنید.');
return;
}
const button = $('btnAddFeature');
setBusy(button, true, 'در حال افزودن...');
try {
const data = new FormData();
data.append('ProductId', state.id);
data.append('Name', name);
data.append('Value', value);
const result = await post(urls.addFeature, data);
renderFeatureRow(valueOf(result, 'data', 'Data'));
$('featureName').value = '';
$('featureValue').value = '';
notify(valueOf(result, 'message', 'Message') || 'ویژگی اضافه شد.');
} catch (error) {
showAlert('featuresAlert', error.message);
} finally {
setBusy(button, false);
}
});
$('featuresBody').addEventListener('click', async event => {
const button = event.target.closest('.js-remove-feature');
if (!button) return;
if (!confirm('این ویژگی از محصول حذف شود؟')) return;
try {
const data = new FormData();
data.append('productId', state.id);
data.append('id', button.dataset.id);
const result = await post(urls.removeFeature, data);
button.closest('tr').remove();
if (!$('featuresBody').querySelector('tr[data-id]')) {
$('featuresBody').innerHTML = '<tr id="featuresEmptyRow"><td colspan="3" class="empty-state"><i class="bx bx-list-ul"></i>هنوز ویژگیای برای این محصول ثبت نشده است.</td></tr>';
}
$('featuresCount').textContent = $('featuresBody').querySelectorAll('tr[data-id]').length;
notify(valueOf(result, 'message', 'Message') || 'ویژگی حذف شد.');
} catch (error) {
showAlert('featuresAlert', error.message);
}
});
async function saveBasicInfo() {
hideAlert('basicInfoAlert');
const title = $('Title').value.trim();
const price = Number($('Price').value || 0);
const categoryId = Number($('CategoryId').value || 0);
if (!title) {
showAlert('basicInfoAlert', 'نام محصول را وارد کنید.');
return false;
}
if (!price || price <= 0) {
showAlert('basicInfoAlert', 'قیمت محصول باید بزرگتر از صفر باشد.');
return false;
}
if (!categoryId) {
showAlert('basicInfoAlert', 'دستهبندی محصول را انتخاب کنید.');
return false;
}
const button = $('btnTopSave');
setBusy(button, true);
try {
const data = new FormData();
if (state.id) data.append('ProductId', state.id);
data.append('Title', title);
data.append('Price', price);
data.append('CategoryId', categoryId);
data.append('Count', Number($('Count').value || 0));
data.append('ShortDiscription', getEditorValue('ShortDiscription'));
data.append('Review', getEditorValue('Review'));
data.append('DetailReview', getEditorValue('DetailReview'));
data.append('IsActive', $('IsActive').checked ? 'true' : 'false');
data.append('Tags', tagify ? JSON.stringify(tagify.value) : '[]');
if ($('ImageFile').files[0]) data.append('ImageFile', $('ImageFile').files[0]);
const result = await post(urls.saveBasicInfo, data);
state.id = Number(valueOf(result, 'productId', 'ProductId') || state.id);
$('productId').value = state.id;
enableProductTabs();
updateProductHeader();
notify(valueOf(result, 'message', 'Message') || 'اطلاعات پایه ذخیره شد.');
return true;
} catch (error) {
showAlert('basicInfoAlert', error.message);
return false;
} finally {
setBusy(button, false);
}
}
$('ImageFile').addEventListener('change', event => {
const file = event.target.files[0];
if (!file) return;
$('productImagePreview').src = URL.createObjectURL(file);
});
$('Title').addEventListener('input', updateProductHeader);
$('Price').addEventListener('input', updateProductHeader);
$('btnTopSave').addEventListener('click', saveBasicInfo);
tabs.forEach(tab => tab.addEventListener('click', () => activateTab(tab.dataset.tabTarget)));
$('btnPreviousTab').addEventListener('click', () => {
const index = tabs.findIndex(x => x.dataset.tabTarget === state.activeTab);
if (index > 0) activateTab(tabs[index - 1].dataset.tabTarget);
});
$('btnNextTab').addEventListener('click', async () => {
const index = tabs.findIndex(x => x.dataset.tabTarget === state.activeTab);
if (index === 0 && !state.id) {
if (!await saveBasicInfo()) return;
}
if (index < tabs.length - 1) activateTab(tabs[index + 1].dataset.tabTarget);
});
$('btnFinish').addEventListener('click', async () => {
if (!state.id && !await saveBasicInfo()) return;
window.location.href = urls.index;
});
function openModal(id) {
const modal = $(id);
if (!modal) return;
modal.classList.add('is-open');
modal.setAttribute('aria-hidden', 'false');
}
function closeModal(id) {
const modal = $(id);
if (!modal) return;
modal.classList.remove('is-open');
modal.setAttribute('aria-hidden', 'true');
modal.querySelectorAll('.product-alert').forEach(x => x.className = 'product-alert');
}
document.addEventListener('click', event => {
const opener = event.target.closest('[data-modal-open]');
if (opener) openModal(opener.dataset.modalOpen);
const closer = event.target.closest('[data-modal-close]');
if (closer) closeModal(closer.closest('.product-modal').id);
});
document.querySelectorAll('.product-modal').forEach(modal => {
modal.addEventListener('click', event => {
if (event.target === modal) closeModal(modal.id);
});
});
document.addEventListener('keydown', event => {
if (event.key === 'Escape') {
document.querySelectorAll('.product-modal.is-open').forEach(modal => closeModal(modal.id));
}
});
initializeCategories();
initializeEditors();
tagify = initializeTags();
renderColorOptions();
updateProductHeader();
}
window.ProductEditor = window.ProductEditor || {};
window.ProductEditor.init = init;
if (window.productEditorConfig) window.ProductEditor.init(window.productEditorConfig);
})(window, document);
6. کدهای product-editor.css
.product-page {
--product-primary: #696cff;
--product-primary-soft: #eef0ff;
--product-ink: #2f3349;
--product-muted: #7b8198;
--product-border: #e8eaf2;
--product-bg: #f8f8fc;
color: var(--product-ink);
}
.product-page .page-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1.25rem;
}
.product-page .eyebrow {
color: var(--product-primary);
font-size: .78rem;
font-weight: 700;
letter-spacing: .03em;
margin-bottom: .45rem;
}
.product-page .page-title {
font-size: 1.55rem;
font-weight: 800;
margin: 0;
}
.product-page .page-subtitle {
color: var(--product-muted);
font-size: .88rem;
margin: .45rem 0 0;
}
.product-page .heading-actions {
display: flex;
flex-wrap: wrap;
gap: .65rem;
}
.product-page .soft-btn {
background: #fff;
border: 1px solid var(--product-border);
color: var(--product-ink);
}
.product-page .soft-btn:hover {
background: var(--product-bg);
border-color: #d7d9e8;
}
.product-page .hero-card,
.product-page .editor-card,
.product-page .stat-card {
background: #fff;
border: 1px solid var(--product-border);
border-radius: 1rem;
box-shadow: 0 8px 24px rgba(40, 42, 70, .04);
}
.product-page .hero-card {
align-items: center;
display: flex;
gap: 1rem;
justify-content: space-between;
margin-bottom: 1rem;
padding: 1rem 1.2rem;
}
.product-page .hero-product {
align-items: center;
display: flex;
gap: .9rem;
min-width: 0;
}
.product-page .hero-product-icon {
align-items: center;
background: linear-gradient(135deg, #696cff, #9b9dff);
border-radius: .8rem;
color: #fff;
display: flex;
flex: 0 0 48px;
font-size: 1.45rem;
height: 48px;
justify-content: center;
width: 48px;
}
.product-page .hero-product-title {
font-size: .96rem;
font-weight: 800;
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.product-page .hero-product-meta {
color: var(--product-muted);
font-size: .78rem;
margin: .25rem 0 0;
}
.product-page .status-pill {
align-items: center;
background: #ecfdf3;
border-radius: 999px;
color: #16834b;
display: inline-flex;
font-size: .75rem;
font-weight: 700;
gap: .4rem;
padding: .45rem .7rem;
white-space: nowrap;
}
.product-page .status-pill::before {
background: currentColor;
border-radius: 50%;
content: "";
height: 7px;
width: 7px;
}
.product-page .status-pill.is-draft {
background: #fff7e6;
color: #b7791f;
}
.product-page .stats-grid {
display: grid;
gap: .85rem;
grid-template-columns: repeat(4, minmax(0, 1fr));
margin-bottom: 1.15rem;
}
.product-page .stat-card {
align-items: center;
display: flex;
gap: .75rem;
padding: .9rem 1rem;
}
.product-page .stat-icon {
align-items: center;
background: var(--product-primary-soft);
border-radius: .7rem;
color: var(--product-primary);
display: flex;
flex: 0 0 38px;
font-size: 1.15rem;
height: 38px;
justify-content: center;
width: 38px;
}
.product-page .stat-label {
color: var(--product-muted);
font-size: .75rem;
margin: 0 0 .15rem;
}
.product-page .stat-value {
font-size: 1.02rem;
font-weight: 800;
margin: 0;
}
.product-page .editor-card {
overflow: hidden;
}
.product-page .product-tabs {
background: #fcfcfe;
border-bottom: 1px solid var(--product-border);
display: flex;
gap: .25rem;
overflow-x: auto;
padding: .55rem;
}
.product-page .product-tab {
align-items: center;
background: transparent;
border: 0;
border-radius: .65rem;
color: var(--product-muted);
display: inline-flex;
flex: 0 0 auto;
font-size: .82rem;
font-weight: 700;
gap: .45rem;
padding: .7rem .95rem;
transition: .2s ease;
}
.product-page .product-tab:hover:not(:disabled) {
background: var(--product-primary-soft);
color: var(--product-primary);
}
.product-page .product-tab.active {
background: var(--product-primary);
box-shadow: 0 5px 13px rgba(105, 108, 255, .2);
color: #fff;
}
.product-page .product-tab:disabled {
cursor: not-allowed;
opacity: .45;
}
.product-page .product-tab .tab-number {
align-items: center;
border: 1px solid currentColor;
border-radius: 50%;
display: inline-flex;
font-size: .68rem;
height: 21px;
justify-content: center;
width: 21px;
}
.product-page .tab-pane {
display: none;
padding: 1.35rem;
}
.product-page .tab-pane.active {
display: block;
}
.product-page .section-intro {
align-items: flex-start;
display: flex;
justify-content: space-between;
margin-bottom: 1.25rem;
gap: 1rem;
}
.product-page .section-title {
font-size: 1.05rem;
font-weight: 800;
margin: 0;
}
.product-page .section-description {
color: var(--product-muted);
font-size: .8rem;
line-height: 1.8;
margin: .3rem 0 0;
}
.product-page .form-label {
color: #555b72;
font-size: .78rem;
font-weight: 700;
margin-bottom: .45rem;
}
.product-page .form-control,
.product-page .form-select {
border-color: var(--product-border);
border-radius: .65rem;
font-size: .83rem;
min-height: 42px;
}
.product-page textarea.form-control {
min-height: 108px;
resize: vertical;
}
.product-page .form-control:focus,
.product-page .form-select:focus {
border-color: var(--product-primary);
box-shadow: 0 0 0 .2rem rgba(105, 108, 255, .12);
}
.product-page .field-hint {
color: var(--product-muted);
font-size: .72rem;
line-height: 1.8;
margin-top: .35rem;
}
.product-page .image-uploader {
background: var(--product-bg);
border: 1px dashed #ccd0e4;
border-radius: .9rem;
padding: .8rem;
}
.product-page .image-preview {
align-items: center;
background: #fff;
border: 1px solid var(--product-border);
border-radius: .75rem;
display: flex;
height: 250px;
justify-content: center;
margin-bottom: .75rem;
overflow: hidden;
}
.product-page .image-preview img {
height: 100%;
object-fit: contain;
width: 100%;
}
.product-page .upload-label {
align-items: center;
background: #fff;
border: 1px solid var(--product-border);
border-radius: .65rem;
color: var(--product-primary);
cursor: pointer;
display: flex;
font-size: .78rem;
font-weight: 700;
gap: .45rem;
justify-content: center;
min-height: 42px;
padding: .5rem;
}
.product-page .upload-label:hover {
background: var(--product-primary-soft);
}
.product-page .upload-label input {
display: none;
}
.product-page .switch-line {
align-items: center;
background: var(--product-bg);
border: 1px solid var(--product-border);
border-radius: .7rem;
display: flex;
justify-content: space-between;
min-height: 42px;
padding: .55rem .75rem;
}
.product-page .switch-line .form-check {
margin: 0;
}
.product-page .switch-line .form-check-input {
cursor: pointer;
float: none;
margin: 0 .4rem 0 0;
vertical-align: middle;
}
.product-page .switch-line .form-check-label {
color: #555b72;
font-size: .78rem;
font-weight: 700;
}
.product-page .tag-picker {
border: 1px solid var(--product-border);
border-radius: .65rem;
min-height: 42px;
padding: .35rem .5rem;
position: relative;
}
.product-page .tag-picker:focus-within {
border-color: var(--product-primary);
box-shadow: 0 0 0 .2rem rgba(105, 108, 255, .12);
}
.product-page .selected-tags {
display: flex;
flex-wrap: wrap;
gap: .35rem;
margin-bottom: .25rem;
}
.product-page .tag-chip {
align-items: center;
background: var(--product-primary-soft);
border-radius: 999px;
color: #5558b9;
display: inline-flex;
font-size: .72rem;
gap: .35rem;
padding: .3rem .55rem;
}
.product-page .tag-chip button {
background: transparent;
border: 0;
color: inherit;
cursor: pointer;
line-height: 1;
padding: 0;
}
.product-page .tag-picker-input {
border: 0;
font-size: .8rem;
min-height: 28px;
outline: 0;
width: 100%;
}
.product-page .tag-suggestions {
background: #fff;
border: 1px solid var(--product-border);
border-radius: .65rem;
box-shadow: 0 12px 28px rgba(40, 42, 70, .12);
display: none;
inset-inline: 0;
max-height: 190px;
overflow-y: auto;
padding: .3rem;
position: absolute;
top: calc(100% + .35rem);
z-index: 20;
}
.product-page .tag-suggestions.show {
display: block;
}
.product-page .tag-suggestion {
background: transparent;
border: 0;
border-radius: .45rem;
color: var(--product-ink);
display: block;
font-size: .78rem;
padding: .55rem .65rem;
text-align: right;
width: 100%;
}
.product-page .tag-suggestion:hover {
background: var(--product-primary-soft);
color: var(--product-primary);
}
.product-page .inline-action {
align-items: center;
color: var(--product-primary);
display: inline-flex;
font-size: .75rem;
font-weight: 700;
gap: .3rem;
text-decoration: none;
}
.product-page .inline-action:hover {
color: #4e52d9;
}
.product-page .table-wrap {
border: 1px solid var(--product-border);
border-radius: .8rem;
overflow-x: auto;
}
.product-page .table {
margin: 0;
min-width: 650px;
}
.product-page .table > :not(caption) > * > * {
border-bottom-color: var(--product-border);
font-size: .78rem;
padding: .8rem .9rem;
vertical-align: middle;
}
.product-page .table thead th {
background: var(--product-bg);
color: var(--product-muted);
font-size: .72rem;
font-weight: 800;
white-space: nowrap;
}
.product-page .color-name {
align-items: center;
display: inline-flex;
font-weight: 700;
gap: .5rem;
}
.product-page .color-swatch {
border: 2px solid #fff;
border-radius: 50%;
box-shadow: 0 0 0 1px #d4d7e5;
display: inline-block;
height: 22px;
width: 22px;
}
.product-page .muted-cell {
color: var(--product-muted);
}
.product-page .empty-state {
color: var(--product-muted);
padding: 2.2rem 1rem !important;
text-align: center;
}
.product-page .empty-state i {
color: #c9cce0;
display: block;
font-size: 2rem;
margin-bottom: .5rem;
}
.product-page .danger-btn {
align-items: center;
background: #fff1f2;
border: 0;
border-radius: .5rem;
color: #d1435b;
display: inline-flex;
font-size: .72rem;
gap: .25rem;
padding: .4rem .55rem;
}
.product-page .danger-btn:hover {
background: #ffe2e6;
}
.product-page .gallery-dropzone {
align-items: center;
background: var(--product-bg);
border: 1px dashed #c8cce2;
border-radius: .9rem;
display: flex;
gap: .8rem;
padding: 1rem;
}
.product-page .gallery-dropzone-icon {
align-items: center;
background: #fff;
border-radius: .7rem;
color: var(--product-primary);
display: flex;
flex: 0 0 42px;
font-size: 1.25rem;
height: 42px;
justify-content: center;
width: 42px;
}
.product-page .gallery-dropzone-copy {
flex: 1;
min-width: 0;
}
.product-page .gallery-dropzone-copy strong {
display: block;
font-size: .82rem;
margin-bottom: .15rem;
}
.product-page .gallery-dropzone-copy span {
color: var(--product-muted);
display: block;
font-size: .72rem;
}
.product-page .gallery-grid {
display: grid;
gap: .8rem;
grid-template-columns: repeat(4, minmax(0, 1fr));
margin-top: 1rem;
}
.product-page .gallery-card {
background: #fff;
border: 1px solid var(--product-border);
border-radius: .8rem;
overflow: hidden;
position: relative;
}
.product-page .gallery-card img {
background: var(--product-bg);
display: block;
height: 145px;
object-fit: cover;
width: 100%;
}
.product-page .gallery-card-body {
padding: .6rem;
}
.product-page .gallery-card-body small {
color: var(--product-muted);
display: block;
font-size: .68rem;
margin-bottom: .45rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.product-page .gallery-card-body .danger-btn {
width: 100%;
justify-content: center;
}
.product-page .pending-label {
background: #fff7e6;
border-radius: 999px;
color: #b7791f;
font-size: .65rem;
font-weight: 800;
left: .45rem;
padding: .25rem .4rem;
position: absolute;
top: .45rem;
}
.product-page .footer-actions {
border-top: 1px solid var(--product-border);
display: flex;
justify-content: space-between;
padding: 1rem 1.35rem;
}
.product-page .footer-actions .right-actions,
.product-page .footer-actions .left-actions {
display: flex;
flex-wrap: wrap;
gap: .6rem;
}
.product-page .product-alert {
border-radius: .65rem;
display: none;
font-size: .78rem;
margin-bottom: 1rem;
padding: .7rem .85rem;
}
.product-page .product-alert.show {
display: block;
}
.product-page .product-alert.error {
background: #fff1f2;
color: #b4233d;
}
.product-page .product-alert.success {
background: #ecfdf3;
color: #16834b;
}
.product-modal {
align-items: center;
background: rgba(31, 34, 54, .45);
display: none;
inset: 0;
justify-content: center;
padding: 1rem;
position: fixed;
z-index: 1050;
}
.product-modal.is-open {
display: flex;
}
.product-modal-dialog {
background: #fff;
border-radius: 1rem;
box-shadow: 0 22px 60px rgba(30, 33, 56, .2);
max-width: 440px;
overflow: hidden;
width: 100%;
}
.product-modal-header,
.product-modal-footer {
align-items: center;
display: flex;
justify-content: space-between;
padding: 1rem 1.15rem;
}
.product-modal-header {
border-bottom: 1px solid var(--product-border);
}
.product-modal-footer {
border-top: 1px solid var(--product-border);
gap: .6rem;
justify-content: flex-start;
}
.product-modal-title {
font-size: .95rem;
font-weight: 800;
margin: 0;
}
.product-modal-close {
background: transparent;
border: 0;
color: var(--product-muted);
font-size: 1.2rem;
line-height: 1;
}
.product-modal-body {
padding: 1.15rem;
}
@media (max-width: 992px) {
.product-page .stats-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.product-page .gallery-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 576px) {
.product-page .page-heading,
.product-page .hero-card,
.product-page .section-intro,
.product-page .footer-actions {
align-items: stretch;
flex-direction: column;
}
.product-page .heading-actions,
.product-page .footer-actions .right-actions,
.product-page .footer-actions .left-actions {
width: 100%;
}
.product-page .heading-actions .btn,
.product-page .footer-actions .btn {
flex: 1;
}
.product-page .tab-pane {
padding: 1rem;
}
.product-page .gallery-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
سلام
بسیار عالی
ممنون از شما