# 📦 Proto & gRPC Complete Guide

> **آخرین بروزرسانی**: January 3, 2026  
> **NuGet Server**: GitLab Package Registry  
> **URL جدید**: `https://git.se.kbs1.ir/api/packages/FourSat/nuget/index.json`

---

## 📊 معماری Packaging

```
┌─────────────────────────────────────────────────────────────┐
│  LAYER 1: CMS Proto (Base)                                  │
│  CMSMicroservice.Protobuf                                   │
│  Version: 0.0.142+ → Auto-push به GitLab                   │
└─────────────────────────────────────────────────────────────┘
                              │
                     PackageReference
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  LAYER 2: BFF Protos                                        │
│  BackOffice.BFF.*.Protobuf (24 packages)                    │
│  FrontOffice.BFF.*.Protobuf (packages)                      │
│  → Depend on: CMS Proto v0.0.x                              │
└─────────────────────────────────────────────────────────────┘
                              │
                     PackageReference / DLL Reference
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  LAYER 3: UI Applications                                   │
│  BackOffice UI → libs/*.dll (24 DLLs)                       │
│  FrontOffice UI → FrontOffice.BFF Protos                    │
└─────────────────────────────────────────────────────────────┘
```

---

## ⚠️ قانون طلایی

**هر تغییر در Proto = این 3 مرحله اجباری:**

```bash
# 1️⃣ افزایش Version
<Version>X.Y.Z</Version>  →  <Version>X.Y.Z+1</Version>

# 2️⃣ Pack کردن
dotnet pack -c Release
# ✅ خودکار push می‌شه به GitLab

# 3️⃣ Update در لایه بالاتر
<PackageReference Include="PackageName" Version="NEW_VERSION" />
```

---

## 🔧 روش‌های Reference در BackOffice

### روش 1: DLL Reference (Production/CI-CD) ✅ پیشنهادی

**مزایا**: مستقل از ریپوی BFF، مناسب CI/CD

```bash
# Build proto DLLs
cd BackOffice
./build-deps.sh

# DLLs در libs/ قرار می‌گیرند
ls libs/*.dll | wc -l  # 24 DLL
```

**BackOffice.csproj**:
```xml
<!-- CI/CD Mode: Use pre-built DLLs -->
<ItemGroup Condition="Exists('../../libs/BackOffice.BFF.Common.Protobuf.dll')">
    <Reference Include="BackOffice.BFF.Common.Protobuf">
        <HintPath>../../libs/BackOffice.BFF.Common.Protobuf.dll</HintPath>
    </Reference>
    <!-- ... all 24 proto DLLs ... -->
</ItemGroup>

<!-- Transitive Dependencies -->
<PackageReference Include="Google.Protobuf" Version="3.28.3"/>
<PackageReference Include="Grpc.Core.Api" Version="2.71.0"/>
```

---

### روش 2: ProjectReference (Development)

**مزایا**: تغییرات بلافاصله اعمال می‌شود

```xml
<!-- Development Mode: Fallback if libs/ doesn't exist -->
<ItemGroup Condition="!Exists('../../libs/BackOffice.BFF.Common.Protobuf.dll')">
    <ProjectReference Include="..\..\..\BackOffice.BFF\src\Protobufs\BackOffice.BFF.Common.Protobuf\BackOffice.BFF.Common.Protobuf.csproj"/>
</ItemGroup>
```

---

### روش 3: PackageReference (قدیمی)

**مزایا**: کنترل دقیق ورژن

```xml
<ItemGroup>
    <PackageReference Include="Foursat.BackOffice.BFF.Common.Protobuf" Version="1.0.0"/>
</ItemGroup>
```

**معایب**: نیاز به push به NuGet server

---

## 📝 اسکریپت build-deps.sh

**مسیر**: `/home/masoud/Apps/project/FourSat/BackOffice/build-deps.sh`

```bash
#!/bin/bash
# Build all BFF proto dependencies and copy DLLs to libs folder

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIBS_DIR="$SCRIPT_DIR/libs"
BFF_PROTOS_DIR="$SCRIPT_DIR/../BackOffice.BFF/src/Protobufs"

echo "🔧 Building all proto dependencies..."
mkdir -p "$LIBS_DIR"

# All 24 proto projects
PROTO_PROJECTS=(
    "BackOffice.BFF.Common.Protobuf"
    "BackOffice.BFF.Category.Protobuf"
    # ... (complete list)
)

for PROJECT in "${PROTO_PROJECTS[@]}"; do
    PROJECT_DIR="$BFF_PROTOS_DIR/$PROJECT"
    dotnet build "$PROJECT_DIR" -c Release --verbosity quiet
    
    # Check both net9.0 and net8.0
    if [ -f "$PROJECT_DIR/bin/Release/net9.0/$PROJECT.dll" ]; then
        cp "$PROJECT_DIR/bin/Release/net9.0/$PROJECT.dll" "$LIBS_DIR/"
    elif [ -f "$PROJECT_DIR/bin/Release/net8.0/$PROJECT.dll" ]; then
        cp "$PROJECT_DIR/bin/Release/net8.0/$PROJECT.dll" "$LIBS_DIR/"
    fi
done

echo "✅ Build complete! Total DLLs: $(ls $LIBS_DIR/*.dll | wc -l)"
```

---

## 🚀 Workflow توسعه

### Development (Local):

```bash
# Build با Debug config
cd BackOffice/src
dotnet build -c Debug

# اگر libs/ نباشد → از ProjectReference استفاده می‌شود
# تغییرات Proto بلافاصله اعمال می‌شود
```

### Production (Deploy):

```bash
# 1. Build proto DLLs
cd BackOffice
./build-deps.sh

# 2. Build & Publish
cd src
dotnet publish BackOffice/BackOffice.csproj -c Release -o ./publish

# 3. بررسی output
ls ./publish/wwwroot/_framework/*.wasm | grep "BackOffice.BFF" | wc -l
# Result: 24 ✅
```

---

## 📦 لیست Proto Projects

### BackOffice.BFF (24 پروژه)

| پروژه | Target Framework | وضعیت |
|-------|------------------|--------|
| BackOffice.BFF.Common.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Category.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.ClubMembership.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Commission.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Configuration.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.DiscountCategory.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.DiscountOrder.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.DiscountProduct.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.DiscountShoppingCart.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Health.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Inventory.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.ManualPayment.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.NetworkMembership.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Otp.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Package.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Products.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.ProductTag.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.PublicMessage.Protobuf | **net8.0** | ✅ |
| BackOffice.BFF.Role.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.Tag.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.User.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.UserAddress.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.UserOrder.Protobuf | net9.0 | ✅ |
| BackOffice.BFF.UserRole.Protobuf | net9.0 | ✅ |

⚠️ **نکته**: `PublicMessage.Protobuf` تنها پروژه با `net8.0` است

---

## 🔧 تنظیمات csproj با Auto-Push

```xml
<Project Sdk="Microsoft.NET.Sdk">
  
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <PackageId>Foursat.BackOffice.BFF.Products.Protobuf</PackageId>
    <Version>1.0.0</Version>
    <Authors>FourSat</Authors>
    <Company>FourSat</Company>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <PackageOutputPath>./nupkg</PackageOutputPath>
  </PropertyGroup>

  <!-- Auto-Push به GitLab -->
  <Target Name="PushToFoursatNuget" AfterTargets="Pack" 
          Condition="'$(Configuration)' == 'Release'">
    <PropertyGroup>
      <NugetPackagePath>$(PackageOutputPath)$(PackageId).$(Version).nupkg</NugetPackagePath>
      <PushCommand>dotnet nuget push **/*.nupkg --source https://git.se.kbs1.ir/api/packages/FourSat/nuget/index.json --api-key YOUR_API_KEY --skip-duplicate</PushCommand>
    </PropertyGroup>
    <Exec Command="$(PushCommand)" />
  </Target>

</Project>
```

---

## 🛠️ Troubleshooting

### مشکل: Version Conflict

**علامت**: 
```
error NU1605: Detected package downgrade: Grpc.Core.Api from 2.71.0 to 2.54.0
```

**راه‌حل**:
```xml
<PackageReference Include="Grpc.Core.Api" Version="2.71.0"/>
```

---

### مشکل: Missing Transitive Dependencies

**علامت**:
```
CS0234: The type or namespace name 'Google' does not exist
```

**راه‌حل**: اضافه کردن dependencies در csproj:
```xml
<PackageReference Include="Google.Protobuf" Version="3.28.3"/>
<PackageReference Include="Google.Api.CommonProtos" Version="2.10.0"/>
<PackageReference Include="FluentValidation" Version="11.2.2"/>
```

---

### مشکل: DLL Not Found

**علامت**:
```
warning MSB3245: Could not resolve this reference
```

**راه‌حل**:
```bash
# Rebuild all proto DLLs
cd BackOffice
rm -rf libs/
./build-deps.sh
```

---

### مشکل: net8.0 vs net9.0

**علامت**: DLL یک پروژه کپی نشده

**راه‌حل**: اسکریپت `build-deps.sh` هر دو framework را چک می‌کند

---

## 📚 مراجع

- [gRPC for .NET](https://docs.microsoft.com/en-us/aspnet/core/grpc/)
- [Protocol Buffers](https://developers.google.com/protocol-buffers)
- [NuGet CLI Reference](https://docs.microsoft.com/en-us/nuget/reference/nuget-exe-cli-reference)
