lodash#hasIn JavaScript Examples

The following examples show how to use lodash#hasIn. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* fundOrderAction(action) {
  const { username, password } = yield select(getUserCredentails);
  yield put({ type: actions.actionStart });
  const { peerID, ...payload } = action.payload;
  try {
    const response = yield call(fundOrder, username, password, payload);

    if (hasIn(response, 'success') && response.success === false) {
      delayedAlert(response.reason);
    } else {
      yield put({ type: actions.fetchPurchases });
      yield put({ type: walletActions.fetchWalletBalance });
      yield put({ type: actions.fetchOrder, payload: payload.orderId });
      yield call(sendNotification, peerID, payload.orderId, 'funded');
    }
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #2
Source File: notification.js    From haven with MIT License 6 votes vote down vote up
filterNotifications = (notifications, type) =>
  notifications.filter((notification) => {
    if (hasIn(notification, 'group') && type === 'social' && SOCIAL_TYPES.includes(notification.verb)) {
      return true;
    }
    if (hasIn(notification, 'type') && getNotificationType(notification.type) === type) {
      return true;
    }
    return false;
  })
Example #3
Source File: purchaseSuccess.js    From haven with MIT License 6 votes vote down vote up
sendMessage() {
    const { message } = this.state;
    const { username, password } = this.props;
    const peerID = this.props.navigation.getParam('peerID');
    const orderInfo = this.props.navigation.getParam('orderInfo');
    sendChat(username, password, peerID, orderInfo.orderId, message).then((response) => {
      if (hasIn(response, 'messageId')) {
        Alert.alert('Successfully sent message');
      }
    });
    sendNotification({ verb: 'chat', type: 'sent', peerID, content: { body: 'You have received a message!' } });
  }
Example #4
Source File: addShippingMethod.js    From haven with MIT License 6 votes vote down vote up
constructor(props) {
    super(props);
    const { shippingOptions } = this.props;
    if (hasIn(props.navigation.state.params, 'idx')) {
      const idx = props.navigation.getParam('idx');
      const selectableCountry = [{ label: '? Worldwide', value: 'ALL' }, ...countryList];
      shippingOptions.forEach((val, i) => {
        if (idx !== i) {
          val.regions.forEach((region) => { remove(selectableCountry, o => o.value === region.value); });
        }
      });
      this.state = {
        name: shippingOptions[idx].name,
        type: shippingOptions[idx].type,
        selectableCountry,
        regions: [...shippingOptions[idx].regions],
        services: [...shippingOptions[idx].services],
      };
    } else {
      const selectableCountry = [{ label: '? Worldwide', value: 'ALL' }, ...countryList];
      shippingOptions.forEach((val) => {
        val.regions.forEach((region) => { remove(selectableCountry, o => o.value === region.value); });
      });
      this.state = {
        name: '',
        type: 'FIXED_PRICE',
        selectableCountry,
        regions: [],
        services: [],
      };
    }
  }
Example #5
Source File: wallet.js    From haven with MIT License 6 votes vote down vote up
function* sendFunds(action) {
  const { data, nextAction } = action.payload;
  const result = yield call(sendBitcoins, data);
  if (hasIn(result, 'confirmedBalance')) {
    if (nextAction) {
      yield call(nextAction);
    }
    eventTracker.trackEvent('Wallet-PaymentSuccess');
    yield put({ type: actions.sendFundsSuccess });
    yield put({ type: actions.fetchWalletBalance });
    yield put({ type: actions.setTxid, payload: result.txid });
    yield put({ type: actions.fetchTransactions, payload: data.wallet });
  } else if (result.success === false) {
    const { reason } = result;
    eventTracker.trackEvent('Wallet-PaymentFailed', reason);
    yield put({ type: actions.sendFundsFailure, payload: getWalletFailureMessage(reason) });
  }
}
Example #6
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* refundOrderAction(action) {
  const { username, password } = yield select(getUserCredentails);
  yield put({ type: actions.actionStart });
  const { orderId, vendorId } = action.payload;
  try {
    const response = yield call(refundOrder, username, password, orderId);
    if (hasIn(response, 'success') && response.success === false) {
      delayedAlert(response.reason);
    } else {
      yield put({ type: actions.fetchSales });
      yield put({ type: walletActions.fetchWalletBalance });
      yield put({ type: actions.fetchOrder, payload: orderId });
      yield call(sendNotification, vendorId, orderId, 'refunded');
    }
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #7
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* claimPaymentAction(action) {
  const { username, password } = yield select(getUserCredentails);
  const { orderId, vendorId } = action.payload;
  yield put({ type: actions.actionStart });

  try {
    const response = yield call(claimPayment, username, password, orderId);

    if (hasIn(response, 'success') && response.success === false) {
      delayedAlert(response.reason);
    } else {
      delayedAlert('You claimed Payment!');
      yield put({ type: actions.fetchPurchases });
      yield put({ type: actions.fetchSales });
      yield put({ type: actions.fetchOrder, payload: orderId });
      yield call(sendNotification, vendorId, orderId, 'releaseEscrow');
    }
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #8
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* acceptPayoutAction(action) {
  const { username, password } = yield select(getUserCredentails);
  const { orderId, orderType, buyerId, vendorId } = action.payload;
  yield put({ type: actions.actionStart });

  try {
    const response = yield call(acceptDispute, username, password, orderId);

    if (hasIn(response, 'success') && response.success === false) {
      delayedAlert(response.reason);
    } else {
      if (orderType === 'purchases') {
        eventTracker.trackEvent('Order-Buyer-AcceptPayout');
      } else {
        eventTracker.trackEvent('Order-Vendor-AcceptPayout');
      }
      yield put({ type: actions.fetchPurchases });
      yield put({ type: actions.fetchSales });
      yield put({ type: actions.fetchOrder, payload: orderId });
      yield call(sendNotification, orderType === 'purchases' ? vendorId : buyerId, orderId, 'resolveDispute');
    }
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #9
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* openDisputeAction(action) {
  const { username, password } = yield select(getUserCredentails);
  const {
    orderId, claim, orderType, callback, vendorId,
  } = action.payload;
  yield put({ type: actions.actionStart });

  try {
    const response = yield call(openDispute, username, password, orderId, claim);

    if (hasIn(response, 'success') && response.success === false) {
      delayedAlert(response.reason);
    } else {
      if (callback) {
        callback();
      }
      if (orderType === 'purchases') {
        eventTracker.trackEvent('Order-Buyer-OpenDispute');
      } else {
        eventTracker.trackEvent('Order-Vendor-OpenDispute');
      }
      yield put({ type: actions.fetchPurchases });
      yield put({ type: actions.fetchSales });
      yield put({ type: actions.fetchOrder, payload: orderId });
      yield call(sendNotification, vendorId, orderId, 'openDispute');
    }
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #10
Source File: stream.js    From haven with MIT License 6 votes vote down vote up
processRequest(apiURL, headers) {
    return fetch(apiURL, headers)
      .then(response => response.json())
      .then((response) => {
        if (hasIn(response, 'message')) {
          if (response.message === 'Token time out') {
            Reactotron.log('re-init stream client from processRequest', new Date());
            this.initStreamClient(true);
          }
          throw Error(response.message);
        } else if (response.error) {
          throw response.error;
        } else {
          return response;
        }
      });
  }
Example #11
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* fulfillOrderAction(action) {
  const { body, onSuccess, onFailure, peerID } = action.payload;
  const { username, password } = yield select(getUserCredentails);
  yield put({ type: actions.actionStart });
  try {
    const response = yield call(fulfillOrder, username, password, body);
    if (hasIn(response, 'success') && response.success === false) {
      if (onFailure) {
        onFailure();
      }
      delayedAlert(response.reason);
    } else {
      const { orderId } = body;
      eventTracker.trackEvent('Order-Vendor-FulfillOrder');
      yield put({ type: actions.fetchSales });
      yield put({ type: actions.fetchOrder, payload: orderId });
      yield call(sendNotification, peerID, orderId, 'fulfilled');
      if (onSuccess) {
        onSuccess();
      }
    }
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #12
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* cancelOrderAction(action) {
  const { username, password } = yield select(getUserCredentails);
  const { peerID, orderId } = action.payload;
  yield put({ type: actions.actionStart });
  try {
    const response = yield call(cancelOrder, username, password, orderId);
    if (hasIn(response, 'success') && response.success === false) {
      delayedAlert(response.reason);
    } else {
      eventTracker.trackEvent('Order-Buyer-CancelOrder');
      yield put({ type: actions.fetchPurchases });
      yield put({ type: walletActions.fetchWalletBalance });
      yield put({ type: actions.fetchOrder, payload: orderId });
      yield call(sendNotification, peerID, orderId, 'cancelled');
    }
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #13
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* confirmOrderAction(action) {
  const { username, password } = yield select(getUserCredentails);
  const { peerID, ...payload } = action.payload;
  yield put({ type: actions.actionStart });
  try {
    const response = yield call(confirmOrder, username, password, payload);
    if (hasIn(response, 'success') && response.success === false) {
      delayedAlert(response.reason);
    } else {
      const { orderId, reject } = payload;
      if (reject) {
        eventTracker.trackEvent('Order-Vendor-DeclineOrder');
      } else {
        eventTracker.trackEvent('Order-Vendor-AcceptOrder');
      }
      yield put({ type: actions.fetchSales });
      yield put({ type: actions.fetchOrder, payload: orderId });
      yield call(sendNotification, peerID, orderId, 'confirmed');
    }
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #14
Source File: order.js    From haven with MIT License 6 votes vote down vote up
function* completeOrderAction(action) {
  const { username, password } = yield select(getUserCredentails);
  const { vendorId, ...payload } = action.payload;
  yield put({ type: actions.actionStart });
  try {
    const response = yield call(completeOrder, username, password, payload);
    if (hasIn(response, 'success') && response.success === false) {
      delayedAlert(response.reason);
    } else {
      eventTracker.trackEvent('Order-Buyer-CompleteOrder');
      yield put({ type: actions.fetchSales });
      yield put({ type: actions.fetchOrder, payload: payload.orderId });
    }
    yield call(sendNotification, vendorId, payload.orderId, 'completed');
  } catch (err) {
    delayedAlert('Error happened because of unknown issues');
  } finally {
    yield put({ type: actions.actionFinished });
  }
}
Example #15
Source File: createListing.js    From haven with MIT License 6 votes vote down vote up
function* updateListingAction(action) {
  const { slug, peerID } = action.payload;
  const { username, password } = yield select(getUserCredentails);
  const structuredData = yield call(generateData, false)
  const result = yield call(updateListing, username, password, structuredData);
  if (hasIn(result, 'success') && result.success === false) {
    const metaType = result.reason.split('Listing_Metadata_')[1];
    yield put({ type: actions.actionFailed });
    if (metaType) {
      Alert.alert(`${metaType} is missing`);
    } else {
      Alert.alert(result.reason);
    }
  } else {
    yield put({
      type: listingAction.fetchListing,
      payload: { slug, peerID },
    });
    yield put({ type: storeListingAction.fetchListings });
    yield put({ type: actions.actionSuccess });
  }
}
Example #16
Source File: createListing.js    From haven with MIT License 6 votes vote down vote up
function* createListingAction(action) {
  const successAction = action.payload;
  const { username, password } = yield select(getUserCredentails);
  const structuredData = yield call(generateData);
  const result = yield call(createListing, username, password, structuredData);
  if (hasIn(result, 'slug')) {
    yield put({ type: actions.resetData });
    yield put({ type: actions.actionSuccess });
    yield call(successAction, get(result, 'slug'));
    eventTracker.trackEvent('CreateListing-Created');
  } else {
    eventTracker.trackEvent('CreateListing-FailedCreation', result.reason);
    const metaType = result.reason.split('Listing_Metadata_')[1];
    yield put({ type: actions.actionFailed });
    if (metaType) {
      Alert.alert(`${metaType} is missing`);
    } else {
      Alert.alert(result.reason);
    }
  }
}
Example #17
Source File: ModerationFee.js    From haven with MIT License 6 votes vote down vote up
fixedInput() {
    const { fee } = this.props;
    const orgFixedAmount = hasIn(fee, 'fixedFee.amount') ? fee.fixedFee.amount : '';
    return (
      <View style={[styles.tabContentWrapper, { height: 48 }]}>
        <TextInput
          noBorder
          title="Fee ($)"
          keyboardType="numeric"
          defaultValue={orgFixedAmount}
          onChangeText={(fee) => {
            this.setState({
              feeType: 'FIXED',
              fixedAmount: fee,
            }, () => {
              this.onChange();
            });
          }}
        />
      </View>
    );
  }
Example #18
Source File: ModerationFee.js    From haven with MIT License 6 votes vote down vote up
fixedPercentage() {
    const { fee } = this.props;
    const orgFixedAmount = hasIn(fee, 'fixedFee.amount') ? fee.fixedFee.amount : '';
    const orgPercentage = hasIn(fee, 'percentage') ? fee.percentage : '';
    return (
      <View style={styles.tabContentWrapper}>
        <TextInput
          title="Flat Fee (%)"
          keyboardType="numeric"
          defaultValue={orgFixedAmount}
          onChangeText={(fixedFee) => {
            this.setState({
              fixedType: 'FIXED_PLUS_PERCENTAGE',
              fixedAmount: fixedFee,
            }, () => {
              this.onChange();
            });
          }}
        />
        <TextInput
          noBorder
          title="Percentage (%)"
          keyboardType="numeric"
          defaultValue={orgPercentage}
          onChangeText={(percentage) => {
            this.setState({
              fixedType: 'FIXED_PLUS_PERCENTAGE',
              percentage,
            }, () => {
              this.onChange();
            });
          }}
        />
      </View>
    );
  }
Example #19
Source File: ModerationFee.js    From haven with MIT License 6 votes vote down vote up
percentageInput() {
    const { fee } = this.props;
    const orgPercentage = hasIn(fee, 'percentage') ? fee.percentage : '';
    return (
      <View style={[styles.tabContentWrapper, { height: 48 }]}>
        <TextInput
          noBorder
          title="Percentage (%)"
          keyboardType="numeric"
          defaultValue={orgPercentage}
          onChangeText={(percentage) => {
            this.setState({
              feeType: 'PERCENTAGE',
              percentage,
            }, () => {
              this.onChange();
            });
          }}
        />
      </View>
    );
  }
Example #20
Source File: CouponModal.js    From haven with MIT License 5 votes vote down vote up
constructor(props) {
    super(props);
    this.state = {
      discountMode: hasIn(props, 'defaultValue.percentDiscount') ? 'percentage' : 'currency',
      value: props.defaultValue,
    };
  }
Example #21
Source File: order.js    From haven with MIT License 5 votes vote down vote up
function* purchaseListingAction(action) {
  const { username, password } = yield select(getUserCredentails);
  const {
    orderData, onSuccess, onHalf, onFailure, walletType, peerID,
  } = action.payload;

  try {
    const response = yield call(purchaseItem, username, password, orderData);
    if (!hasIn(response, 'orderId')) {
      eventTracker.trackEvent('Checkout-PaymentFailed', response.reason);
      yield call(onFailure, response.reason);
    } else {
      if (onHalf) {
        yield call(onHalf, response);
      }

      if (walletType === 'external') {
        return;
      }

      const { amount: amountObj = {}, paymentAddress, orderId } = response;
      const { amount } = amountObj;
      const coin = orderData.paymentCoin;
      const finalResponse = yield call(fundOrder, username, password, {
        amount, address: paymentAddress, orderId, coin, memo: '',
      });
      if (hasIn(finalResponse, 'success') && finalResponse.success === false) {
        eventTracker.trackEvent('Checkout-PaymentFailed', finalResponse.reason);
        yield call(onFailure, finalResponse.reason);
      } else {
        eventTracker.trackEvent('Checkout-PaymentSucceed');
        yield call(onSuccess, finalResponse);
        yield put({ type: actions.fetchPurchases });
        yield put({ type: walletActions.fetchWalletBalance });
        yield put({ type: actions.fetchOrder, payload: orderId });

        yield call(sendNotification, peerID, orderId, 'funded');
      }
    }
  } catch (err) {
    eventTracker.trackEvent('Checkout-PaymentFailed', err);
    if (onFailure) {
      yield call(onFailure, 'Unknown error');
    }
  }
}
Example #22
Source File: MultiSelector.js    From haven with MIT License 5 votes vote down vote up
render() {
    const { selection, showModal } = this.state;
    const { options, title, required } = this.props;
    let text = 'None';
    if (selection.length === 1) {
      if (selection[0] === 'ALL') {
        const idx = findIndex(options, option => option.value === 'ALL');
        if (idx >= 0) {
          text = options[idx].label;
        } else {
          text = 'All';
        }
      } else if (hasIn(selection, '[0].label')) {
        text = selection[0].label;
      } else {
        const idx = findIndex(options, option => option.value.toLowerCase() === selection[0].toLowerCase());
        text = options[idx].label;
      }
    } else if (selection.length > 1) {
      text = `${selection.length} selected`;
    }
    return (
      <View style={styles.wrapper}>
        <TouchableWithoutFeedback onPress={this.onShowSelector}>
          <View style={styles.optionTrigger}>
            <Text style={styles.title}>
              {title}
              <Text style={required ? { color: 'red' } : {}}>{required ? '*' : ''}</Text>
            </Text>
            <Text style={styles.input} numberOfLines={1} ellipsizeMode="tail">{text}</Text>
            <Ionicons
              name="ios-arrow-forward"
              size={18}
              color={primaryTextColor}
              style={styles.icon}
            />
          </View>
        </TouchableWithoutFeedback>
        <OBLightModal
          animationType="slide"
          transparent
          visible={showModal}
          onRequestClose={this.onClose}
        >
          <Header
            modal
            title=""
            left={<NavBackButton />}
            onLeft={this.onClose}
            right={<LinkText text="Done" />}
            onRight={this.onClose}
          />
          <FlatList
            keyExtractor={this.keyExtractor}
            renderItem={this.renderItem}
            data={options}
            extraData={selection}
          />
          {selection.length > 0 && (
            <View style={styles.selectionIndicatorWrapper}>
              <Text style={styles.selectedIndicator}>
                {selection.length} Selected
              </Text>
              <TouchableOpacity onPress={this.resetSelection}>
                <LinkText text="Reset" />
              </TouchableOpacity>
            </View>
          )}
        </OBLightModal>
      </View>
    );
  }
Example #23
Source File: dataMapping.js    From haven with MIT License 5 votes vote down vote up
bundleCoupon = (value) => {
  const newVal = { ...value };
  if (hasIn(value, 'priceDiscount')) {
    newVal.bigPriceDiscount = value.priceDiscount.toString();
    delete newVal.priceDiscount;
  }
  return newVal;
}
Example #24
Source File: dataMapping.js    From haven with MIT License 4 votes vote down vote up
restructureListingInfo = (
  listingInfo,
  acceptedCurrencies,
  moderators = [],
  isCreating = true,
) => {
  const slug = isCreating ? uuidv4() : listingInfo.slug;
  const { type = {}, currency, shippingOptions, termsAndConditions, refundPolicy } = listingInfo || {};
  const contractType = (type.value || type).toUpperCase();
  const metadata = {
    contractType,
    format: 'FIXED_PRICE',
    expiry: '2037-12-31T05:00:00.000Z',
    escrowTimeoutHours: 1080,
    acceptedCurrencies,
  };
  const options = listingInfo.options.map((val) => {
    const { name, description, variants } = val;
    const parsedVariants = variants.map(val => ({ name: val }));
    return {
      name,
      description,
      variants: parsedVariants,
    };
  });
  const images = filter(listingInfo.images, o => !isEmpty(o)).map(val => ({
    filename: val.filename,
    ...val.hashes,
  }));
  const item = {
    priceCurrency: getBigCurrencyInfo(currency, true),
    title: listingInfo.title,
    description: listingInfo.description,
    bigPrice: getPriceInMinimumUnit(listingInfo.price, currency).toString(),
    tags: listingInfo.tags,
    images,
    categories: listingInfo.categories,
    options,
    condition: hasIn(listingInfo.condition, 'label')
      ? listingInfo.condition.label
      : listingInfo.condition,
    skus: listingInfo.inventory.map(({ quantity, surcharge, ...val }) => ({
      ...val,
      bigSurcharge: getPriceInMinimumUnit(surcharge, currency),
      bigQuantity: quantity.toString(),
    })),
    nsfw: listingInfo.nsfw,
  };
  const reShippingOptions = shippingOptions.map((val) => {
    const {
      name, type, regions, services,
    } = val;
    const newRegions = regions.map((region) => {
      if (hasIn(region, 'value')) {
        if (region.value === 'any') {
          return 'ALL';
        }
        return region.value.toUpperCase();
      }
      return region.toUpperCase();
    });
    return {
      name,
      type,
      regions: newRegions,
      services: services.map((val) => {
        const { price, additionalItemPrice, ...restVal } = val;
        return {
          ...restVal,
          bigPrice: getPriceInMinimumUnit(price, currency).toString(),
          bigAdditionalItemPrice: getPriceInMinimumUnit(additionalItemPrice, currency).toString(),
        };
      }),
    };
  });
  const taxes = [];
  const { coupons = [] } = listingInfo;

  return {
    slug: isCreating ? '' : slug,
    metadata,
    item,
    shippingOptions: contractType === 'PHYSICAL_GOOD' ? reShippingOptions : undefined,
    termsAndConditions,
    refundPolicy,
    taxes,
    coupons: coupons.map(bundleCoupon),
    moderators,
  };
}