src/main/resources/mapper/stock/StockInventoryMapper.xml
@@ -671,4 +671,58 @@
        batch_no
    </select>
    <!-- 分页查询产品库存和领用量(按批号区分) -->
    <select id="pageStockAndBorrow" resultType="com.ruoyi.stock.dto.StockInventoryDto">
        WITH RECURSIVE product_tree AS (
            SELECT id
            FROM product
            WHERE id = #{ew.topParentProductId}
            UNION ALL
            SELECT p.id
            FROM product p
            INNER JOIN product_tree pt ON p.parent_id = pt.id
        )
        SELECT
            pm.id as product_model_id,
            pm.model,
            pm.product_code,
            pm.unit,
            p.product_name,
            p.id as product_id,
            si.batch_no,
            IFNULL(si.qualitity, 0) as qualitity,
            IFNULL(si.locked_quantity, 0) as locked_quantity,
            IFNULL(borrowed.borrowed_quantity, 0) as borrowed_quantity,
            IFNULL(si.qualitity, 0) - IFNULL(borrowed.borrowed_quantity, 0) as available_quantity
        FROM product_model pm
        LEFT JOIN product p ON pm.product_id = p.id
        LEFT JOIN stock_inventory si ON pm.id = si.product_model_id
        LEFT JOIN (
            SELECT
                product_model_id,
                batch_no,
                SUM(borrow_quantity - IFNULL(returned_quantity, 0)) as borrowed_quantity
            FROM product_borrow
            WHERE approval_status = 1
              AND status != 2
            GROUP BY product_model_id, batch_no
        ) borrowed ON pm.id = borrowed.product_model_id
            AND (si.batch_no = borrowed.batch_no OR (si.batch_no IS NULL AND borrowed.batch_no IS NULL))
        <where>
            <if test="ew.topParentProductId != null and ew.topParentProductId > 0">
                AND p.id IN (SELECT id FROM product_tree)
            </if>
            <if test="ew.productName != null and ew.productName != ''">
                AND p.product_name LIKE CONCAT('%', #{ew.productName}, '%')
            </if>
            <if test="ew.model != null and ew.model != ''">
                AND pm.model LIKE CONCAT('%', #{ew.model}, '%')
            </if>
            <if test="ew.batchNo != null and ew.batchNo != ''">
                AND si.batch_no LIKE CONCAT('%', #{ew.batchNo}, '%')
            </if>
        </where>
        ORDER BY pm.id DESC, si.batch_no
    </select>
</mapper>