Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
780335dc15 | ||
|
|
dd08e047a3 | ||
|
|
b02528a795 | ||
|
|
7e0a646853 | ||
|
|
d900b62f33 | ||
|
|
182f20d43e | ||
|
|
fe22681c66 | ||
|
|
266af59bc6 |
No files matched your search
@@ -38,9 +38,9 @@ def get_default_series(document_type: str) -> Optional[int]:
|
||||
def get_active_series(document_type: str) -> List[dict]:
|
||||
"""
|
||||
Lista las series no bloqueadas de un tipo de documento de SAP B1, vía
|
||||
SeriesService_GetDocumentSeries. Confirmado contra Service Layer real:
|
||||
la respuesta viene en "value", cada item con "Series" (código) y
|
||||
"Name"; "Locked" en "tYES"/"tNO".
|
||||
SeriesService_GetDocumentSeries. Confirmado contra el HANA/Service Layer
|
||||
real de tagumedica: la respuesta viene en "value", cada item con
|
||||
"Series" (código) y "Name"; "Locked" en "tYES"/"tNO".
|
||||
"""
|
||||
response = forward_to_sapb1(
|
||||
method="POST",
|
||||
|
||||
@@ -1,13 +1,31 @@
|
||||
{
|
||||
"admin.demo@empresa.com": [
|
||||
"renato.ortega@tagumedica.com": [
|
||||
"*"
|
||||
],
|
||||
"ventas.demo@empresa.com": [
|
||||
"/ventas/*",
|
||||
"/socios/clientes"
|
||||
"rodrigo.catari@tagumedica.com": [
|
||||
"/inventario/*"
|
||||
],
|
||||
"inventario.demo@empresa.com": [
|
||||
"jose.huayta@tagumedica.com": [
|
||||
"/inventario/*",
|
||||
"/ventas/*",
|
||||
"/compras/*"
|
||||
],
|
||||
"ricardo.merino@tagumedica.com": [
|
||||
"/socios/*"
|
||||
],
|
||||
"renato.bustamante@tagumedica.com": [
|
||||
"/inventario/articulos",
|
||||
"/inventario/lotes"
|
||||
"/inventario/lotes",
|
||||
"/inventario/inmovilizar-lotes",
|
||||
"/inventario/liberar-lotes",
|
||||
"/inventario/confirmar-liberacion-lote",
|
||||
"/ventas/*",
|
||||
"/compras/*"
|
||||
],
|
||||
"vania.barrios@tagumedica.com":[
|
||||
"/inventario/lotes",
|
||||
"/inventario/inmovilizar-lotes",
|
||||
"/inventario/liberar-lotes",
|
||||
"/inventario/confirmar-liberacion-lote"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,8 @@ logger = logging.getLogger(__name__)
|
||||
# Stock de un lote por almacén. OBTN es el maestro de lotes: cada DistNumber
|
||||
# (número de lote) tiene un AbsEntry propio. OBTQ guarda la cantidad actual
|
||||
# por almacén, pero se enlaza a OBTN por "MdAbsEntry" = OBTN."AbsEntry" (no
|
||||
# por DistNumber ni ItemCode directamente). Confirmado contra HANA real.
|
||||
# por DistNumber ni ItemCode directamente). Confirmado contra el HANA real
|
||||
# de tagumedica con el lote 2090456 (AbsEntry 74701).
|
||||
BATCH_STOCK_QUERY = f"""
|
||||
SELECT
|
||||
T1."WhsCode" AS "WarehouseCode",
|
||||
|
||||
@@ -8,11 +8,14 @@ router = APIRouter(tags=["Tablas de Usuario"])
|
||||
|
||||
# Mapea un nombre amigable de tabla de usuario (@...) a su nombre real de
|
||||
# entidad en Service Layer. La convención de nombre no es uniforme entre
|
||||
# tablas de un mismo cliente (una tabla de usuario puede exponerse con
|
||||
# prefijo "U_" y otra sin él), así que se centraliza acá en vez de que cada
|
||||
# módulo tenga que adivinar o repetir el nombre de endpoint real. Cada
|
||||
# cliente completa este mapeo según sus propias tablas de usuario en SAP.
|
||||
USER_TABLES: Dict[str, str] = {}
|
||||
# tablas (confirmado contra el SAP real de tagumedica: @SIS_MOVINV se expone
|
||||
# como "U_SIS_MOVINV", pero @EXX_TIPOOPER se expone como "EXX_TIPOOPER", sin
|
||||
# prefijo "U_"), así que se centraliza acá en vez de que cada módulo tenga
|
||||
# que adivinar o repetir el nombre de endpoint real.
|
||||
USER_TABLES: Dict[str, str] = {
|
||||
"MovimientoInventario": "U_SIS_MOVINV",
|
||||
"TipoOperacion": "EXX_TIPOOPER",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/UserTables/{name}")
|
||||
|
||||
@@ -98,7 +98,7 @@
|
||||
<div class="pagina">
|
||||
{% for sticker in pagina %}
|
||||
<div class="sticker">
|
||||
<div class="titulo">EMPRESA</div>
|
||||
<div class="titulo">TAGUMEDICA</div>
|
||||
|
||||
<div class="campo">
|
||||
<div class="campo-label">DATOS DEL CLIENTE:</div>
|
||||
|
||||
@@ -4,15 +4,15 @@ info:
|
||||
|
||||
http:
|
||||
method: POST
|
||||
url: https://<host>:60000/login
|
||||
url: https://192.168.1.175:60000/login
|
||||
body:
|
||||
type: json
|
||||
data: |-
|
||||
{
|
||||
"CompanyDB":"<CompanyDB>",
|
||||
"CompanyDB":"SBO_TAGUMEDICA_21",
|
||||
"UserName": "manager",
|
||||
"Password": "<password>",
|
||||
"DBInstance":"NDB@<host>:30013"
|
||||
"Password": "m1r1",
|
||||
"DBInstance":"NDB@192.168.1.175:30013"
|
||||
}
|
||||
auth: inherit
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
@url=https://192.168.1.175:50000/b1s/v2
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
POST {{url}}/Login HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"CompanyDB": "SBO_TAGUMEDICA_21",
|
||||
"UserName": "manager",
|
||||
"Password": "m1r1"
|
||||
}
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/$metadata
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/EmployeesInfo?$select=EmployeeID,FirstName,LastName,Active,U_WEB_USER,U_WEB_PASS&$filter=U_WEB_USER eq 'renato.ortega@tagumedica.com'
|
||||
Content-Type: application/json
|
||||
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/Items?$top=20&$orderby=ItemCode desc
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/DeliveryNotes(29360)
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/UserFieldsMD?$filter=TableName eq 'OWTQ' and Name eq 'SIS_TIPDESP'
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/Warehouses
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/PurchaseInvoices(135235)
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/Orders?$filter=DocumentStatus eq 'bost_Open'
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
POST {{url}}/MessagesService_GetInbox HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/Messages(173810)
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/ItemGroups?$select=Number,GroupName
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
POST {{url}}/FactoringIndicators?$select=IndicatorCode,IndicatorName&$filter=U_EXX_REGVEN eq 'Y'
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/Currencies
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
GET {{url}}/BatchNumberDetails
|
||||
Content-Type: application/json
|
||||
|
||||
|
||||
###
|
||||
# @noRejectUnauthorized
|
||||
POST {{url}}/SeriesService_GetSeries
|
||||
Content-Type: application/json
|
||||
{
|
||||
"SeriesParams": {}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,15 @@ const BatchNumberDetailsList = lazy(
|
||||
const BatchNumberDetails = lazy(
|
||||
() => import("./views/inventario/BatchNumberDetailsView"),
|
||||
);
|
||||
const InmovilizarLotes = lazy(
|
||||
() => import("./views/inventario/InmovilizarLotesView"),
|
||||
);
|
||||
const LiberarLotes = lazy(
|
||||
() => import("./views/inventario/LiberarLotesView"),
|
||||
);
|
||||
const ConfirmarLiberacionLote = lazy(
|
||||
() => import("./views/inventario/ConfirmarLiberacionLoteView"),
|
||||
);
|
||||
|
||||
// 2. Socios de Negocios
|
||||
const CustomersList = lazy(() => import("./views/socios/CustomersList"));
|
||||
@@ -131,6 +140,18 @@ export default function App() {
|
||||
path="inventario/lotes/mantenimiento"
|
||||
element={<BatchNumberDetails />}
|
||||
/>
|
||||
<Route
|
||||
path="inventario/inmovilizar-lotes"
|
||||
element={<InmovilizarLotes />}
|
||||
/>
|
||||
<Route
|
||||
path="inventario/liberar-lotes"
|
||||
element={<LiberarLotes />}
|
||||
/>
|
||||
<Route
|
||||
path="inventario/confirmar-liberacion-lote"
|
||||
element={<ConfirmarLiberacionLote />}
|
||||
/>
|
||||
|
||||
{/* 2. Socios de Negocios */}
|
||||
<Route path="socios/clientes" element={<CustomersList />} />
|
||||
|
||||
@@ -13,7 +13,6 @@ import SelectField from "./ui/SelectField";
|
||||
import PrimaryButton from "./ui/PrimaryButton";
|
||||
import SecondaryButton from "./ui/SecondaryButton";
|
||||
import PageLoader from "./ui/PageLoader";
|
||||
import FieldTooltip from "./ui/FieldTooltip";
|
||||
|
||||
interface BatchFormProps {
|
||||
batchId: string;
|
||||
@@ -37,6 +36,9 @@ export default function BatchForm({ batchId, backPath }: BatchFormProps) {
|
||||
U_SIS_OBSER: "Observaciones",
|
||||
U_SIS_ESTLIB: "EstadoLiberacion",
|
||||
U_SIS_HORAPROB: "HoraAprobacion",
|
||||
U_SIS_MOTEST: "MotivoEstado",
|
||||
U_SIS_COMEST: "ComentarioEstado",
|
||||
U_SIS_ACCTOM: "AccionATomar"
|
||||
};
|
||||
|
||||
function mapSapToFriendly(raw: Record<string, any>): BatchNumberDetail {
|
||||
@@ -102,6 +104,9 @@ export default function BatchForm({ batchId, backPath }: BatchFormProps) {
|
||||
U_SIS_OBSER: batch.Observaciones,
|
||||
U_SIS_ESTLIB: batch.EstadoLiberacion,
|
||||
U_SIS_HORAPROB: batch.HoraAprobacion,
|
||||
U_SIS_MOTEST: batch.MotivoEstado,
|
||||
U_SIS_COMEST: batch.ComentarioEstado,
|
||||
U_SIS_ACCTOM: batch.AccionATomar
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -286,12 +291,44 @@ export default function BatchForm({ batchId, backPath }: BatchFormProps) {
|
||||
name="HoraAprobacion"
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Motivo de Estado"
|
||||
dbField="U_SIS_MOTEST"
|
||||
value={batch.MotivoEstado}
|
||||
mode="input"
|
||||
name="MotivoEstado"
|
||||
onChange={handleChange}
|
||||
multiline
|
||||
rows={3}
|
||||
/>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Comentario de Estado"
|
||||
dbField="U_SIS_COMEST"
|
||||
value={batch.ComentarioEstado}
|
||||
mode="input"
|
||||
name="ComentarioEstado"
|
||||
onChange={handleChange}
|
||||
multiline
|
||||
rows={3}
|
||||
/>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Acción a tomar"
|
||||
dbField="U_SIS_ACCTOM"
|
||||
value={batch.AccionATomar}
|
||||
mode="input"
|
||||
name="AccionATomar"
|
||||
onChange={handleChange}
|
||||
multiline
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="p-3 bg-[var(--color-bg)] border border-[var(--color-border)]">
|
||||
{/* <div className="p-3 bg-[var(--color-bg)] border border-[var(--color-border)]">
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1">
|
||||
Detalles / Observaciones
|
||||
<FieldTooltip text="Details" />
|
||||
Detalles / Observaciones (Details)
|
||||
</label>
|
||||
<textarea
|
||||
name="Details"
|
||||
@@ -300,7 +337,7 @@ export default function BatchForm({ batchId, backPath }: BatchFormProps) {
|
||||
rows={3}
|
||||
className="w-full px-2 py-1.5 border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div> */}
|
||||
|
||||
<div className="flex justify-end pt-4 border-t border-[var(--color-border-light)] space-x-2">
|
||||
<SecondaryButton type="button" onClick={() => navigate(backPath)}>
|
||||
|
||||
@@ -27,6 +27,9 @@ const menuConfig: MenuItem[] = [
|
||||
subItems: [
|
||||
{ name: "Articulos", path: "/inventario/articulos" },
|
||||
{ name: "Lotes", path: "/inventario/lotes" },
|
||||
{ name: "Inmovilizar Lotes", path: "/inventario/inmovilizar-lotes" },
|
||||
{ name: "Liberar Lotes", path: "/inventario/liberar-lotes" },
|
||||
{ name: "Confirmar Liberación Lote", path: "/inventario/confirmar-liberacion-lote" },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -17,4 +17,7 @@ export interface BatchNumberDetail {
|
||||
Observaciones?: string;
|
||||
EstadoLiberacion?: string;
|
||||
HoraAprobacion?: string;
|
||||
MotivoEstado?: string;
|
||||
ComentarioEstado? : string;
|
||||
AccionATomar? : string;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
export interface BatchWarehouseStock {
|
||||
WarehouseCode: string;
|
||||
WarehouseName: string;
|
||||
Quantity: number;
|
||||
CommitQty: number;
|
||||
CountQty: number;
|
||||
ItemCode: string;
|
||||
ItemDescription?: string;
|
||||
}
|
||||
|
||||
export interface BatchStockResponse {
|
||||
Batch: string;
|
||||
Warehouses: BatchWarehouseStock[];
|
||||
}
|
||||
|
||||
export interface SeriesOption {
|
||||
Series: number;
|
||||
Name: string;
|
||||
}
|
||||
|
||||
export interface SeriesListResponse {
|
||||
Default?: number;
|
||||
Options: SeriesOption[];
|
||||
}
|
||||
|
||||
// Shape que espera SAP Service Layer para crear una Solicitud de
|
||||
// Transferencia de Inventario (entidad "InventoryTransferRequests"). El
|
||||
// frontend arma este JSON completo (incluyendo los campos de usuario U_*) y
|
||||
// lo manda directo a /api/InventoryTransferRequests: el backend no lo
|
||||
// transforma ni lo valida, solo lo reenvía a SAP.
|
||||
export interface StockTransferLineBatchNumber {
|
||||
BatchNumber: string;
|
||||
Quantity: number;
|
||||
}
|
||||
|
||||
export interface StockTransferLine {
|
||||
ItemCode: string;
|
||||
Quantity: number;
|
||||
WarehouseCode: string;
|
||||
FromWarehouseCode: string;
|
||||
BatchNumbers: StockTransferLineBatchNumber[];
|
||||
}
|
||||
|
||||
export interface InventoryTransferRequestPayload {
|
||||
DocDate: string;
|
||||
Series: number;
|
||||
U_SIS_MOVINV: string;
|
||||
U_EXX_TIPOOPER: string;
|
||||
U_SIS_TIPDESP: string;
|
||||
U_SIS_MOTALM: string;
|
||||
U_SIS_MOTEST: string;
|
||||
U_SIS_COMEST: string;
|
||||
U_SIS_ACCTOM: string;
|
||||
StockTransferLines: StockTransferLine[];
|
||||
}
|
||||
|
||||
// Shape que devuelve SAP Service Layer al leer una Solicitud de
|
||||
// Transferencia de Inventario ya creada (GET /api/InventoryTransferRequests).
|
||||
// A diferencia de StockTransferLine (lo que se envía al crear), acá SAP
|
||||
// agrega "LineNum" a cada línea; "ItemDescription" no viene en la línea, hay
|
||||
// que resolverla aparte por ItemCode (ver Items).
|
||||
export interface StockTransferLineDetail {
|
||||
LineNum: number;
|
||||
ItemCode: string;
|
||||
Quantity: number;
|
||||
WarehouseCode: string;
|
||||
FromWarehouseCode: string;
|
||||
BatchNumbers?: StockTransferLineBatchNumber[];
|
||||
}
|
||||
|
||||
export interface InventoryTransferRequestSummary {
|
||||
DocEntry: number;
|
||||
DocNum: number;
|
||||
DocDate: string;
|
||||
DocumentStatus: string;
|
||||
U_SIS_MOTALM?: string;
|
||||
StockTransferLines: StockTransferLineDetail[];
|
||||
}
|
||||
|
||||
// Respuesta de /api/batch/lot-source-warehouse: para cada Artículo+Lote, la
|
||||
// cantidad se reparte entre los almacenes de los que realmente salió antes
|
||||
// de llegar al almacén donde está hoy inmovilizado (resuelto contra el
|
||||
// historial de transferencias en HANA). Puede haber más de una asignación
|
||||
// si el lote llegó en transferencias distintas desde almacenes distintos;
|
||||
// Allocations viene vacío si no se encontró ninguna transferencia de
|
||||
// ingreso (OWTR) para ese lote.
|
||||
export interface LotSourceAllocation {
|
||||
WarehouseCode: string;
|
||||
Quantity: number;
|
||||
}
|
||||
|
||||
export interface LotSourceWarehouseResult {
|
||||
ItemCode: string;
|
||||
DistNumber: string;
|
||||
Allocations: LotSourceAllocation[];
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { API_URL, apiFetch } from "../../utils/api";
|
||||
import { getErrorMessage } from "../../utils/errors";
|
||||
import { formatDisplayDate } from "../../utils/dateFormat";
|
||||
import Icon from "../../components/ui/Icon";
|
||||
import PrimaryButton from "../../components/ui/PrimaryButton";
|
||||
import ModalSearchTemplate from "../../components/ui/ModalSearchTemplate";
|
||||
import type {
|
||||
InventoryTransferRequestSummary,
|
||||
LotSourceWarehouseResult,
|
||||
StockTransferLineDetail,
|
||||
} from "../../types/sapInventoryLock";
|
||||
|
||||
// "108" es el mismo código de U_SIS_MOTALM que "Liberar Lotes" manda por
|
||||
// defecto al crear la Solicitud de Transferencia: identifica los documentos
|
||||
// que quedaron pendientes de confirmar la liberación. Fijo a propósito, no
|
||||
// es un valor que el usuario deba elegir acá.
|
||||
const PENDING_MOVIMIENTO_ALMACEN = "108";
|
||||
const OPEN_REQUESTS_FILTER = `DocumentStatus eq 'bost_Open' and U_SIS_MOTALM eq '${PENDING_MOVIMIENTO_ALMACEN}'`;
|
||||
|
||||
interface LineBatchRow {
|
||||
key: string;
|
||||
LineNum: number;
|
||||
ItemCode: string;
|
||||
Quantity: number;
|
||||
BatchNumber: string;
|
||||
WarehouseCode: string;
|
||||
}
|
||||
|
||||
// Cada línea trae su(s) número(s) de lote en BatchNumbers; se muestra una
|
||||
// fila de subdetalle por cada combinación línea+lote (normalmente una sola).
|
||||
function lineBatchRows(lines: StockTransferLineDetail[]): LineBatchRow[] {
|
||||
const rows: LineBatchRow[] = [];
|
||||
for (const line of lines) {
|
||||
const batches = line.BatchNumbers?.length ? line.BatchNumbers : [{ BatchNumber: "-", Quantity: line.Quantity }];
|
||||
batches.forEach((batch, index) => {
|
||||
rows.push({
|
||||
key: `${line.LineNum}-${index}`,
|
||||
LineNum: line.LineNum,
|
||||
ItemCode: line.ItemCode,
|
||||
Quantity: batch.Quantity,
|
||||
BatchNumber: batch.BatchNumber,
|
||||
WarehouseCode: line.WarehouseCode,
|
||||
});
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Una fila editable del detalle de liberación: a qué almacén y con qué
|
||||
// cantidad vuelve una porción del lote. El usuario puede agregar, quitar o
|
||||
// editar estas filas antes de confirmar (además de lo que se precarga
|
||||
// resolviendo contra el historial de transferencias en HANA).
|
||||
interface DraftAllocation {
|
||||
rowId: number;
|
||||
WarehouseCode: string;
|
||||
WarehouseName: string;
|
||||
Quantity: string;
|
||||
}
|
||||
|
||||
interface DraftLine {
|
||||
LineNum: number;
|
||||
ItemCode: string;
|
||||
DistNumber: string;
|
||||
FromWarehouseCode: string;
|
||||
allocations: DraftAllocation[];
|
||||
}
|
||||
|
||||
export default function ConfirmarLiberacionLoteView() {
|
||||
const [requests, setRequests] = useState<InventoryTransferRequestSummary[]>([]);
|
||||
const [itemNames, setItemNames] = useState<Record<string, string>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState("");
|
||||
const [selectedDocEntry, setSelectedDocEntry] = useState<number | null>(null);
|
||||
|
||||
const [resolving, setResolving] = useState(false);
|
||||
const [resolveError, setResolveError] = useState("");
|
||||
const [draftLines, setDraftLines] = useState<DraftLine[] | null>(null);
|
||||
const nextRowIdRef = useRef(0);
|
||||
const [warehousePickerTarget, setWarehousePickerTarget] = useState<{
|
||||
lineNum: number;
|
||||
rowId: number;
|
||||
} | null>(null);
|
||||
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [confirmError, setConfirmError] = useState("");
|
||||
const [confirmSuccess, setConfirmSuccess] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const fetchRequests = async () => {
|
||||
setLoading(true);
|
||||
setLoadError("");
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`${API_URL}/api/InventoryTransferRequests?filter=${encodeURIComponent(
|
||||
OPEN_REQUESTS_FILTER,
|
||||
)}&orderby=${encodeURIComponent("DocEntry desc")}&top=200`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new Error(data?.detail || "Error al obtener las solicitudes de transferencia");
|
||||
}
|
||||
const data = await response.json();
|
||||
const summaries: InventoryTransferRequestSummary[] = data.value ?? [];
|
||||
|
||||
// SAP Service Layer no devuelve BatchNumbers (ni otros datos de
|
||||
// línea) completos en una consulta de lista: solo un GET directo
|
||||
// por DocEntry trae el documento completo con sus lotes. Por eso,
|
||||
// después de listar, se vuelve a pedir cada solicitud por su clave.
|
||||
const fullRequests = await Promise.all(
|
||||
summaries.map(async (summary) => {
|
||||
try {
|
||||
const detailResponse = await apiFetch(
|
||||
`${API_URL}/api/InventoryTransferRequests/${summary.DocEntry}`,
|
||||
);
|
||||
if (!detailResponse.ok) return summary;
|
||||
return (await detailResponse.json()) as InventoryTransferRequestSummary;
|
||||
} catch {
|
||||
return summary;
|
||||
}
|
||||
}),
|
||||
);
|
||||
const value = fullRequests;
|
||||
setRequests(value);
|
||||
setSelectedDocEntry(null);
|
||||
|
||||
// La descripción del artículo no viene en StockTransferLines: se
|
||||
// resuelve aparte por ItemCode, una sola vez por código distinto.
|
||||
const itemCodes = Array.from(
|
||||
new Set(value.flatMap((req) => req.StockTransferLines.map((l) => l.ItemCode))),
|
||||
);
|
||||
const entries = await Promise.all(
|
||||
itemCodes.map(async (code) => {
|
||||
try {
|
||||
const itemResponse = await apiFetch(
|
||||
`${API_URL}/api/Items/${encodeURIComponent(code)}?fields=ItemCode,ItemName`,
|
||||
);
|
||||
if (!itemResponse.ok) return null;
|
||||
const item = await itemResponse.json();
|
||||
return [code, item.ItemName ?? code] as const;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
setItemNames(Object.fromEntries(entries.filter((e): e is [string, string] => e !== null)));
|
||||
} catch (err: unknown) {
|
||||
setLoadError(getErrorMessage(err, "Error al obtener las solicitudes de transferencia"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchRequests();
|
||||
}, []);
|
||||
|
||||
const selectedRequest = requests.find((req) => req.DocEntry === selectedDocEntry) ?? null;
|
||||
|
||||
// Apenas se selecciona una solicitud, se averigua contra HANA de qué
|
||||
// almacén(es) vino realmente cada lote (puede ser más de uno, si llegó al
|
||||
// almacén actual en transferencias distintas), repartiendo la cantidad de
|
||||
// cada línea entre ellos. El resultado se arma como filas editables: si
|
||||
// para alguna línea no se encuentra transferencia de ingreso, queda sin
|
||||
// filas y el usuario agrega el almacén manualmente.
|
||||
useEffect(() => {
|
||||
setDraftLines(null);
|
||||
setResolveError("");
|
||||
setConfirmError("");
|
||||
setConfirmSuccess("");
|
||||
|
||||
if (!selectedRequest) return;
|
||||
|
||||
const resolveDestinations = async () => {
|
||||
setResolving(true);
|
||||
try {
|
||||
const lines = selectedRequest.StockTransferLines.map((line) => ({
|
||||
LineNum: line.LineNum,
|
||||
ItemCode: line.ItemCode,
|
||||
DistNumber: line.BatchNumbers?.[0]?.BatchNumber ?? "",
|
||||
Warehouse: line.FromWarehouseCode,
|
||||
Quantity: line.Quantity,
|
||||
}));
|
||||
|
||||
const response = await apiFetch(`${API_URL}/api/batch/lot-source-warehouse`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
Lines: lines.map(({ ItemCode, DistNumber, Warehouse, Quantity }) => ({
|
||||
ItemCode,
|
||||
DistNumber,
|
||||
Warehouse,
|
||||
Quantity,
|
||||
})),
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new Error(data?.detail || "Error al buscar el almacén de origen de los lotes");
|
||||
}
|
||||
const results: LotSourceWarehouseResult[] = await response.json();
|
||||
|
||||
setDraftLines(
|
||||
lines.map((line, index) => ({
|
||||
LineNum: line.LineNum,
|
||||
ItemCode: line.ItemCode,
|
||||
DistNumber: line.DistNumber,
|
||||
FromWarehouseCode: line.Warehouse,
|
||||
allocations: results[index].Allocations.map((allocation) => ({
|
||||
rowId: nextRowIdRef.current++,
|
||||
WarehouseCode: allocation.WarehouseCode,
|
||||
WarehouseName: "",
|
||||
Quantity: String(allocation.Quantity),
|
||||
})),
|
||||
})),
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
setResolveError(
|
||||
getErrorMessage(err, "Error al buscar el almacén de origen de los lotes"),
|
||||
);
|
||||
} finally {
|
||||
setResolving(false);
|
||||
}
|
||||
};
|
||||
resolveDestinations();
|
||||
}, [selectedDocEntry]);
|
||||
|
||||
const addAllocationRow = (lineNum: number) => {
|
||||
setDraftLines(
|
||||
(prev) =>
|
||||
prev?.map((line) =>
|
||||
line.LineNum === lineNum
|
||||
? {
|
||||
...line,
|
||||
allocations: [
|
||||
...line.allocations,
|
||||
{ rowId: nextRowIdRef.current++, WarehouseCode: "", WarehouseName: "", Quantity: "" },
|
||||
],
|
||||
}
|
||||
: line,
|
||||
) ?? null,
|
||||
);
|
||||
};
|
||||
|
||||
const removeAllocationRow = (lineNum: number, rowId: number) => {
|
||||
setDraftLines(
|
||||
(prev) =>
|
||||
prev?.map((line) =>
|
||||
line.LineNum === lineNum
|
||||
? { ...line, allocations: line.allocations.filter((a) => a.rowId !== rowId) }
|
||||
: line,
|
||||
) ?? null,
|
||||
);
|
||||
};
|
||||
|
||||
const updateAllocationQuantity = (lineNum: number, rowId: number, value: string) => {
|
||||
setDraftLines(
|
||||
(prev) =>
|
||||
prev?.map((line) =>
|
||||
line.LineNum === lineNum
|
||||
? {
|
||||
...line,
|
||||
allocations: line.allocations.map((a) =>
|
||||
a.rowId === rowId ? { ...a, Quantity: value } : a,
|
||||
),
|
||||
}
|
||||
: line,
|
||||
) ?? null,
|
||||
);
|
||||
};
|
||||
|
||||
const handleWarehouseSeleccionado = (rows: any[]) => {
|
||||
if (rows.length === 0 || !warehousePickerTarget) return;
|
||||
const { lineNum, rowId } = warehousePickerTarget;
|
||||
setDraftLines(
|
||||
(prev) =>
|
||||
prev?.map((line) =>
|
||||
line.LineNum === lineNum
|
||||
? {
|
||||
...line,
|
||||
allocations: line.allocations.map((a) =>
|
||||
a.rowId === rowId
|
||||
? { ...a, WarehouseCode: rows[0].WarehouseCode, WarehouseName: rows[0].WarehouseName }
|
||||
: a,
|
||||
),
|
||||
}
|
||||
: line,
|
||||
) ?? null,
|
||||
);
|
||||
setWarehousePickerTarget(null);
|
||||
};
|
||||
|
||||
const hasIncompleteRows = Boolean(
|
||||
draftLines?.some((line) =>
|
||||
line.allocations.some(
|
||||
(a) => !a.WarehouseCode || a.Quantity.trim() === "" || Number(a.Quantity) <= 0,
|
||||
),
|
||||
),
|
||||
);
|
||||
const hasAnyAllocation = Boolean(draftLines?.some((line) => line.allocations.length > 0));
|
||||
|
||||
// El botón actualiza directo la Solicitud de Transferencia en SAP (PATCH)
|
||||
// con las filas armadas/editadas por el usuario. Una línea con una sola
|
||||
// fila se actualiza en el lugar (mismo LineNum); una línea con varias
|
||||
// filas se reemplaza por varias líneas: la primera reusa el LineNum
|
||||
// original, las siguientes van sin LineNum para que SAP las agregue como
|
||||
// líneas nuevas. Una línea sin filas (el usuario borró todas) se elimina
|
||||
// del documento.
|
||||
const handleConfirmApply = async () => {
|
||||
if (!selectedRequest || !draftLines) return;
|
||||
setConfirming(true);
|
||||
setConfirmError("");
|
||||
try {
|
||||
const updatedLines = draftLines.flatMap((line) =>
|
||||
line.allocations.map((allocation, index) => ({
|
||||
...(index === 0 ? { LineNum: line.LineNum } : {}),
|
||||
ItemCode: line.ItemCode,
|
||||
Quantity: Number(allocation.Quantity),
|
||||
WarehouseCode: allocation.WarehouseCode,
|
||||
FromWarehouseCode: line.FromWarehouseCode,
|
||||
BatchNumbers: [{ BatchNumber: line.DistNumber, Quantity: Number(allocation.Quantity) }],
|
||||
})),
|
||||
);
|
||||
|
||||
// Se puede estar agregando o quitando líneas (repartir una línea
|
||||
// entre varios almacenes destino), así que Service Layer debe
|
||||
// reemplazar StockTransferLines entero en vez de mergearlo por
|
||||
// LineNum con lo que ya tenía el documento. El backend reenvía tal
|
||||
// cual cualquier header B1S-* que se mande acá.
|
||||
const response = await apiFetch(
|
||||
`${API_URL}/api/InventoryTransferRequests/${selectedRequest.DocEntry}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: { "B1S-ReplaceCollectionsOnPatch": "true" },
|
||||
body: JSON.stringify({ StockTransferLines: updatedLines }),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new Error(data?.detail || "Error al actualizar la Solicitud de Transferencia");
|
||||
}
|
||||
|
||||
// Se vuelve a pedir la solicitud actualizada en vez de simular las
|
||||
// líneas localmente: SAP es quien asigna los LineNum definitivos de
|
||||
// las líneas nuevas que se agregaron por el reparto.
|
||||
const refreshed = await apiFetch(
|
||||
`${API_URL}/api/InventoryTransferRequests/${selectedRequest.DocEntry}`,
|
||||
);
|
||||
if (refreshed.ok) {
|
||||
const refreshedData: InventoryTransferRequestSummary = await refreshed.json();
|
||||
setRequests((prev) =>
|
||||
prev.map((req) => (req.DocEntry === selectedRequest.DocEntry ? refreshedData : req)),
|
||||
);
|
||||
}
|
||||
setConfirmSuccess(
|
||||
`Solicitud #${selectedRequest.DocNum} actualizada con los almacenes destino correctos.`,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
setConfirmError(
|
||||
getErrorMessage(err, "Error al actualizar la Solicitud de Transferencia"),
|
||||
);
|
||||
} finally {
|
||||
setConfirming(false);
|
||||
setDraftLines(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 bg-[var(--color-surface)] h-full flex flex-col font-sans select-none text-xs text-[var(--color-text)] overflow-auto">
|
||||
<div className="mb-4 border-b border-[var(--color-border-light)] pb-2">
|
||||
<h1 className="text-base font-semibold text-[var(--color-sidebar-title)] flex items-center gap-2">
|
||||
<Icon name="clipboard" className="w-4 h-4" />
|
||||
Confirmar Liberación Lote
|
||||
</h1>
|
||||
<p className="text-[11px] text-[var(--color-text-muted)]">
|
||||
Solicitudes de Transferencia abiertas generadas por "Liberar Lotes", de la más reciente
|
||||
a la más antigua. Seleccione una para continuar.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{loadError && (
|
||||
<div className="mb-4 p-2 bg-[var(--color-error-bg)] border border-[var(--color-error-border)] text-[var(--color-error)]">
|
||||
{loadError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && (
|
||||
<div className="text-[var(--color-text-muted)]">Cargando solicitudes...</div>
|
||||
)}
|
||||
|
||||
{!loading && !loadError && requests.length === 0 && (
|
||||
<div className="text-[var(--color-text-muted)]">
|
||||
No hay Solicitudes de Transferencia abiertas pendientes de confirmar liberación.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && requests.length > 0 && (
|
||||
<div className="space-y-3 mb-4">
|
||||
{requests.map((req) => {
|
||||
const isSelected = req.DocEntry === selectedDocEntry;
|
||||
return (
|
||||
<div
|
||||
key={req.DocEntry}
|
||||
onClick={() => setSelectedDocEntry(req.DocEntry)}
|
||||
className={`p-3 border cursor-pointer ${
|
||||
isSelected
|
||||
? "border-[var(--color-primary)] bg-[var(--color-primary-active)]"
|
||||
: "border-[var(--color-border)] bg-[var(--color-bg)] hover:bg-[var(--color-sidebar-hover)]"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<input
|
||||
type="radio"
|
||||
name="solicitud"
|
||||
checked={isSelected}
|
||||
onChange={() => setSelectedDocEntry(req.DocEntry)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<Icon name="document" className="w-4 h-4 shrink-0" />
|
||||
<span className="font-semibold text-[var(--color-sidebar-title)]">
|
||||
Solicitud #{req.DocNum}
|
||||
</span>
|
||||
<span className="text-[11px] text-[var(--color-text-muted)]">
|
||||
Fecha: {formatDisplayDate(req.DocDate)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="pl-6 border-l border-[var(--color-sidebar-submenu-border)] ml-2 overflow-x-auto">
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr className="text-[11px] text-[var(--color-text-muted)] border-b border-[var(--color-border)]">
|
||||
<th className="text-left py-1 px-2">Artículo</th>
|
||||
<th className="text-left py-1 px-2">Descripción</th>
|
||||
<th className="text-right py-1 px-2">Cantidad</th>
|
||||
<th className="text-left py-1 px-2">Número de Lote</th>
|
||||
<th className="text-left py-1 px-2">Almacén destino</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{lineBatchRows(req.StockTransferLines).map((row) => (
|
||||
<tr
|
||||
key={row.key}
|
||||
className="border-b border-[var(--color-border-light)]"
|
||||
>
|
||||
<td className="py-1.5 px-2">{row.ItemCode}</td>
|
||||
<td className="py-1.5 px-2">
|
||||
{itemNames[row.ItemCode] ?? row.ItemCode}
|
||||
</td>
|
||||
<td className="py-1.5 px-2 text-right font-mono">
|
||||
{row.Quantity} UND
|
||||
</td>
|
||||
<td className="py-1.5 px-2">{row.BatchNumber}</td>
|
||||
<td className="py-1.5 px-2">{row.WarehouseCode}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{isSelected && (
|
||||
<div
|
||||
className="mt-3 pt-3 border-t border-[var(--color-border-light)] space-y-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{resolving && (
|
||||
<div className="text-[var(--color-text-muted)]">
|
||||
Buscando en el historial de transferencias de qué almacén(es) salió cada
|
||||
lote...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{resolveError && (
|
||||
<div className="p-2 bg-[var(--color-error-bg)] border border-[var(--color-error-border)] text-[var(--color-error)]">
|
||||
{resolveError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{draftLines && (
|
||||
<div className="space-y-3">
|
||||
<p className="text-[var(--color-text-muted)]">
|
||||
Así va a quedar la Solicitud al confirmar. Puede editar la cantidad,
|
||||
cambiar el almacén destino, agregar o quitar filas por artículo/lote
|
||||
antes de confirmar:
|
||||
</p>
|
||||
{draftLines.map((line) => (
|
||||
<div
|
||||
key={line.LineNum}
|
||||
className="pl-6 border-l border-[var(--color-sidebar-submenu-border)] ml-2"
|
||||
>
|
||||
<div className="text-[11px] text-[var(--color-text-muted)] mb-1">
|
||||
{line.ItemCode} - Lote {line.DistNumber || "(sin lote)"}
|
||||
{line.allocations.length === 0 && (
|
||||
<span className="text-[var(--color-error)]">
|
||||
{" "}
|
||||
· No se encontró transferencia de ingreso; agregue el almacén
|
||||
destino manualmente.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr className="text-[11px] text-[var(--color-text-muted)] border-b border-[var(--color-border)]">
|
||||
<th className="text-right py-1 px-2 w-28">Cantidad</th>
|
||||
<th className="text-left py-1 px-2">Almacén destino</th>
|
||||
<th className="py-1 px-2 w-8"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{line.allocations.map((allocation) => (
|
||||
<tr
|
||||
key={allocation.rowId}
|
||||
className="border-b border-[var(--color-border-light)]"
|
||||
>
|
||||
<td className="py-1.5 px-2 text-right">
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="any"
|
||||
value={allocation.Quantity}
|
||||
onChange={(e) =>
|
||||
updateAllocationQuantity(
|
||||
line.LineNum,
|
||||
allocation.rowId,
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
className="w-24 px-2 h-[26px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs text-right"
|
||||
/>
|
||||
</td>
|
||||
<td className="py-1.5 px-2">
|
||||
<div className="flex items-center border border-[var(--color-input-border)] bg-[var(--color-surface)] focus-within:border-[var(--color-input-focus)] max-w-xs">
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={
|
||||
allocation.WarehouseCode
|
||||
? `${allocation.WarehouseCode}${
|
||||
allocation.WarehouseName
|
||||
? ` - ${allocation.WarehouseName}`
|
||||
: ""
|
||||
}`
|
||||
: ""
|
||||
}
|
||||
placeholder="Seleccionar almacén..."
|
||||
onClick={() =>
|
||||
setWarehousePickerTarget({
|
||||
lineNum: line.LineNum,
|
||||
rowId: allocation.rowId,
|
||||
})
|
||||
}
|
||||
className="flex-1 min-w-0 h-[26px] px-2 border-none outline-none bg-transparent text-xs cursor-pointer"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setWarehousePickerTarget({
|
||||
lineNum: line.LineNum,
|
||||
rowId: allocation.rowId,
|
||||
})
|
||||
}
|
||||
className="h-[26px] px-1.5 bg-transparent border-none cursor-pointer text-[var(--color-primary)] shrink-0"
|
||||
title="Buscar almacén"
|
||||
>
|
||||
<Icon name="search" className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-1.5 px-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
removeAllocationRow(line.LineNum, allocation.rowId)
|
||||
}
|
||||
className="bg-transparent border-none cursor-pointer text-[var(--color-error)]"
|
||||
title="Quitar fila"
|
||||
>
|
||||
<Icon name="trash" className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => addAllocationRow(line.LineNum)}
|
||||
className="mt-1 bg-transparent border-none cursor-pointer text-[var(--color-primary)] text-[11px]"
|
||||
>
|
||||
+ Agregar almacén
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{confirmError && (
|
||||
<div className="p-2 bg-[var(--color-error-bg)] border border-[var(--color-error-border)] text-[var(--color-error)]">
|
||||
{confirmError}
|
||||
</div>
|
||||
)}
|
||||
{confirmSuccess && (
|
||||
<div className="p-2 bg-[var(--color-success-bg)] border border-[var(--color-success-border)] text-[var(--color-success)]">
|
||||
{confirmSuccess}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end">
|
||||
<PrimaryButton
|
||||
onClick={handleConfirmApply}
|
||||
size="md"
|
||||
disabled={
|
||||
resolving ||
|
||||
confirming ||
|
||||
!draftLines ||
|
||||
hasIncompleteRows ||
|
||||
!hasAnyAllocation
|
||||
}
|
||||
>
|
||||
{confirming ? "Actualizando..." : "Actualizar solicitud"}
|
||||
</PrimaryButton>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ModalSearchTemplate
|
||||
isOpen={!!warehousePickerTarget}
|
||||
onClose={() => setWarehousePickerTarget(null)}
|
||||
title="Buscar Almacén"
|
||||
endpoint="Warehouses"
|
||||
fields={["WarehouseCode", "WarehouseName"]}
|
||||
columns={[
|
||||
{ key: "WarehouseCode", title: "Código", width: "120px" },
|
||||
{ key: "WarehouseName", title: "Nombre" },
|
||||
]}
|
||||
baseFilter=""
|
||||
seleccion="unica"
|
||||
onConfirmarSeleccion={handleWarehouseSeleccionado}
|
||||
rowKey="WarehouseCode"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,723 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { API_URL, apiFetch } from "../../utils/api";
|
||||
import { getErrorMessage } from "../../utils/errors";
|
||||
import FormattedField from "../../components/ui/FormattedField";
|
||||
import PrimaryButton from "../../components/ui/PrimaryButton";
|
||||
import SecondaryButton from "../../components/ui/SecondaryButton";
|
||||
import Icon from "../../components/ui/Icon";
|
||||
import ModalSearchTemplate from "../../components/ui/ModalSearchTemplate";
|
||||
import ConfirmModal from "../../components/ui/ConfirmModal";
|
||||
import FieldTooltip from "../../components/ui/FieldTooltip";
|
||||
import { useSapCatalog } from "../../hooks/useSapCatalog";
|
||||
import type {
|
||||
BatchStockResponse,
|
||||
BatchWarehouseStock,
|
||||
InventoryTransferRequestPayload,
|
||||
SeriesOption,
|
||||
} from "../../types/sapInventoryLock";
|
||||
|
||||
const MOTIVO_MAX = 100;
|
||||
const TEXT_MAX = 254;
|
||||
// Almacén destino por defecto para inmovilizar (302 - INMOVILIZADOS DRO),
|
||||
// pedido explícitamente por el usuario. Es un valor fijo del frontend: no se
|
||||
// resuelve contra SAP, se manda directo en el JSON de la Solicitud de
|
||||
// Transferencia. El usuario puede cambiarlo igual con la lupa.
|
||||
const DEFAULT_TO_WAREHOUSE = { code: "302", name: "INMOVILIZADOS DRO" };
|
||||
// Código de objeto SAP B1 (BoObjectTypes) para Solicitud de Transferencia de
|
||||
// Inventario, usado para pedirle al endpoint genérico de series las suyas.
|
||||
const INVENTORY_TRANSFER_REQUEST_DOCUMENT_TYPE = "1250000001";
|
||||
// Valores por defecto pedidos explícitamente por el usuario para los campos
|
||||
// de usuario U_SIS_MOVINV, U_EXX_TIPOOPER, U_SIS_TIPDESP y U_SIS_MOTALM.
|
||||
const DEFAULT_MOVIMIENTO_INVENTARIO = "XTD";
|
||||
const DEFAULT_TIPO_OPERACION = "11";
|
||||
const DEFAULT_TIPO_DESPACHO = "N";
|
||||
const DEFAULT_MOVIMIENTO_ALMACEN = "107";
|
||||
|
||||
function today(): string {
|
||||
return new Date().toISOString().split("T")[0];
|
||||
}
|
||||
|
||||
interface ItemStockGroup {
|
||||
ItemCode: string;
|
||||
ItemDescription?: string;
|
||||
rows: BatchWarehouseStock[];
|
||||
}
|
||||
|
||||
// Un mismo número de lote puede repetirse en más de un artículo en SAP, así
|
||||
// que el árbol se arma por Artículo (no solo por Almacén).
|
||||
function groupByItem(warehouses: BatchWarehouseStock[]): ItemStockGroup[] {
|
||||
const groups: ItemStockGroup[] = [];
|
||||
for (const w of warehouses) {
|
||||
let group = groups.find((g) => g.ItemCode === w.ItemCode);
|
||||
if (!group) {
|
||||
group = { ItemCode: w.ItemCode, ItemDescription: w.ItemDescription, rows: [] };
|
||||
groups.push(group);
|
||||
}
|
||||
group.rows.push(w);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
// Identifica una fila de stock (Artículo + Almacén) para usarla como key de
|
||||
// selección: un mismo almacén puede repetirse en distintos artículos del lote.
|
||||
function rowKey(row: BatchWarehouseStock): string {
|
||||
return `${row.ItemCode}::${row.WarehouseCode}`;
|
||||
}
|
||||
|
||||
function quantityErrorFor(row: BatchWarehouseStock, rawQuantity: string): string {
|
||||
if (rawQuantity === "") return "";
|
||||
const quantityNumber = Number(rawQuantity);
|
||||
if (quantityNumber <= 0) return "La cantidad debe ser mayor a 0";
|
||||
if (quantityNumber > row.Quantity) {
|
||||
return `La cantidad no puede superar el stock disponible en el almacén (${row.Quantity})`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export default function InmovilizarLotesView() {
|
||||
const [batchInput, setBatchInput] = useState("");
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [searchError, setSearchError] = useState("");
|
||||
const [result, setResult] = useState<BatchStockResponse | null>(null);
|
||||
|
||||
// Selección múltiple: qué filas (Artículo + Almacén) están marcadas para
|
||||
// inmovilizar y qué cantidad tiene cada una, por rowKey.
|
||||
const [selections, setSelections] = useState<Record<string, string>>({});
|
||||
const [docDate, setDocDate] = useState(today());
|
||||
const [toWarehouse, setToWarehouse] = useState<{ code: string; name: string } | null>(null);
|
||||
const [isWarehouseModalOpen, setIsWarehouseModalOpen] = useState(false);
|
||||
const [seriesOptions, setSeriesOptions] = useState<SeriesOption[]>([]);
|
||||
const [defaultSeries, setDefaultSeries] = useState<number | "">("");
|
||||
const [series, setSeries] = useState<number | "">("");
|
||||
const [movimientoInventario, setMovimientoInventario] = useState(DEFAULT_MOVIMIENTO_INVENTARIO);
|
||||
const [tipoOperacion, setTipoOperacion] = useState(DEFAULT_TIPO_OPERACION);
|
||||
const [tipoDespacho, setTipoDespacho] = useState(DEFAULT_TIPO_DESPACHO);
|
||||
const [movimientoAlmacen, setMovimientoAlmacen] = useState(DEFAULT_MOVIMIENTO_ALMACEN);
|
||||
const { options: movimientoInventarioOptions } = useSapCatalog(
|
||||
"UserTables/MovimientoInventario",
|
||||
);
|
||||
const { options: tipoOperacionOptions } = useSapCatalog("UserTables/TipoOperacion");
|
||||
const { options: tipoDespachoOptions } = useSapCatalog("Catalogs/UdfValidValues", {
|
||||
table_name: "OWTQ",
|
||||
field_name: "SIS_TIPDESP",
|
||||
});
|
||||
const { options: movimientoAlmacenOptions } = useSapCatalog("Catalogs/UdfValidValues", {
|
||||
table_name: "OWTQ",
|
||||
field_name: "SIS_MOTALM",
|
||||
});
|
||||
const [motivo, setMotivo] = useState("");
|
||||
const [comentario, setComentario] = useState("");
|
||||
const [accion, setAccion] = useState("");
|
||||
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [formError, setFormError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
const [showConfirm, setShowConfirm] = useState(false);
|
||||
|
||||
// Serie de la Solicitud de Transferencia: se trae la lista de series
|
||||
// activas (no bloqueadas) y cuál es la default, para preseleccionarla en
|
||||
// el combo sin impedir que el usuario elija otra.
|
||||
useEffect(() => {
|
||||
const fetchSeries = async () => {
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`${API_URL}/api/series?document=${INVENTORY_TRANSFER_REQUEST_DOCUMENT_TYPE}`,
|
||||
);
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
setSeriesOptions(data.Options ?? []);
|
||||
if (data.Default != null) {
|
||||
setDefaultSeries(data.Default);
|
||||
setSeries(data.Default);
|
||||
}
|
||||
} catch {
|
||||
/* sin series cargadas, el usuario no podrá inmovilizar hasta reintentar */
|
||||
}
|
||||
};
|
||||
fetchSeries();
|
||||
}, []);
|
||||
|
||||
const resetPanel = () => {
|
||||
setSelections({});
|
||||
setDocDate(today());
|
||||
setToWarehouse(DEFAULT_TO_WAREHOUSE);
|
||||
setSeries(defaultSeries);
|
||||
setMovimientoInventario(DEFAULT_MOVIMIENTO_INVENTARIO);
|
||||
setTipoOperacion(DEFAULT_TIPO_OPERACION);
|
||||
setTipoDespacho(DEFAULT_TIPO_DESPACHO);
|
||||
setMovimientoAlmacen(DEFAULT_MOVIMIENTO_ALMACEN);
|
||||
setMotivo("");
|
||||
setComentario("");
|
||||
setAccion("");
|
||||
setFormError("");
|
||||
setSuccess("");
|
||||
};
|
||||
|
||||
const handleBuscar = async () => {
|
||||
const batch = batchInput.trim();
|
||||
if (!batch) return;
|
||||
setSearching(true);
|
||||
setSearchError("");
|
||||
setResult(null);
|
||||
resetPanel();
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`${API_URL}/api/batch/stock?batch=${encodeURIComponent(batch)}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new Error(data?.detail || "No se encontró stock para el lote indicado");
|
||||
}
|
||||
const data: BatchStockResponse = await response.json();
|
||||
setResult(data);
|
||||
} catch (err: unknown) {
|
||||
setSearchError(getErrorMessage(err, "Error al buscar el lote"));
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
// El stock que ya está en el almacén de inmovilizados (302) no se puede
|
||||
// volver a inmovilizar, así que esa fila no es seleccionable.
|
||||
const isLockedRow = (row: BatchWarehouseStock) =>
|
||||
row.WarehouseCode === DEFAULT_TO_WAREHOUSE.code;
|
||||
|
||||
const toggleRow = (row: BatchWarehouseStock) => {
|
||||
if (isLockedRow(row)) return;
|
||||
const key = rowKey(row);
|
||||
setSelections((prev) => {
|
||||
if (key in prev) {
|
||||
const { [key]: _removed, ...rest } = prev;
|
||||
return rest;
|
||||
}
|
||||
// Al marcar la fila, se precarga con el stock disponible (el usuario
|
||||
// puede editarlo después, pero no superarlo).
|
||||
return { ...prev, [key]: String(row.Quantity) };
|
||||
});
|
||||
};
|
||||
|
||||
const handleQuantityChange = (row: BatchWarehouseStock, value: string) => {
|
||||
const numericValue = Number(value);
|
||||
const clampedValue =
|
||||
value !== "" && !Number.isNaN(numericValue) && numericValue > row.Quantity
|
||||
? String(row.Quantity)
|
||||
: value;
|
||||
setSelections((prev) => ({ ...prev, [rowKey(row)]: clampedValue }));
|
||||
};
|
||||
|
||||
const handleWarehouseSeleccionado = (rows: any[]) => {
|
||||
if (rows.length === 0) return;
|
||||
setToWarehouse({ code: rows[0].WarehouseCode, name: rows[0].WarehouseName });
|
||||
};
|
||||
|
||||
const selectedRows = result
|
||||
? result.Warehouses.filter((w) => rowKey(w) in selections)
|
||||
: [];
|
||||
|
||||
const warehouseError =
|
||||
toWarehouse && selectedRows.some((row) => row.WarehouseCode === toWarehouse.code)
|
||||
? "El almacén destino debe ser distinto al almacén de origen"
|
||||
: "";
|
||||
|
||||
const allQuantitiesValid = selectedRows.every((row) => {
|
||||
const rawQuantity = selections[rowKey(row)] ?? "";
|
||||
return rawQuantity !== "" && !quantityErrorFor(row, rawQuantity);
|
||||
});
|
||||
|
||||
const canSubmit =
|
||||
selectedRows.length > 0 &&
|
||||
allQuantitiesValid &&
|
||||
!!toWarehouse &&
|
||||
!warehouseError &&
|
||||
!!docDate &&
|
||||
series !== "" &&
|
||||
movimientoInventario !== "" &&
|
||||
tipoOperacion !== "" &&
|
||||
tipoDespacho !== "" &&
|
||||
movimientoAlmacen !== "" &&
|
||||
motivo.trim() !== "" &&
|
||||
comentario.trim() !== "" &&
|
||||
accion.trim() !== "";
|
||||
|
||||
// El submit del form solo abre la confirmación; el POST real (que crea un
|
||||
// documento en SAP) ocurre recién si el usuario confirma en el modal.
|
||||
const handleFormSubmit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (selectedRows.length === 0 || !toWarehouse || !result || !canSubmit) return;
|
||||
setShowConfirm(true);
|
||||
};
|
||||
|
||||
const handleConfirmLock = async () => {
|
||||
setShowConfirm(false);
|
||||
if (selectedRows.length === 0 || !toWarehouse || !result || !canSubmit) return;
|
||||
setSubmitting(true);
|
||||
setFormError("");
|
||||
try {
|
||||
// El JSON que espera SAP se arma acá, no en el backend: el backend
|
||||
// solo reenvía este payload tal cual a Service Layer y es SAP quien
|
||||
// rechaza el documento si no hay stock suficiente.
|
||||
const payload: InventoryTransferRequestPayload = {
|
||||
DocDate: docDate,
|
||||
Series: Number(series),
|
||||
U_SIS_MOVINV: movimientoInventario,
|
||||
U_EXX_TIPOOPER: tipoOperacion,
|
||||
U_SIS_TIPDESP: tipoDespacho,
|
||||
U_SIS_MOTALM: movimientoAlmacen,
|
||||
U_SIS_MOTEST: motivo,
|
||||
U_SIS_COMEST: comentario,
|
||||
U_SIS_ACCTOM: accion,
|
||||
StockTransferLines: selectedRows.map((row) => {
|
||||
const quantity = Number(selections[rowKey(row)]);
|
||||
return {
|
||||
ItemCode: row.ItemCode,
|
||||
Quantity: quantity,
|
||||
WarehouseCode: toWarehouse.code,
|
||||
FromWarehouseCode: row.WarehouseCode,
|
||||
BatchNumbers: [{ BatchNumber: result.Batch, Quantity: quantity }],
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
const response = await apiFetch(`${API_URL}/api/InventoryTransferRequests`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) {
|
||||
// Error: se queda en el panel, con todo lo ya completado, para que
|
||||
// el usuario pueda corregir y reintentar sin volver a escribir todo.
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new Error(data?.detail || "Error al generar la Solicitud de Transferencia");
|
||||
}
|
||||
const data = await response.json();
|
||||
const docNumber = data.DocEntry;
|
||||
// Éxito: se vuelve a la pantalla inicial de búsqueda (no al mismo
|
||||
// lote) y el mensaje de éxito queda visible arriba, ya que el panel
|
||||
// donde estaba antes desaparece junto con la búsqueda.
|
||||
setBatchInput("");
|
||||
setResult(null);
|
||||
resetPanel();
|
||||
setSuccess(`Solicitud de Transferencia generada en SAP B1 (Doc. #${docNumber})`);
|
||||
} catch (err: unknown) {
|
||||
setFormError(getErrorMessage(err, "Error al generar la Solicitud de Transferencia"));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 bg-[var(--color-surface)] h-full flex flex-col font-sans select-none text-xs text-[var(--color-text)] overflow-auto">
|
||||
<div className="mb-4 border-b border-[var(--color-border-light)] pb-2">
|
||||
<h1 className="text-base font-semibold text-[var(--color-sidebar-title)] flex items-center gap-2">
|
||||
<Icon name="lock" className="w-4 h-4" />
|
||||
Inmovilizar Lotes
|
||||
</h1>
|
||||
<p className="text-[11px] text-[var(--color-text-muted)]">
|
||||
Consulta de stock por lote y almacén, y generación de Solicitud de Transferencia en SAP Business One
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-3 bg-[var(--color-bg)] border border-[var(--color-border)] mb-4">
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Número de Lote
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={batchInput}
|
||||
onChange={(e) => setBatchInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleBuscar();
|
||||
}}
|
||||
placeholder="Ingrese el número de lote"
|
||||
className="flex-1 max-w-sm px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
/>
|
||||
<PrimaryButton onClick={handleBuscar} disabled={searching || !batchInput.trim()}>
|
||||
{searching ? "Buscando..." : "Buscar"}
|
||||
</PrimaryButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{success && (
|
||||
<div className="mb-4 p-2 bg-[var(--color-success-bg)] border border-[var(--color-success-border)] text-[var(--color-success)]">
|
||||
{success}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{searchError && (
|
||||
<div className="mb-4 p-2 bg-[var(--color-error-bg)] border border-[var(--color-error-border)] text-[var(--color-error)]">
|
||||
{searchError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="space-y-3 mb-4">
|
||||
{/* Un mismo número de lote (DistNumber) puede repetirse en más de un
|
||||
artículo en SAP: se agrupa por Artículo y ese dato va en el
|
||||
mismo encabezado que el Lote (no se repite fila por fila). */}
|
||||
{groupByItem(result.Warehouses).map((group) => (
|
||||
<div
|
||||
key={group.ItemCode}
|
||||
className="p-3 bg-[var(--color-bg)] border border-[var(--color-border)]"
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Icon name="box" className="w-4 h-4 shrink-0" />
|
||||
<span className="font-semibold text-[var(--color-sidebar-title)]">
|
||||
Lote {result.Batch} · {group.ItemCode} - {group.ItemDescription}
|
||||
</span>
|
||||
<span className="text-[11px] text-[var(--color-text-muted)] ml-auto">
|
||||
Stock total: {group.rows.reduce((acc, w) => acc + w.Quantity, 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="pl-6 border-l border-[var(--color-sidebar-submenu-border)] ml-2 overflow-x-auto">
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr className="text-[11px] text-[var(--color-text-muted)] border-b border-[var(--color-border)]">
|
||||
<th className="text-left py-1 px-2 w-6"></th>
|
||||
<th className="text-left py-1 px-2">Almacén</th>
|
||||
<th className="text-right py-1 px-2">Cantidad</th>
|
||||
<th className="text-right py-1 px-2">Cantidad a inmovilizar</th>
|
||||
<th className="text-right py-1 px-2">Comprometido</th>
|
||||
<th className="text-right py-1 px-2">Contado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{group.rows.map((w) => {
|
||||
const key = rowKey(w);
|
||||
const isChecked = key in selections;
|
||||
const isLocked = isLockedRow(w);
|
||||
const rawQuantity = selections[key] ?? "";
|
||||
const rowQuantityError = isChecked ? quantityErrorFor(w, rawQuantity) : "";
|
||||
return (
|
||||
<tr
|
||||
key={key}
|
||||
onClick={() => toggleRow(w)}
|
||||
title={isLocked ? "Stock ya inmovilizado (almacén 302)" : undefined}
|
||||
className={`border-b border-[var(--color-border-light)] ${
|
||||
isLocked
|
||||
? "cursor-not-allowed opacity-50"
|
||||
: isChecked
|
||||
? "cursor-pointer bg-[var(--color-primary-active)]"
|
||||
: "cursor-pointer hover:bg-[var(--color-sidebar-hover)]"
|
||||
}`}
|
||||
>
|
||||
<td className="py-1.5 px-2" onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
disabled={isLocked}
|
||||
onChange={() => toggleRow(w)}
|
||||
/>
|
||||
</td>
|
||||
<td className="py-1.5 px-2">
|
||||
{w.WarehouseCode} - {w.WarehouseName}
|
||||
</td>
|
||||
<td className="py-1.5 px-2 text-right font-mono">{w.Quantity} UND</td>
|
||||
<td
|
||||
className="py-1.5 px-2 text-right"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max={w.Quantity}
|
||||
step="any"
|
||||
disabled={!isChecked}
|
||||
value={rawQuantity}
|
||||
onChange={(e) => handleQuantityChange(w, e.target.value)}
|
||||
placeholder="Cantidad"
|
||||
className="w-24 px-2 h-[26px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs text-right disabled:bg-[var(--color-disabled-bg)] disabled:cursor-not-allowed"
|
||||
/>
|
||||
{rowQuantityError && (
|
||||
<div className="mt-0.5 text-[10px] text-[var(--color-error)]">
|
||||
{rowQuantityError}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-1.5 px-2 text-right font-mono">
|
||||
{w.CommitQty} UND
|
||||
</td>
|
||||
<td className="py-1.5 px-2 text-right font-mono">{w.CountQty} UND</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedRows.length > 0 && (
|
||||
<form
|
||||
onSubmit={handleFormSubmit}
|
||||
className="p-3 bg-[var(--color-bg)] border border-[var(--color-border)] space-y-4"
|
||||
>
|
||||
<div>
|
||||
<span className="font-semibold text-[var(--color-sidebar-title)]">
|
||||
Inmovilizar Lote {result?.Batch} · {selectedRows.length} almacén(es) seleccionado(s)
|
||||
</span>
|
||||
<ul className="mt-1 text-[11px] text-[var(--color-text-muted)] space-y-0.5">
|
||||
{selectedRows.map((row) => (
|
||||
<li key={rowKey(row)}>
|
||||
{row.ItemCode} - {row.ItemDescription} · Almacén origen: {row.WarehouseCode} -{" "}
|
||||
{row.WarehouseName} · Cantidad a inmovilizar:{" "}
|
||||
{selections[rowKey(row)] || "-"} UND (stock disponible: {row.Quantity} UND)
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{formError && (
|
||||
<div className="p-2 bg-[var(--color-error-bg)] border border-[var(--color-error-border)] text-[var(--color-error)]">
|
||||
{formError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
|
||||
<FormattedField
|
||||
type="date"
|
||||
label="Fecha"
|
||||
value={docDate}
|
||||
mode="input"
|
||||
name="DocDate"
|
||||
required
|
||||
onChange={(e) => setDocDate(e.target.value)}
|
||||
/>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Serie <span className="text-[var(--color-error)]">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={series}
|
||||
onChange={(e) => setSeries(e.target.value ? Number(e.target.value) : "")}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
<option value="">Seleccione serie</option>
|
||||
{seriesOptions.map((s) => (
|
||||
<option key={s.Series} value={s.Series}>
|
||||
{s.Series} - {s.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Almacén destino <span className="text-[var(--color-error)]">*</span>
|
||||
</label>
|
||||
<div className="flex items-center border border-[var(--color-input-border)] bg-[var(--color-surface)] focus-within:border-[var(--color-input-focus)]">
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={toWarehouse ? `${toWarehouse.code} - ${toWarehouse.name}` : ""}
|
||||
placeholder="Seleccionar almacén..."
|
||||
onClick={() => setIsWarehouseModalOpen(true)}
|
||||
className="flex-1 min-w-0 h-[28px] px-2 border-none outline-none bg-transparent text-xs cursor-pointer"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsWarehouseModalOpen(true)}
|
||||
className="h-[28px] px-1.5 bg-transparent border-none cursor-pointer text-[var(--color-primary)] shrink-0"
|
||||
title="Buscar almacén"
|
||||
>
|
||||
<Icon name="search" className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
{warehouseError && (
|
||||
<div className="mt-1 text-[11px] text-[var(--color-error)]">{warehouseError}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Movimiento de inventario <span className="text-[var(--color-error)]">*</span>
|
||||
<FieldTooltip text="U_SIS_MOVINV" />
|
||||
</label>
|
||||
<select
|
||||
value={movimientoInventario}
|
||||
onChange={(e) => setMovimientoInventario(e.target.value)}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
{movimientoInventarioOptions.map((o) => (
|
||||
<option key={o.Code} value={o.Code}>
|
||||
{o.Code} - {o.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Tipo de operación <span className="text-[var(--color-error)]">*</span>
|
||||
<FieldTooltip text="U_EXX_TIPOOPER" />
|
||||
</label>
|
||||
<select
|
||||
value={tipoOperacion}
|
||||
onChange={(e) => setTipoOperacion(e.target.value)}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
{tipoOperacionOptions.map((o) => (
|
||||
<option key={o.Code} value={o.Code}>
|
||||
{o.Code} - {o.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Tipo de despacho <span className="text-[var(--color-error)]">*</span>
|
||||
<FieldTooltip text="U_SIS_TIPDESP" />
|
||||
</label>
|
||||
<select
|
||||
value={tipoDespacho}
|
||||
onChange={(e) => setTipoDespacho(e.target.value)}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
{tipoDespachoOptions.map((o) => (
|
||||
<option key={o.Code} value={o.Code}>
|
||||
{o.Code} - {o.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Movimiento almacén <span className="text-[var(--color-error)]">*</span>
|
||||
<FieldTooltip text="U_SIS_MOTALM" />
|
||||
</label>
|
||||
<select
|
||||
value={movimientoAlmacen}
|
||||
onChange={(e) => setMovimientoAlmacen(e.target.value)}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
{movimientoAlmacenOptions.map((o) => (
|
||||
<option key={o.Code} value={o.Code}>
|
||||
{o.Code} - {o.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-[var(--color-border-light)] space-y-3">
|
||||
<h2 className="text-xs font-semibold text-[var(--color-sidebar-title)]">
|
||||
Datos de la Solicitud de Transferencia (SAP B1)
|
||||
</h2>
|
||||
<div>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Motivo de estado"
|
||||
dbField="U_SIS_MOTEST"
|
||||
value={motivo}
|
||||
mode="input"
|
||||
name="MotivoEstado"
|
||||
required
|
||||
multiline
|
||||
rows={2}
|
||||
maxLength={MOTIVO_MAX}
|
||||
onChange={(e) => setMotivo(e.target.value)}
|
||||
/>
|
||||
<div className="text-right text-[10px] text-[var(--color-text-muted)]">
|
||||
{motivo.length} / {MOTIVO_MAX}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Comentario de estado"
|
||||
dbField="U_SIS_COMEST"
|
||||
value={comentario}
|
||||
mode="input"
|
||||
name="ComentarioEstado"
|
||||
required
|
||||
multiline
|
||||
rows={6}
|
||||
maxLength={TEXT_MAX}
|
||||
onChange={(e) => setComentario(e.target.value)}
|
||||
/>
|
||||
<div className="text-right text-[10px] text-[var(--color-text-muted)]">
|
||||
{comentario.length} / {TEXT_MAX}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Acción a tomar"
|
||||
dbField="U_SIS_ACCTOM"
|
||||
value={accion}
|
||||
mode="input"
|
||||
name="AccionATomar"
|
||||
required
|
||||
multiline
|
||||
rows={6}
|
||||
maxLength={TEXT_MAX}
|
||||
onChange={(e) => setAccion(e.target.value)}
|
||||
/>
|
||||
<div className="text-right text-[10px] text-[var(--color-text-muted)]">
|
||||
{accion.length} / {TEXT_MAX}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-2 border-t border-[var(--color-border-light)] space-x-2">
|
||||
<SecondaryButton type="button" onClick={resetPanel}>
|
||||
Cancelar
|
||||
</SecondaryButton>
|
||||
<PrimaryButton type="submit" size="md" disabled={!canSubmit || submitting}>
|
||||
{submitting ? "Procesando..." : "Inmovilizar"}
|
||||
</PrimaryButton>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<ModalSearchTemplate
|
||||
isOpen={isWarehouseModalOpen}
|
||||
onClose={() => setIsWarehouseModalOpen(false)}
|
||||
title="Buscar Almacén"
|
||||
endpoint="Warehouses"
|
||||
fields={["WarehouseCode", "WarehouseName"]}
|
||||
columns={[
|
||||
{ key: "WarehouseCode", title: "Código", width: "120px" },
|
||||
{ key: "WarehouseName", title: "Nombre" },
|
||||
]}
|
||||
baseFilter=""
|
||||
seleccion="unica"
|
||||
onConfirmarSeleccion={handleWarehouseSeleccionado}
|
||||
rowKey="WarehouseCode"
|
||||
/>
|
||||
|
||||
<ConfirmModal
|
||||
isOpen={showConfirm}
|
||||
title="Confirmar inmovilización"
|
||||
onConfirm={handleConfirmLock}
|
||||
onCancel={() => setShowConfirm(false)}
|
||||
message={
|
||||
selectedRows.length > 0 &&
|
||||
toWarehouse && (
|
||||
<div className="space-y-1">
|
||||
<p>¿Confirma que desea generar la Solicitud de Transferencia en SAP B1?</p>
|
||||
<ul className="mt-2 space-y-0.5 text-[var(--color-text-muted)]">
|
||||
<li>Lote: {result?.Batch}</li>
|
||||
<li>
|
||||
Almacén destino: {toWarehouse.code} - {toWarehouse.name}
|
||||
</li>
|
||||
{selectedRows.map((row) => (
|
||||
<li key={rowKey(row)}>
|
||||
{row.ItemCode} - {row.ItemDescription} · Origen: {row.WarehouseCode} -{" "}
|
||||
{row.WarehouseName} · Cantidad: {selections[rowKey(row)]} UND
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,773 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { API_URL, apiFetch } from "../../utils/api";
|
||||
import { getErrorMessage } from "../../utils/errors";
|
||||
import FormattedField from "../../components/ui/FormattedField";
|
||||
import PrimaryButton from "../../components/ui/PrimaryButton";
|
||||
import SecondaryButton from "../../components/ui/SecondaryButton";
|
||||
import Icon from "../../components/ui/Icon";
|
||||
import ModalSearchTemplate from "../../components/ui/ModalSearchTemplate";
|
||||
import ConfirmModal from "../../components/ui/ConfirmModal";
|
||||
import FieldTooltip from "../../components/ui/FieldTooltip";
|
||||
import { useSapCatalog } from "../../hooks/useSapCatalog";
|
||||
import type {
|
||||
BatchStockResponse,
|
||||
BatchWarehouseStock,
|
||||
InventoryTransferRequestPayload,
|
||||
SeriesOption,
|
||||
} from "../../types/sapInventoryLock";
|
||||
|
||||
const MOTIVO_MAX = 100;
|
||||
const TEXT_MAX = 254;
|
||||
// Almacén de origen por defecto para liberar (302 - INMOVILIZADOS DRO): es el
|
||||
// almacén donde "Inmovilizar Lotes" deja el stock, así que es el punto de
|
||||
// partida natural acá. El usuario puede cambiarlo igual con la lupa.
|
||||
const DEFAULT_FROM_WAREHOUSE = { code: "302", name: "INMOVILIZADOS DRO" };
|
||||
// Código de objeto SAP B1 (BoObjectTypes) para Solicitud de Transferencia de
|
||||
// Inventario, usado para pedirle al endpoint genérico de series las suyas.
|
||||
const INVENTORY_TRANSFER_REQUEST_DOCUMENT_TYPE = "1250000001";
|
||||
// Mismos valores por defecto que "Inmovilizar Lotes" para estos campos de
|
||||
// usuario, confirmados explícitamente por el usuario para "Liberar Lotes".
|
||||
const DEFAULT_MOVIMIENTO_INVENTARIO = "XTD";
|
||||
const DEFAULT_TIPO_OPERACION = "11";
|
||||
const DEFAULT_TIPO_DESPACHO = "N";
|
||||
const DEFAULT_MOVIMIENTO_ALMACEN = "108";
|
||||
const DEFAULT_TO_WAREHOUSE = { code: "201", name: "APROBADOS DRO" };
|
||||
|
||||
function today(): string {
|
||||
return new Date().toISOString().split("T")[0];
|
||||
}
|
||||
|
||||
interface ItemStockGroup {
|
||||
ItemCode: string;
|
||||
ItemDescription?: string;
|
||||
rows: BatchWarehouseStock[];
|
||||
}
|
||||
|
||||
// Un mismo número de lote puede repetirse en más de un artículo en SAP, así
|
||||
// que el árbol se arma por Artículo (no solo por Almacén).
|
||||
function groupByItem(warehouses: BatchWarehouseStock[]): ItemStockGroup[] {
|
||||
const groups: ItemStockGroup[] = [];
|
||||
for (const w of warehouses) {
|
||||
let group = groups.find((g) => g.ItemCode === w.ItemCode);
|
||||
if (!group) {
|
||||
group = { ItemCode: w.ItemCode, ItemDescription: w.ItemDescription, rows: [] };
|
||||
groups.push(group);
|
||||
}
|
||||
group.rows.push(w);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
// Identifica una fila de stock (Artículo + Almacén) para usarla como key de
|
||||
// selección: un mismo almacén puede repetirse en distintos artículos del lote.
|
||||
function rowKey(row: BatchWarehouseStock): string {
|
||||
return `${row.ItemCode}::${row.WarehouseCode}`;
|
||||
}
|
||||
|
||||
function quantityErrorFor(row: BatchWarehouseStock, rawQuantity: string): string {
|
||||
if (rawQuantity === "") return "";
|
||||
const quantityNumber = Number(rawQuantity);
|
||||
if (quantityNumber <= 0) return "La cantidad debe ser mayor a 0";
|
||||
if (quantityNumber > row.Quantity) {
|
||||
return `La cantidad no puede superar el stock disponible en el almacén (${row.Quantity})`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export default function LiberarLotesView() {
|
||||
const [fromWarehouse, setFromWarehouse] = useState(DEFAULT_FROM_WAREHOUSE);
|
||||
const [isFromWarehouseModalOpen, setIsFromWarehouseModalOpen] = useState(false);
|
||||
const [batchInput, setBatchInput] = useState("");
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [searchError, setSearchError] = useState("");
|
||||
const [result, setResult] = useState<BatchStockResponse | null>(null);
|
||||
|
||||
// Selección múltiple: qué filas (Artículo + Almacén) están marcadas para
|
||||
// liberar y qué cantidad tiene cada una, por rowKey.
|
||||
const [selections, setSelections] = useState<Record<string, string>>({});
|
||||
const [docDate, setDocDate] = useState(today());
|
||||
const [toWarehouse, setToWarehouse] = useState(DEFAULT_TO_WAREHOUSE);
|
||||
const [isToWarehouseModalOpen, setIsToWarehouseModalOpen] = useState(false);
|
||||
const [seriesOptions, setSeriesOptions] = useState<SeriesOption[]>([]);
|
||||
const [defaultSeries, setDefaultSeries] = useState<number | "">("");
|
||||
const [series, setSeries] = useState<number | "">("");
|
||||
const [movimientoInventario, setMovimientoInventario] = useState(DEFAULT_MOVIMIENTO_INVENTARIO);
|
||||
const [tipoOperacion, setTipoOperacion] = useState(DEFAULT_TIPO_OPERACION);
|
||||
const [tipoDespacho, setTipoDespacho] = useState(DEFAULT_TIPO_DESPACHO);
|
||||
const [movimientoAlmacen, setMovimientoAlmacen] = useState(DEFAULT_MOVIMIENTO_ALMACEN);
|
||||
const { options: movimientoInventarioOptions } = useSapCatalog(
|
||||
"UserTables/MovimientoInventario",
|
||||
);
|
||||
const { options: tipoOperacionOptions } = useSapCatalog("UserTables/TipoOperacion");
|
||||
const { options: tipoDespachoOptions } = useSapCatalog("Catalogs/UdfValidValues", {
|
||||
table_name: "OWTQ",
|
||||
field_name: "SIS_TIPDESP",
|
||||
});
|
||||
const { options: movimientoAlmacenOptions } = useSapCatalog("Catalogs/UdfValidValues", {
|
||||
table_name: "OWTQ",
|
||||
field_name: "SIS_MOTALM",
|
||||
});
|
||||
const [motivo, setMotivo] = useState("");
|
||||
const [comentario, setComentario] = useState("");
|
||||
const [accion, setAccion] = useState("");
|
||||
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [formError, setFormError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
const [showConfirm, setShowConfirm] = useState(false);
|
||||
|
||||
// Serie de la Solicitud de Transferencia: se trae la lista de series
|
||||
// activas (no bloqueadas) y cuál es la default, para preseleccionarla en
|
||||
// el combo sin impedir que el usuario elija otra.
|
||||
useEffect(() => {
|
||||
const fetchSeries = async () => {
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`${API_URL}/api/series?document=${INVENTORY_TRANSFER_REQUEST_DOCUMENT_TYPE}`,
|
||||
);
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
setSeriesOptions(data.Options ?? []);
|
||||
if (data.Default != null) {
|
||||
setDefaultSeries(data.Default);
|
||||
setSeries(data.Default);
|
||||
}
|
||||
} catch {
|
||||
/* sin series cargadas, el usuario no podrá liberar hasta reintentar */
|
||||
}
|
||||
};
|
||||
fetchSeries();
|
||||
}, []);
|
||||
|
||||
const resetPanel = () => {
|
||||
setSelections({});
|
||||
setDocDate(today());
|
||||
setToWarehouse(DEFAULT_TO_WAREHOUSE);
|
||||
setSeries(defaultSeries);
|
||||
setMovimientoInventario(DEFAULT_MOVIMIENTO_INVENTARIO);
|
||||
setTipoOperacion(DEFAULT_TIPO_OPERACION);
|
||||
setTipoDespacho(DEFAULT_TIPO_DESPACHO);
|
||||
setMovimientoAlmacen(DEFAULT_MOVIMIENTO_ALMACEN);
|
||||
setMotivo("");
|
||||
setComentario("");
|
||||
setAccion("");
|
||||
setFormError("");
|
||||
setSuccess("");
|
||||
};
|
||||
|
||||
const handleBuscar = async () => {
|
||||
const batch = batchInput.trim();
|
||||
if (!batch) return;
|
||||
setSearching(true);
|
||||
setSearchError("");
|
||||
setResult(null);
|
||||
resetPanel();
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`${API_URL}/api/batch/stock?batch=${encodeURIComponent(batch)}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new Error(data?.detail || "No se encontró stock para el lote indicado");
|
||||
}
|
||||
const data: BatchStockResponse = await response.json();
|
||||
const hasStockInWarehouse = data.Warehouses.some(
|
||||
(w) => w.WarehouseCode === fromWarehouse.code,
|
||||
);
|
||||
if (!hasStockInWarehouse) {
|
||||
throw new Error(
|
||||
`El lote '${batch}' no tiene stock en el almacén ${fromWarehouse.code} - ${fromWarehouse.name}`,
|
||||
);
|
||||
}
|
||||
setResult(data);
|
||||
} catch (err: unknown) {
|
||||
setSearchError(getErrorMessage(err, "Error al buscar el lote"));
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleRow = (row: BatchWarehouseStock) => {
|
||||
const key = rowKey(row);
|
||||
setSelections((prev) => {
|
||||
if (key in prev) {
|
||||
const { [key]: _removed, ...rest } = prev;
|
||||
return rest;
|
||||
}
|
||||
// Al marcar la fila, se precarga con el stock disponible (el usuario
|
||||
// puede editarlo después, pero no superarlo).
|
||||
return { ...prev, [key]: String(row.Quantity) };
|
||||
});
|
||||
};
|
||||
|
||||
const handleQuantityChange = (row: BatchWarehouseStock, value: string) => {
|
||||
const numericValue = Number(value);
|
||||
const clampedValue =
|
||||
value !== "" && !Number.isNaN(numericValue) && numericValue > row.Quantity
|
||||
? String(row.Quantity)
|
||||
: value;
|
||||
setSelections((prev) => ({ ...prev, [rowKey(row)]: clampedValue }));
|
||||
};
|
||||
|
||||
const handleFromWarehouseSeleccionado = (rows: any[]) => {
|
||||
if (rows.length === 0) return;
|
||||
setFromWarehouse({ code: rows[0].WarehouseCode, name: rows[0].WarehouseName });
|
||||
};
|
||||
|
||||
const handleToWarehouseSeleccionado = (rows: any[]) => {
|
||||
if (rows.length === 0) return;
|
||||
setToWarehouse({ code: rows[0].WarehouseCode, name: rows[0].WarehouseName });
|
||||
};
|
||||
|
||||
// El resultado de la búsqueda trae stock de todos los almacenes del lote;
|
||||
// acá se muestra solo el del almacén de origen elegido. Si el usuario
|
||||
// cambia el almacén de origen después de buscar, esto se recalcula sin
|
||||
// necesidad de volver a pedirle al backend.
|
||||
const warehouseRows = result
|
||||
? result.Warehouses.filter((w) => w.WarehouseCode === fromWarehouse.code)
|
||||
: [];
|
||||
|
||||
const selectedRows = warehouseRows.filter((w) => rowKey(w) in selections);
|
||||
|
||||
const warehouseError =
|
||||
toWarehouse && toWarehouse.code === fromWarehouse.code
|
||||
? "El almacén destino debe ser distinto al almacén de origen"
|
||||
: "";
|
||||
|
||||
const allQuantitiesValid = selectedRows.every((row) => {
|
||||
const rawQuantity = selections[rowKey(row)] ?? "";
|
||||
return rawQuantity !== "" && !quantityErrorFor(row, rawQuantity);
|
||||
});
|
||||
|
||||
const canSubmit =
|
||||
selectedRows.length > 0 &&
|
||||
allQuantitiesValid &&
|
||||
!!toWarehouse &&
|
||||
!warehouseError &&
|
||||
!!docDate &&
|
||||
series !== "" &&
|
||||
movimientoInventario !== "" &&
|
||||
tipoOperacion !== "" &&
|
||||
tipoDespacho !== "" &&
|
||||
movimientoAlmacen !== "" &&
|
||||
motivo.trim() !== "";
|
||||
|
||||
// El submit del form solo abre la confirmación; el POST real (que crea un
|
||||
// documento en SAP) ocurre recién si el usuario confirma en el modal.
|
||||
const handleFormSubmit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (selectedRows.length === 0 || !toWarehouse || !result || !canSubmit) return;
|
||||
setShowConfirm(true);
|
||||
};
|
||||
|
||||
const handleConfirmRelease = async () => {
|
||||
setShowConfirm(false);
|
||||
if (selectedRows.length === 0 || !toWarehouse || !result || !canSubmit) return;
|
||||
setSubmitting(true);
|
||||
setFormError("");
|
||||
try {
|
||||
// El JSON que espera SAP se arma acá, no en el backend: el backend
|
||||
// solo reenvía este payload tal cual a Service Layer y es SAP quien
|
||||
// rechaza el documento si no hay stock suficiente.
|
||||
const payload: InventoryTransferRequestPayload = {
|
||||
DocDate: docDate,
|
||||
Series: Number(series),
|
||||
U_SIS_MOVINV: movimientoInventario,
|
||||
U_EXX_TIPOOPER: tipoOperacion,
|
||||
U_SIS_TIPDESP: tipoDespacho,
|
||||
U_SIS_MOTALM: movimientoAlmacen,
|
||||
U_SIS_MOTEST: motivo,
|
||||
U_SIS_COMEST: comentario,
|
||||
U_SIS_ACCTOM: accion,
|
||||
StockTransferLines: selectedRows.map((row) => {
|
||||
const quantity = Number(selections[rowKey(row)]);
|
||||
return {
|
||||
ItemCode: row.ItemCode,
|
||||
Quantity: quantity,
|
||||
WarehouseCode: toWarehouse.code,
|
||||
FromWarehouseCode: fromWarehouse.code,
|
||||
BatchNumbers: [{ BatchNumber: result.Batch, Quantity: quantity }],
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
const response = await apiFetch(`${API_URL}/api/InventoryTransferRequests`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) {
|
||||
// Error: se queda en el panel, con todo lo ya completado, para que
|
||||
// el usuario pueda corregir y reintentar sin volver a escribir todo.
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new Error(data?.detail || "Error al generar la Solicitud de Transferencia");
|
||||
}
|
||||
const data = await response.json();
|
||||
const docNumber = data.DocEntry;
|
||||
// Éxito: se vuelve a la pantalla inicial de búsqueda (no al mismo
|
||||
// lote) y el mensaje de éxito queda visible arriba, ya que el panel
|
||||
// donde estaba antes desaparece junto con la búsqueda.
|
||||
setBatchInput("");
|
||||
setResult(null);
|
||||
resetPanel();
|
||||
setSuccess(`Solicitud de Transferencia generada en SAP B1 (Doc. #${docNumber})`);
|
||||
} catch (err: unknown) {
|
||||
setFormError(getErrorMessage(err, "Error al generar la Solicitud de Transferencia"));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 bg-[var(--color-surface)] h-full flex flex-col font-sans select-none text-xs text-[var(--color-text)] overflow-auto">
|
||||
<div className="mb-4 border-b border-[var(--color-border-light)] pb-2">
|
||||
<h1 className="text-base font-semibold text-[var(--color-sidebar-title)] flex items-center gap-2">
|
||||
<Icon name="check-circle" className="w-4 h-4" />
|
||||
Liberar Lotes
|
||||
</h1>
|
||||
<p className="text-[11px] text-[var(--color-text-muted)]">
|
||||
Consulta de stock inmovilizado por lote en un almacén, y generación de Solicitud de
|
||||
Transferencia en SAP Business One
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-3 bg-[var(--color-bg)] border border-[var(--color-border)] mb-4">
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-end gap-3">
|
||||
<div className="w-full sm:w-64">
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Almacén de origen
|
||||
</label>
|
||||
<div className="flex items-center border border-[var(--color-input-border)] bg-[var(--color-surface)] focus-within:border-[var(--color-input-focus)]">
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={`${fromWarehouse.code} - ${fromWarehouse.name}`}
|
||||
onClick={() => setIsFromWarehouseModalOpen(true)}
|
||||
className="flex-1 min-w-0 h-[28px] px-2 border-none outline-none bg-transparent text-xs cursor-pointer"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsFromWarehouseModalOpen(true)}
|
||||
className="h-[28px] px-1.5 bg-transparent border-none cursor-pointer text-[var(--color-primary)] shrink-0"
|
||||
title="Buscar almacén"
|
||||
>
|
||||
<Icon name="search" className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Número de Lote
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={batchInput}
|
||||
onChange={(e) => setBatchInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleBuscar();
|
||||
}}
|
||||
placeholder="Ingrese el número de lote"
|
||||
className="flex-1 max-w-sm px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
/>
|
||||
<PrimaryButton onClick={handleBuscar} disabled={searching || !batchInput.trim()}>
|
||||
{searching ? "Buscando..." : "Buscar"}
|
||||
</PrimaryButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{success && (
|
||||
<div className="mb-4 p-2 bg-[var(--color-success-bg)] border border-[var(--color-success-border)] text-[var(--color-success)]">
|
||||
{success}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{searchError && (
|
||||
<div className="mb-4 p-2 bg-[var(--color-error-bg)] border border-[var(--color-error-border)] text-[var(--color-error)]">
|
||||
{searchError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="space-y-3 mb-4">
|
||||
{/* Un mismo número de lote (DistNumber) puede repetirse en más de un
|
||||
artículo en SAP: se agrupa por Artículo y ese dato va en el
|
||||
mismo encabezado que el Lote (no se repite fila por fila). El
|
||||
Almacén no se repite por fila porque acá siempre es el mismo:
|
||||
el elegido arriba en "Almacén de origen". */}
|
||||
{groupByItem(warehouseRows).map((group) => (
|
||||
<div
|
||||
key={group.ItemCode}
|
||||
className="p-3 bg-[var(--color-bg)] border border-[var(--color-border)]"
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Icon name="box" className="w-4 h-4 shrink-0" />
|
||||
<span className="font-semibold text-[var(--color-sidebar-title)]">
|
||||
Lote {result.Batch} · {group.ItemCode} - {group.ItemDescription} · Almacén{" "}
|
||||
{fromWarehouse.code} - {fromWarehouse.name}
|
||||
</span>
|
||||
<span className="text-[11px] text-[var(--color-text-muted)] ml-auto">
|
||||
Stock total: {group.rows.reduce((acc, w) => acc + w.Quantity, 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="pl-6 border-l border-[var(--color-sidebar-submenu-border)] ml-2 overflow-x-auto">
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr className="text-[11px] text-[var(--color-text-muted)] border-b border-[var(--color-border)]">
|
||||
<th className="text-left py-1 px-2 w-6"></th>
|
||||
<th className="text-right py-1 px-2">Cantidad</th>
|
||||
<th className="text-right py-1 px-2">Cantidad a liberar</th>
|
||||
<th className="text-right py-1 px-2">Comprometido</th>
|
||||
<th className="text-right py-1 px-2">Contado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{group.rows.map((w) => {
|
||||
const key = rowKey(w);
|
||||
const isChecked = key in selections;
|
||||
const rawQuantity = selections[key] ?? "";
|
||||
const rowQuantityError = isChecked ? quantityErrorFor(w, rawQuantity) : "";
|
||||
return (
|
||||
<tr
|
||||
key={key}
|
||||
onClick={() => toggleRow(w)}
|
||||
className={`cursor-pointer border-b border-[var(--color-border-light)] ${
|
||||
isChecked
|
||||
? "bg-[var(--color-primary-active)]"
|
||||
: "hover:bg-[var(--color-sidebar-hover)]"
|
||||
}`}
|
||||
>
|
||||
<td className="py-1.5 px-2" onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
onChange={() => toggleRow(w)}
|
||||
/>
|
||||
</td>
|
||||
<td className="py-1.5 px-2 text-right font-mono">{w.Quantity} UND</td>
|
||||
<td
|
||||
className="py-1.5 px-2 text-right"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max={w.Quantity}
|
||||
step="any"
|
||||
disabled={!isChecked}
|
||||
value={rawQuantity}
|
||||
onChange={(e) => handleQuantityChange(w, e.target.value)}
|
||||
placeholder="Cantidad"
|
||||
className="w-24 px-2 h-[26px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs text-right disabled:bg-[var(--color-disabled-bg)] disabled:cursor-not-allowed"
|
||||
/>
|
||||
{rowQuantityError && (
|
||||
<div className="mt-0.5 text-[10px] text-[var(--color-error)]">
|
||||
{rowQuantityError}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-1.5 px-2 text-right font-mono">
|
||||
{w.CommitQty} UND
|
||||
</td>
|
||||
<td className="py-1.5 px-2 text-right font-mono">{w.CountQty} UND</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedRows.length > 0 && (
|
||||
<form
|
||||
onSubmit={handleFormSubmit}
|
||||
className="p-3 bg-[var(--color-bg)] border border-[var(--color-border)] space-y-4"
|
||||
>
|
||||
<div>
|
||||
<span className="font-semibold text-[var(--color-sidebar-title)]">
|
||||
Liberar Lote {result?.Batch} · {selectedRows.length} artículo(s) seleccionado(s)
|
||||
</span>
|
||||
<ul className="mt-1 text-[11px] text-[var(--color-text-muted)] space-y-0.5">
|
||||
{selectedRows.map((row) => (
|
||||
<li key={rowKey(row)}>
|
||||
{row.ItemCode} - {row.ItemDescription} · Cantidad a liberar:{" "}
|
||||
{selections[rowKey(row)] || "-"} UND (stock disponible: {row.Quantity} UND)
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{formError && (
|
||||
<div className="p-2 bg-[var(--color-error-bg)] border border-[var(--color-error-border)] text-[var(--color-error)]">
|
||||
{formError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
|
||||
<FormattedField
|
||||
type="date"
|
||||
label="Fecha"
|
||||
value={docDate}
|
||||
mode="input"
|
||||
name="DocDate"
|
||||
required
|
||||
onChange={(e) => setDocDate(e.target.value)}
|
||||
/>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Serie <span className="text-[var(--color-error)]">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={series}
|
||||
onChange={(e) => setSeries(e.target.value ? Number(e.target.value) : "")}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
<option value="">Seleccione serie</option>
|
||||
{seriesOptions.map((s) => (
|
||||
<option key={s.Series} value={s.Series}>
|
||||
{s.Series} - {s.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Almacén destino <span className="text-[var(--color-error)]">*</span>
|
||||
</label>
|
||||
<div className="flex items-center border border-[var(--color-input-border)] bg-[var(--color-surface)] focus-within:border-[var(--color-input-focus)]">
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={toWarehouse ? `${toWarehouse.code} - ${toWarehouse.name}` : ""}
|
||||
placeholder="Seleccionar almacén..."
|
||||
onClick={() => setIsToWarehouseModalOpen(true)}
|
||||
className="flex-1 min-w-0 h-[28px] px-2 border-none outline-none bg-transparent text-xs cursor-pointer"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsToWarehouseModalOpen(true)}
|
||||
className="h-[28px] px-1.5 bg-transparent border-none cursor-pointer text-[var(--color-primary)] shrink-0"
|
||||
title="Buscar almacén"
|
||||
>
|
||||
<Icon name="search" className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
{warehouseError && (
|
||||
<div className="mt-1 text-[11px] text-[var(--color-error)]">{warehouseError}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Movimiento de inventario <span className="text-[var(--color-error)]">*</span>
|
||||
<FieldTooltip text="U_SIS_MOVINV" />
|
||||
</label>
|
||||
<select
|
||||
value={movimientoInventario}
|
||||
onChange={(e) => setMovimientoInventario(e.target.value)}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
{movimientoInventarioOptions.map((o) => (
|
||||
<option key={o.Code} value={o.Code}>
|
||||
{o.Code} - {o.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Tipo de operación <span className="text-[var(--color-error)]">*</span>
|
||||
<FieldTooltip text="U_EXX_TIPOOPER" />
|
||||
</label>
|
||||
<select
|
||||
value={tipoOperacion}
|
||||
onChange={(e) => setTipoOperacion(e.target.value)}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
{tipoOperacionOptions.map((o) => (
|
||||
<option key={o.Code} value={o.Code}>
|
||||
{o.Code} - {o.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Tipo de despacho <span className="text-[var(--color-error)]">*</span>
|
||||
<FieldTooltip text="U_SIS_TIPDESP" />
|
||||
</label>
|
||||
<select
|
||||
value={tipoDespacho}
|
||||
onChange={(e) => setTipoDespacho(e.target.value)}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
{tipoDespachoOptions.map((o) => (
|
||||
<option key={o.Code} value={o.Code}>
|
||||
{o.Code} - {o.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[var(--color-text-muted)] font-medium mb-1 text-xs">
|
||||
Movimiento almacén <span className="text-[var(--color-error)]">*</span>
|
||||
<FieldTooltip text="U_SIS_MOTALM" />
|
||||
</label>
|
||||
<select
|
||||
value={movimientoAlmacen}
|
||||
onChange={(e) => setMovimientoAlmacen(e.target.value)}
|
||||
required
|
||||
className="w-full px-2 h-[28px] border border-[var(--color-input-border)] bg-[var(--color-surface)] rounded-none outline-none focus:border-[var(--color-input-focus)] text-xs"
|
||||
>
|
||||
{movimientoAlmacenOptions.map((o) => (
|
||||
<option key={o.Code} value={o.Code}>
|
||||
{o.Code} - {o.Name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-[var(--color-border-light)] space-y-3">
|
||||
<h2 className="text-xs font-semibold text-[var(--color-sidebar-title)]">
|
||||
Datos de la Solicitud de Transferencia (SAP B1)
|
||||
</h2>
|
||||
<div>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Motivo de estado"
|
||||
dbField="U_SIS_MOTEST"
|
||||
value={motivo}
|
||||
mode="input"
|
||||
name="MotivoEstado"
|
||||
required
|
||||
multiline
|
||||
rows={2}
|
||||
maxLength={MOTIVO_MAX}
|
||||
onChange={(e) => setMotivo(e.target.value)}
|
||||
/>
|
||||
<div className="text-right text-[10px] text-[var(--color-text-muted)]">
|
||||
{motivo.length} / {MOTIVO_MAX}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Comentario de estado"
|
||||
dbField="U_SIS_COMEST"
|
||||
value={comentario}
|
||||
mode="input"
|
||||
name="ComentarioEstado"
|
||||
multiline
|
||||
rows={6}
|
||||
maxLength={TEXT_MAX}
|
||||
onChange={(e) => setComentario(e.target.value)}
|
||||
/>
|
||||
<div className="text-right text-[10px] text-[var(--color-text-muted)]">
|
||||
{comentario.length} / {TEXT_MAX}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<FormattedField
|
||||
type="text"
|
||||
label="Acción a tomar"
|
||||
dbField="U_SIS_ACCTOM"
|
||||
value={accion}
|
||||
mode="input"
|
||||
name="AccionATomar"
|
||||
multiline
|
||||
rows={6}
|
||||
maxLength={TEXT_MAX}
|
||||
onChange={(e) => setAccion(e.target.value)}
|
||||
/>
|
||||
<div className="text-right text-[10px] text-[var(--color-text-muted)]">
|
||||
{accion.length} / {TEXT_MAX}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-2 border-t border-[var(--color-border-light)] space-x-2">
|
||||
<SecondaryButton type="button" onClick={resetPanel}>
|
||||
Cancelar
|
||||
</SecondaryButton>
|
||||
<PrimaryButton type="submit" size="md" disabled={!canSubmit || submitting}>
|
||||
{submitting ? "Procesando..." : "Liberar"}
|
||||
</PrimaryButton>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<ModalSearchTemplate
|
||||
isOpen={isFromWarehouseModalOpen}
|
||||
onClose={() => setIsFromWarehouseModalOpen(false)}
|
||||
title="Buscar Almacén"
|
||||
endpoint="Warehouses"
|
||||
fields={["WarehouseCode", "WarehouseName"]}
|
||||
columns={[
|
||||
{ key: "WarehouseCode", title: "Código", width: "120px" },
|
||||
{ key: "WarehouseName", title: "Nombre" },
|
||||
]}
|
||||
baseFilter=""
|
||||
seleccion="unica"
|
||||
onConfirmarSeleccion={handleFromWarehouseSeleccionado}
|
||||
rowKey="WarehouseCode"
|
||||
/>
|
||||
|
||||
<ModalSearchTemplate
|
||||
isOpen={isToWarehouseModalOpen}
|
||||
onClose={() => setIsToWarehouseModalOpen(false)}
|
||||
title="Buscar Almacén"
|
||||
endpoint="Warehouses"
|
||||
fields={["WarehouseCode", "WarehouseName"]}
|
||||
columns={[
|
||||
{ key: "WarehouseCode", title: "Código", width: "120px" },
|
||||
{ key: "WarehouseName", title: "Nombre" },
|
||||
]}
|
||||
baseFilter=""
|
||||
seleccion="unica"
|
||||
onConfirmarSeleccion={handleToWarehouseSeleccionado}
|
||||
rowKey="WarehouseCode"
|
||||
/>
|
||||
|
||||
<ConfirmModal
|
||||
isOpen={showConfirm}
|
||||
title="Confirmar liberación"
|
||||
onConfirm={handleConfirmRelease}
|
||||
onCancel={() => setShowConfirm(false)}
|
||||
message={
|
||||
selectedRows.length > 0 &&
|
||||
toWarehouse && (
|
||||
<div className="space-y-1">
|
||||
<p>¿Confirma que desea generar la Solicitud de Transferencia en SAP B1?</p>
|
||||
<ul className="mt-2 space-y-0.5 text-[var(--color-text-muted)]">
|
||||
<li>Lote: {result?.Batch}</li>
|
||||
<li>
|
||||
Almacén origen: {fromWarehouse.code} - {fromWarehouse.name}
|
||||
</li>
|
||||
<li>
|
||||
Almacén destino: {toWarehouse.code} - {toWarehouse.name}
|
||||
</li>
|
||||
{selectedRows.map((row) => (
|
||||
<li key={rowKey(row)}>
|
||||
{row.ItemCode} - {row.ItemDescription} · Cantidad:{" "}
|
||||
{selections[rowKey(row)]} UND
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user