<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.erp.inventory.repository.StockLogRepository">

    <!-- 分页查询库存流水（带条件） -->
    <select id="findByConditions" resultType="com.erp.inventory.entity.StockLog">
        SELECT * FROM stock_logs
        WHERE 1=1
        <if test="skuCode != null and skuCode != ''">
            AND sku_code = #{skuCode}
        </if>
        <if test="warehouseId != null">
            AND warehouse_id = #{warehouseId}
        </if>
        <if test="type != null and type != ''">
            AND type = #{type}
        </if>
        <if test="orderId != null">
            AND order_id = #{orderId}
        </if>
        <if test="deliveryNo != null and deliveryNo != ''">
            AND delivery_no LIKE CONCAT('%', #{deliveryNo}, '%')
        </if>
        <if test="startDate != null">
            AND created_at &gt;= #{startDate}
        </if>
        <if test="endDate != null">
            AND created_at &lt;= #{endDate}
        </if>
        ORDER BY created_at DESC
    </select>

    <!-- 根据预扣凭证查找预扣记录 -->
    <select id="findByReserveToken" resultType="com.erp.inventory.entity.StockLog">
        SELECT * FROM stock_logs
        WHERE remark LIKE CONCAT('%', #{reserveToken}, '%')
        AND type = 'reserve'
        AND order_id = #{orderId}
        ORDER BY id DESC
        LIMIT 1
    </select>

</mapper>
