name: CI/CD - ERP Core Monorepo

on:
  pull_request:
    branches:
      - production
    types:
      - closed

jobs:
  backend-build-and-deploy:
    name: Build & Deploy ERP Core Backend
    runs-on: linux
    if: github.event.pull_request.merged == true
    steps:
      - name: Checkout code
        run: |
          git clone \
            --depth 1 \
            --branch production \
            https://oauth2:${{ secrets.ERPCORE }}@gitea.hexdive.com/New_REP_SYSTEM/ERP-core.git \
            .

      - name: Restore backend
        run: dotnet restore Backend/ERPCore.sln

      - name: Publish backend
        run: |
          rm -rf /tmp/erpcore-deploy
          mkdir -p /tmp/erpcore-deploy
          dotnet publish Backend/ERPCore/ERPCore.csproj \
            -c Release \
            -r linux-x64 \
            --self-contained true \
            -o /tmp/erpcore-deploy

      - name: Stop backend service
        run: systemctl stop erpcore.service

      - name: Copy backend to deploy folder
        run: |
          mkdir -p /home/erp/core/publish
          rm -rf /home/erp/core/publish/*
          cp -r /tmp/erpcore-deploy/* /home/erp/core/publish/

      - name: Fix backend ownership and permissions
        run: |
          chown -R erpuser:erpuser /home/erp/core/publish
          find /home/erp/core/publish -type d -exec chmod 755 {} +
          find /home/erp/core/publish -type f -exec chmod 644 {} +
          chmod +x /home/erp/core/publish/ERPCore

      - name: Restart backend service
        run: systemctl restart erpcore.service

      - name: Verify backend
        run: |
          systemctl is-active erpcore.service && echo "Backend service running" || echo "Backend service failed"

  frontend-build-and-deploy:
    name: Build & Deploy ERP Core Frontend
    runs-on: linux
    needs: backend-build-and-deploy
    if: github.event.pull_request.merged == true
    steps:
      - name: Checkout code
        run: |
          git clone \
            --depth 1 \
            --branch Production \
            https://oauth2:${{ secrets.ERPCORE }}@gitea.hexdive.com/New_REP_SYSTEM/ERP-core.git \
            .

      - name: Build frontend Docker image
        run: docker build -t erpcore-frontend:latest Frontend/erp-system

      - name: Stop & remove existing frontend container
        run: |
          docker stop erpcore-frontend 2>/dev/null || true
          docker rm erpcore-frontend 2>/dev/null || true

      - name: Start frontend container
        run: |
          docker run -d \
            --name erpcore-frontend \
            -p 6702:6702 \
            --add-host=host.docker.internal:host-gateway \
            -e BACKEND_ORIGIN=http://host.docker.internal:6701 \
            --restart unless-stopped \
            --memory="512m" \
            --cpus="1.0" \
            --cap-drop ALL \
            --security-opt no-new-privileges \
            erpcore-frontend:latest

      - name: Remove old frontend images
        run: docker image prune -f

      - name: Verify frontend
        run: |
          docker ps --filter name=erpcore-frontend --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" \
            | grep erpcore-frontend && echo "Frontend container running" || echo "Frontend container failed"
This commit is contained in:
Kalana B. Thilakarathna
2026-09-17 13:59:05 +05:30
parent 93f2f1bd3b
commit 03d01d4c4e
61 changed files with 2195 additions and 1245 deletions
@@ -15,24 +15,21 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { Button } from '@/components/ui/button'
import { FieldGroup } from '@/components/ui/field'
import { Separator } from '@/components/ui/separator'
import { toast } from '@/components/ui/toast'
import {
sales as salesApi,
shopPos as shopPosApi,
stores as storesApi,
rides as ridesApi,
items as itemsApi,
users as usersApi,
priceLists as priceListsApi,
getApiError,
getPaginatedItems,
} from '@/lib/api/index'
import type { ItemSummaryResponse, RideResponse, StoreResponse, UserResponse } from '@/types/api'
import type { ItemSummaryResponse, StoreResponse } from '@/types/api'
const saleItemSchema = z.object({
const lineItemSchema = z.object({
itemId: z.string().min(1, 'Item is required'),
quantity: z.number().min(1, 'Quantity must be at least 1'),
unitPrice: z.number().min(0.01, 'Unit price must be greater than 0'),
@@ -40,11 +37,7 @@ const saleItemSchema = z.object({
const schema = z.object({
storeId: z.string().min(1, 'Store is required'),
saleDate: z.string().min(1, 'Sale date is required'),
createdByUserId: z.string().min(1, 'Created by is required'),
rideId: z.string(),
fulfillImmediately: z.boolean(),
items: z.array(saleItemSchema).min(1, 'At least one item is required'),
items: z.array(lineItemSchema).min(1, 'At least one item is required'),
})
type FormValues = z.infer<typeof schema>
@@ -53,61 +46,46 @@ function createDefaultItem() {
return { itemId: '', quantity: 1, unitPrice: 0 }
}
function todayIso() {
return new Date().toISOString().slice(0, 10)
}
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
export default function NewSalePage() {
export default function NewShopPOPage() {
const router = useRouter()
const [storesList, setStoresList] = useState<StoreResponse[]>([])
const [ridesList, setRidesList] = useState<RideResponse[]>([])
const [itemsList, setItemsList] = useState<ItemSummaryResponse[]>([])
const [usersList, setUsersList] = useState<UserResponse[]>([])
const [priceMinByIndex, setPriceMinByIndex] = useState<Record<number, number | null>>({})
const [priceRetailByIndex, setPriceRetailByIndex] = useState<Record<number, number | null>>({})
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
storeId: '',
saleDate: todayIso(),
createdByUserId: '',
rideId: '',
fulfillImmediately: false,
items: [createDefaultItem()],
},
})
const { fields, append, remove } = useFieldArray({
control: form.control,
name: 'items',
defaultValues: { storeId: '', items: [createDefaultItem()] },
})
const { fields, append, remove } = useFieldArray({ control: form.control, name: 'items' })
const watchedItems = useWatch({ control: form.control, name: 'items' })
const watchedStoreId = useWatch({ control: form.control, name: 'storeId' })
const watchedSaleDate = useWatch({ control: form.control, name: 'saleDate' })
const itemsById = useMemo(
() => new Map(itemsList.map((item) => [item.id, item])),
[itemsList]
)
const totalAmount = useMemo(
() => watchedItems.reduce((sum, item) => sum + (Number(item.quantity) || 0) * (Number(item.unitPrice) || 0), 0),
() => watchedItems.reduce((sum, line) => sum + (Number(line.quantity) || 0) * (Number(line.unitPrice) || 0), 0),
[watchedItems]
)
const [priceMinByIndex, setPriceMinByIndex] = useState<Record<number, number | null>>({})
const [priceRetailByIndex, setPriceRetailByIndex] = useState<Record<number, number | null>>({})
async function resolveAndSetPrice(index: number, itemId: string) {
const item = itemsById.get(itemId)
if (watchedStoreId && watchedSaleDate) {
const today = new Date().toISOString().slice(0, 10)
if (watchedStoreId) {
try {
const resolution = await priceListsApi.resolve({ itemId, storeId: watchedStoreId, saleDate: watchedSaleDate })
const resolution = await priceListsApi.resolve({ itemId, storeId: watchedStoreId, saleDate: today })
form.setValue(`items.${index}.unitPrice`, resolution.price, { shouldValidate: true })
setPriceMinByIndex((prev) => ({ ...prev, [index]: resolution.minPrice }))
setPriceRetailByIndex((prev) => ({ ...prev, [index]: resolution.retailPrice }))
return
} catch {
// No resolvable price for this store/date (e.g. store/item not found) — fall back below.
// No resolvable price for this store — fall back to item default.
}
}
if (item) {
@@ -117,28 +95,22 @@ export default function NewSalePage() {
}
}
// Re-resolve every already-selected line's price whenever the store or sale date changes,
// since the applicable price list is scoped by the store's region and the sale date.
useEffect(() => {
if (!watchedStoreId || !watchedSaleDate) return
if (!watchedStoreId) return
watchedItems.forEach((line, index) => {
if (line.itemId) resolveAndSetPrice(index, line.itemId)
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [watchedStoreId, watchedSaleDate])
}, [watchedStoreId])
useEffect(() => {
Promise.all([
storesApi.list({ pageSize: 200 }),
ridesApi.list({ pageSize: 200, rideType: 'Sale' }),
itemsApi.list({ pageSize: 200 }),
usersApi.list({ pageSize: 200 }),
])
.then(([stores, rides, items, usersRes]) => {
.then(([stores, items]) => {
setStoresList(getPaginatedItems(stores))
setRidesList(getPaginatedItems(rides))
setItemsList(getPaginatedItems(items))
setUsersList(getPaginatedItems(usersRes))
})
.catch((err) => {
toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' })
@@ -147,18 +119,14 @@ export default function NewSalePage() {
async function onSubmit(values: FormValues) {
try {
await salesApi.create({
await shopPosApi.create({
storeId: values.storeId,
saleDate: values.saleDate,
rideId: values.rideId || null,
fulfillImmediately: values.fulfillImmediately,
items: values.items,
createdByUserId: values.createdByUserId,
})
toast.add({ title: 'Sale created', type: 'success' })
toast.add({ title: 'Shop PO created', type: 'success' })
router.push('/sales')
} catch (err) {
toast.add({ title: 'Failed to create sale', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to create Shop PO', description: getApiError(err), type: 'error' })
}
}
@@ -170,116 +138,34 @@ export default function NewSalePage() {
Back
</Button>
<div>
<h1 className="text-2xl font-semibold text-foreground">Create Sale</h1>
<p className="text-sm text-muted-foreground">Record a sale for a store with one or more items.</p>
<h1 className="text-2xl font-semibold text-foreground">Create Shop PO</h1>
<p className="text-sm text-muted-foreground">Record a purchase order for a store.</p>
</div>
</div>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
<div className="rounded-2xl border p-6">
<h3 className="mb-4 text-sm font-medium text-foreground">Sale Details</h3>
<h3 className="mb-4 text-sm font-medium text-foreground">Order Details</h3>
<FieldGroup>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
<FormField
control={form.control}
name="storeId"
label="Store"
required
render={({ field }) => (
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select store..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select store...</SelectItem>
{storesList.map((store) => (
<SelectItem key={store.id} value={store.id}>
{store.storeName} - {store.ownerName}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
<FormField
control={form.control}
name="saleDate"
label="Sale Date"
required
render={({ field, invalid }) => (
<Input
id="saleDate"
name={field.name}
ref={field.ref}
type="date"
value={field.value as string}
onChange={field.onChange}
onBlur={field.onBlur}
aria-invalid={invalid}
/>
)}
/>
<FormField
control={form.control}
name="createdByUserId"
label="Created By"
description="Temporary — required until auth resolves the logged-in user automatically."
required
render={({ field }) => (
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select user..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select user...</SelectItem>
{usersList.map((user) => (
<SelectItem key={user.id} value={user.id}>
{user.fullName}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
<FormField
control={form.control}
name="rideId"
label="Ride"
render={({ field }) => (
<Select
value={(field.value as string) || '__none__'}
onValueChange={(value) => field.onChange(value === '__none__' ? '' : value)}
>
<SelectTrigger>
<SelectValue placeholder="Select ride..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">No ride</SelectItem>
{ridesList.map((ride) => (
<SelectItem key={ride.id} value={ride.id}>
{ride.routeName} - {ride.vehicleNumberPlate}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
<FormField
control={form.control}
name="fulfillImmediately"
name="storeId"
label="Store"
required
render={({ field }) => (
<label className="flex items-center gap-3 text-sm font-medium">
<Checkbox
checked={Boolean(field.value)}
onCheckedChange={(checked) => field.onChange(Boolean(checked))}
/>
Fulfill immediately (van sale)
</label>
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select store..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select store...</SelectItem>
{storesList.map((store) => (
<SelectItem key={store.id} value={store.id}>
{store.storeName} — {store.ownerName}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</FieldGroup>
@@ -313,7 +199,9 @@ export default function NewSalePage() {
<tbody>
{fields.map((fieldItem, index) => {
const selectedItem = itemsById.get(watchedItems[index]?.itemId ?? '')
const lineTotal = (Number(watchedItems[index]?.quantity) || 0) * (Number(watchedItems[index]?.unitPrice) || 0)
const lineTotal =
(Number(watchedItems[index]?.quantity) || 0) *
(Number(watchedItems[index]?.unitPrice) || 0)
return (
<tr key={fieldItem.id} className="border-t align-top">
@@ -336,7 +224,7 @@ export default function NewSalePage() {
<SelectItem value="" disabled>Select item...</SelectItem>
{itemsList.map((item) => (
<SelectItem key={item.id} value={item.id}>
{item.name} - {item.sku}
{item.name} — {item.sku}
</SelectItem>
))}
</SelectContent>
@@ -356,9 +244,6 @@ export default function NewSalePage() {
name={`items.${index}.quantity`}
render={({ field, invalid }) => (
<Input
id={`items.${index}.quantity`}
name={field.name}
ref={field.ref}
type="number"
min={1}
value={Number(field.value as number)}
@@ -377,9 +262,6 @@ export default function NewSalePage() {
name={`items.${index}.unitPrice`}
render={({ field, invalid }) => (
<Input
id={`items.${index}.unitPrice`}
name={field.name}
ref={field.ref}
type="number"
min={0.01}
step="0.01"
@@ -393,12 +275,12 @@ export default function NewSalePage() {
/>
{priceMinByIndex[index] != null && (
<p className="mt-1 text-xs text-muted-foreground">
Negotiable down to {fmtAmount(priceMinByIndex[index]!)}
Min: {fmtAmount(priceMinByIndex[index]!)}
</p>
)}
{priceRetailByIndex[index] != null && (
<p className="mt-1 text-xs text-muted-foreground">
Retail price: {fmtAmount(priceRetailByIndex[index]!)}
Retail: {fmtAmount(priceRetailByIndex[index]!)}
</p>
)}
</td>
@@ -426,9 +308,9 @@ export default function NewSalePage() {
<div className="flex justify-end">
<div className="w-full rounded-2xl border p-6 sm:w-96">
<h3 className="text-sm font-medium text-foreground">Sale Summary</h3>
<h3 className="text-sm font-medium text-foreground">Order Summary</h3>
<p className="mt-1 text-sm text-muted-foreground">
{watchedItems.length} item{watchedItems.length === 1 ? '' : 's'} on this sale.
{watchedItems.length} item{watchedItems.length === 1 ? '' : 's'} on this order.
</p>
<Separator className="my-4" />
@@ -440,7 +322,7 @@ export default function NewSalePage() {
<div className="mt-6 flex flex-col gap-2">
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Creating...' : 'Create Sale'}
{form.formState.isSubmitting ? 'Creating...' : 'Create Shop PO'}
</Button>
<Button type="button" variant="outline" onClick={() => router.push('/sales')}>
Cancel