@@ -30,10 +30,6 @@ exports.post = ({ appSdk }, req, res) => {
3030 }
3131
3232 const destinationZip = params . to ? params . to . zip . replace ( / \D / g, '' ) : ''
33- const originZip = params . from
34- ? params . from . zip . replace ( / \D / g, '' )
35- : appData . zip ? appData . zip . replace ( / \D / g, '' ) : ''
36-
3733 const checkZipCode = rule => {
3834 // validate rule zip range
3935 if ( destinationZip && rule . zip_range ) {
@@ -43,11 +39,36 @@ exports.post = ({ appSdk }, req, res) => {
4339 return true
4440 }
4541
42+ let originZip , warehouseCode
43+ if ( params . from ) {
44+ originZip = params . from . zip
45+ } else if ( Array . isArray ( appData . warehouses ) && appData . warehouses . length ) {
46+ for ( let i = 0 ; i < appData . warehouses . length ; i ++ ) {
47+ const warehouse = appData . warehouses [ i ]
48+ if ( warehouse && warehouse . zip && checkZipCode ( warehouse ) ) {
49+ const { code } = warehouse
50+ if (
51+ code && params . items &&
52+ params . items . find ( ( { inventory } ) => inventory && Object . keys ( inventory ) . length && ! inventory [ code ] )
53+ ) {
54+ // item not available on current warehouse
55+ continue
56+ }
57+ originZip = warehouse . zip
58+ warehouseCode = code
59+ }
60+ }
61+ }
62+ if ( ! originZip ) {
63+ originZip = appData . zip
64+ }
65+ originZip = typeof originZip === 'string' ? originZip . replace ( / \D / g, '' ) : ''
66+
4667 // search for configured free shipping rule
4768 if ( Array . isArray ( appData . free_shipping_rules ) ) {
4869 for ( let i = 0 ; i < appData . free_shipping_rules . length ; i ++ ) {
4970 const rule = appData . free_shipping_rules [ i ]
50- if ( checkZipCode ( rule ) ) {
71+ if ( rule && checkZipCode ( rule ) ) {
5172 if ( ! rule . min_amount ) {
5273 response . free_shipping_from_value = 0
5374 break
@@ -190,6 +211,7 @@ exports.post = ({ appSdk }, req, res) => {
190211 days : 3 ,
191212 ...appData . posting_deadline
192213 } ,
214+ warehouse_code : warehouseCode ,
193215 flags : [ 'datafrete-ws' , `datafrete-${ serviceCode } ` . substr ( 0 , 20 ) ]
194216 }
195217 } )
0 commit comments