react-native-elements#Avatar JavaScript Examples

The following examples show how to use react-native-elements#Avatar. 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: CustomSidebarMenu.js    From barter-app-stage-11 with MIT License 6 votes vote down vote up
render(){
    return(
      <View style={{flex:1}}>
        <View
          style={{
            flex: 0.5,
            alignItems: "center",
            backgroundColor: "orange",
          }}
          >
          <Avatar
            rounded
            source={{
              uri: this.state.image,
            }}
            size="medium"
            onPress={() => this.selectPicture()}
            containerStyle={styles.imageContainer}
            showEditButton
          />

          <Text style={{ fontWeight: "100", fontSize: 20, paddingTop: 10 }}>
            {this.state.name}
          </Text>
        </View>

        <DrawerItems {...this.props}/>
        <View style={{flex:1,justifyContent:'flex-end',paddingBottom:30}}>
          <TouchableOpacity style={{justifyContent:'center',padding:10,height:30,width:'100%'}}
          onPress = {() => {
              this.props.navigation.navigate('WelcomeScreen')
              firebase.auth().signOut()
          }}>
            <Text>Logout</Text>
          </TouchableOpacity>
        </View>
      </View>
    )
  }
Example #2
Source File: CustomSideBarMenu.js    From book-santa-stage-12 with MIT License 5 votes vote down vote up
render() {
    return (
      <View style={{ flex: 1 }}>
        <View
          style={{
            flex: 0.5,

            alignItems: "center",
            backgroundColor: "orange",
          }}
        >
          <Avatar
            rounded
            source={{
              uri: this.state.image,
            }}
            size="medium"
            onPress={() => this.selectPicture()}
            containerStyle={styles.imageContainer}
            showEditButton
          />

          <Text style={{ fontWeight: "100", fontSize: 20, paddingTop: 10 }}>
            {this.state.name}
          </Text>
        </View>

        <View style={styles.drawerItemsContainer}>
          <DrawerItems {...this.props} />
        </View>
        <View style={styles.logOutContainer}>
          <TouchableOpacity
            style={styles.logOutButton}
            onPress={() => {
              this.props.navigation.navigate("WelcomeScreen");
              firebase.auth().signOut();
            }}
          >
            <Text>Log Out</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
Example #3
Source File: CustomSideBarMenu.js    From book-santa-stage-11 with MIT License 5 votes vote down vote up
render() {
    return (
      <View style={{ flex: 1 }}>
        <View
          style={{
            flex: 0.5,

            alignItems: "center",
            backgroundColor: "orange",
          }}
        >
          <Avatar
            rounded
            source={{
              uri: this.state.image,
            }}
            size="medium"
            onPress={() => this.selectPicture()}
            containerStyle={styles.imageContainer}
            showEditButton
          />

          <Text style={{ fontWeight: "100", fontSize: 20, paddingTop: 10 }}>
            {this.state.name}
          </Text>
        </View>

        <View style={styles.drawerItemsContainer}>
          <DrawerItems {...this.props} />
        </View>
        <View style={styles.logOutContainer}>
          <TouchableOpacity
            style={styles.logOutButton}
            onPress={() => {
              this.props.navigation.navigate("WelcomeScreen");
              firebase.auth().signOut();
            }}
          >
            <Text>Log Out</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
Example #4
Source File: CustomSideBarMenu.js    From book-santa-stage-10 with MIT License 5 votes vote down vote up
render(){
    return(
      <View style={{flex:1}}>
        <View style={{flex:0.5,borderColor:'red',borderWidth:2,alignItems:'center',backgroundColor:'orange'}}>

            <Avatar
                rounded
                icon={{name: 'user', type: 'font-awesome'}}
                source={{
                  uri:
                    this.state.image
                  }}
                size="medium"

                 overlayContainerStyle={{backgroundColor: 'white'}}
                 onPress={() => this.selectPicture()}
                 activeOpacity={0.7}
                 containerStyle={{flex:0.75,width:'40%',height:'20%', marginLeft: 20, marginTop: 30,borderRadius:40}}
              />


            <Text style = {{fontWeight:'100',fontSize:20,paddingTop:10,}}> {this.state.name}</Text>

        </View>

        <View style={styles.drawerItemsContainer}>
          <DrawerItems {...this.props}/>
        </View>
        <View style={styles.logOutContainer}>
          <TouchableOpacity style={styles.logOutButton}
          onPress = {() => {
              this.props.navigation.navigate('WelcomeScreen')
              firebase.auth().signOut()
          }}>
            <Text>Log Out</Text>
          </TouchableOpacity>
        </View>
      </View>
    )
  }
Example #5
Source File: CustomSidebarMenu.js    From barter-app-stage-12 with MIT License 5 votes vote down vote up
render() {
    return (
      <View style={{ flex: 1 }}>
        <View
          style={{
            flex: 0.3,
            justifyContent: "center",
            alignItems: "center",
            backgroundColor: "#32867d",
          }}
        >
          <Avatar
            rounded
            source={{
              uri: this.state.image,
            }}
            size={"xlarge"}
            onPress={() => this.selectPicture()}
            showEditButton
          />

          <Text
            style={{
              fontWeight: "300",
              fontSize: RFValue(20),
              color: "#fff",
              padding: RFValue(10),
            }}
          >
            {this.state.name}
          </Text>
        </View>
        <View style={{ flex: 0.6 }}>
          <DrawerItems {...this.props} />
        </View>
        <View style={{ flex: 0.1 }}>
          <TouchableOpacity
            style={{
              flexDirection: "row",
              width: "100%",
              height: "100%",
            }}
            onPress={() => {
              this.props.navigation.navigate("WelcomeScreen");
              firebase.auth().signOut();
            }}
          >
            <Icon
              name="logout"
              type="antdesign"
              size={RFValue(20)}
              iconStyle={{ paddingLeft: RFValue(10) }}
            />

            <Text
              style={{
                fontSize: RFValue(15),
                fontWeight: "bold",
                marginLeft: RFValue(30),
              }}
            >
              Log Out
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
Example #6
Source File: index.js    From guardioes-app with Apache License 2.0 5 votes vote down vote up
styles = StyleSheet.create({
    Avatar: {
        borderColor: '#ffffff',
        borderWidth: 3,
    },
})
Example #7
Source File: CustomDrawerContent.js    From atendimento-e-agilidade-medica-AAMed with MIT License 5 votes vote down vote up
export default function CustomDrawerContent(props) {
  const [, { logout }] = useAuth();
  const [user, setUser] = useState(null || '');

  // A função getUserLogged recupera os dados do usuário por meio de uma Promise
  // que é executada assim que o componente e montado
  useEffect(() => {
    function getUserLogged() {
      // O uso da Promise + setTmeout foi necessário pois leva um tempo até os dados do AsyncStorage sejam recuperados
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          // A função resolve() irá conter os dados do usuário após 2s definidos no setTimeout()
          resolve(AsyncStorage.getItem('store'));
        }, 2000);
      });
    }
    getUserLogged()
      .then(data => {
        // Para acessar os dados recuperados é usado o .then()
        // Como os dados armazenados estão em formato de string, é utilizado o JSON.parse() para tranforma-los em objeto
        const dataParse = JSON.parse(data);
        // Após esse processo teremos um objeto que terá dentro outro objeto "auth", nele está os dados do usuário além do token
        // Como só é necessário apenas o usuário, o estado é setado apenas com os dados do mesmo (id, nome, bio, etc.)
        setUser(dataParse.auth.user);
      })
      .catch(err => console.log(err)); // Por fim é usado um .catch() para tratar algum erro
  }, []);

  return (
    <DrawerContentScrollView {...props}>
      <View style={styles.topDrawer}>
        <View style={styles.viewAvatar}>
          <Avatar
            avatarStyle={styles.avatarStyle}
            containerStyle={styles.avatarContainerStyle}
            onPress={() => props.navigation.navigate('EditProfile')}
            activeOpacity={0.7}
            size="medium"
            rounded
            title={user ? JSON.stringify(user.name[0]) : 'a'}
          />
        </View>
        <View style={styles.viewDados}>
          <Text style={styles.nameUser}>{user.name}</Text>
          <Text style={styles.bioUser}>{user.bio}</Text>
        </View>
      </View>

      <DrawerItemList {...props} />
      <View style={styles.separator} />
      <DrawerItem
        onPress={logout}
        label="SAIR"
        style={styles.drawerItem}
        labelStyle={styles.drawerItemLabel}
        icon={() => <Feather name="log-out" size={20} color="#E53935" />}
      />
    </DrawerContentScrollView>
  );
}
Example #8
Source File: listitem.playground.jsx    From playground with MIT License 5 votes vote down vote up
ListItemPlayground = () => {
  const params = useView({
    componentName: "ListItem",
    props: {
      children: {
        type: PropTypes.ReactNode,
        value: `<Avatar source={{uri: "https://avatars0.githubusercontent.com/u/32242596?s=460&u=1ea285743fc4b083f95d6ee0be2e7bb8dcfc676e&v=4"}} /> 
          <ListItem.Content>
            <ListItem.Title><Text>Pranshu Chittora</Text></ListItem.Title>
            <ListItem.Subtitle><Text>React Native Elements</Text></ListItem.Subtitle>
          </ListItem.Content>`,
      },
      bottomDivider: {
        type: PropTypes.Boolean,
        value: false,
      },
      Component: {
        type: PropTypes.Object,
        value: `TouchableHighlight`,
        description:
          "View or TouchableHighlight (default) if onPress method is added as prop",
      },
      containerStyle: {
        type: PropTypes.Object,
        value: `{}`,
      },
      disabled: {
        type: PropTypes.Boolean,
        value: false,
      },
      disabledStyle: {
        type: PropTypes.Object,
        value: `{opacity:0.5}`,
      },
      onLongPress: {
        type: PropTypes.Function,
        value: `() => console.log("onLongPress()")`,
      },
      onPress: {
        type: PropTypes.Function,
        value: `() => console.log("onLongPress()")`,
      },
      pad: {
        type: PropTypes.Number,
        value: 20,
      },
      topDivider: {
        type: PropTypes.Boolean,
        value: false,
      },
      ViewComponent: {
        type: PropTypes.Object,
        value: ``,
        description: "ontainer for linear gradient (for non-expo user)",
      },
    },
    scope: {
      ListItem,
      Avatar,
      Text,
      TouchableHighlight,
    },
    imports: {
      "react-native-elements": {
        named: ["ListItem", "Avatar"],
      },
      "react-native": {
        named: ["TouchableHighlight"],
      },
    },
  });

  return (
    <React.Fragment>
      <Playground params={params} />
    </React.Fragment>
  );
}
Example #9
Source File: SearchScreen.js    From hero with MIT License 4 votes vote down vote up
SearchScreen = ({ navigation }) => {
  const [query, setQuery] = useState("");
  const [XMen, popularHeroes, villains] = useContext(HeroesContext);
  const [heroNames, setHeroNames] = useState([]);
  const [filteredHeroNames, setFilteredHeroNames] = useState([]);
  const [loadingSearch, setLoadingSearch] = useState(false);
  const [loading, setLoading] = useState(false);

  const fetchHeroes = async () => {
    try {
      setLoadingSearch(true);
      const response = await fetch(
        "https://cdn.jsdelivr.net/gh/akabab/[email protected]/api/all.json"
      );
      const herojson = await response.json();

      setHeroNames(herojson);
      // heroNames.forEach((hero) => {
      //   console.log(hero.name);
      // });
      setLoadingSearch(false);
    } catch (error) {
      console.error(error);
      setLoadingSearch(false);
    }
  };

  const renderFooter = () => {
    if (!loadingSearch) return null;

    return (
      <View
        style={{
          paddingVertical: 20,
          borderTopWidth: 1,
          borderColor: "#CED0CE",
        }}
      >
        <ActivityIndicator animating size="large" />
      </View>
    );
  };

  const renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: COLORS.navy,
          borderRadius: 50,
          marginLeft: "7%",
        }}
      />
    );
  };

  const handleSearch = (text) => {
    const formattedQuery = text.toLowerCase();
    const data = heroNames.filter((item) => {
      // return contains(name, formattedQuery);
      return item.name.toLowerCase().includes(formattedQuery);
    });
    setFilteredHeroNames(data);
    setQuery(text);
    // this.setState({ data, query: text })
  };

  const search = async (item) => {
    try {
      setLoading(true);
      const searchResponse = await fetch(
        `https://superheroapi.com/api/${api.key}/${item.id}/`,
        {
          method: "GET",
        }
      );
      // console.log(item.biography.fullName);
      // const realName = item.biography.fullName.text();
      const characterResponse = await fetch(
        `https://comicvine.gamespot.com/api/characters/?api_key=${apiComicVine.key}&filter=name:${item.name},publisher:${item.biography.publisher},real_name:${item.biography.fullName},origin:${item.appearance.race}&field_list=deck,publisher,first_appeared_in_issue&format=json`,
        {
          method: "GET",
        }
      );
      const hero = await searchResponse.json();
      const characterInfo = await characterResponse.json();
      // console.log(characterInfo);
      {
        characterInfo.results[0].deck == undefined
          ? (summary = "no summary")
          : (summary = characterInfo.results[0].deck);
      }
      // summary = characterInfo.results[0].deck;
      firstIssue = characterInfo.results[0].first_appeared_in_issue;
      publisher = characterInfo.results[0].publisher.name;
      const firstComicResponse = await fetch(
        `https://comicvine.gamespot.com/api/issue/4000-${firstIssue.id}/?api_key=${apiComicVine.key}&format=json`,
        {
          method: "GET",
        }
      );
      const firstComicInfo = await firstComicResponse.json();
      // console.log(firstComicInfo);
      firstIssueURL = firstComicInfo.results.image.original_url;
      navigation.navigate("Character", {
        hero: hero,
        image: { uri: item.images.lg },
        // publisher: item.publisher,
        comicPicture: comicPicture,
        summary: summary,
        firstIssue: firstIssue,
        firstIssueURL: firstIssueURL,
        publisher: publisher,
      });
      setLoading(false);
    } catch (error) {
      console.error(error);
      setLoading(false);
      Alert.alert("Sorry!", "Hero Not Found");
    }
  };

  useEffect(() => {
    fetchHeroes();
    setLoading(false);
  }, []);

  return (
    <View style={styles.appContainer}>
      <StatusBar
        translucent
        backgroundColor="transparent"
        barStyle="dark-content"
      />
      <SafeAreaView>
        <View style={styles.header}>
          <Text style={styles.appTitle}>search</Text>
        </View>
        {/* <KeyboardAvoidingView
          style={{
            paddingHorizontal: 15,
            marginBottom: -20,
            zIndex: 5,
            backgroundColor: "transparent",
          }}
        > */}
        <SearchBar
          placeholder="Search..."
          onChangeText={handleSearch}
          value={query}
          containerStyle={styles.inputContainer}
          inputContainerStyle={styles.input}
          inputStyle={styles.inputText}
          searchIcon={{ size: 25 }}
          round={true}
        />
        {/* </KeyboardAvoidingView> */}
        <BigList
          itemHeight={ITEM_HEIGHT}
          headerHeight={0}
          footerHeight={0}
          style={{
            position: "absolute",
            width: "100%",
            marginTop: 20,
            paddingTop: 10,
            height: Platform.OS === "ios" ? 580 : 590,
          }}
          data={
            filteredHeroNames && filteredHeroNames.length > 0
              ? filteredHeroNames
              : heroNames
          }
          renderItem={({ item }) => (
            <TouchableOpacity onPress={() => search(item)}>
              <View
                style={{
                  flexDirection: "row",
                  padding: 10,
                  // paddingTop: 30,
                  paddingHorizontal: 15,
                  alignItems: "center",
                  borderBottomColor: COLORS.navy,
                  borderBottomWidth: 2,

                  // backgroundColor: COLORS.navy,
                  marginBottom: 15,
                  // marginHorizontal: 10,
                  borderRadius: 15,
                }}
              >
                <Avatar
                  rounded
                  source={{ uri: item.images.md }}
                  size="medium"
                  containerStyle={{
                    marginRight: 13,
                    borderColor: COLORS.navy,
                    borderWidth: 2,
                    top: 0,
                  }}
                />
                {/* <Image
                  source={{ uri: item.images.sm }}
                  style={{ width: "100%", height: 90, borderRadius: 10 }}
                /> */}
                <Text
                  style={{
                    ...styles.p,
                    fontFamily: "Flame-Regular",
                    color: COLORS.navy,
                  }}
                >
                  {item.name}
                </Text>
              </View>
            </TouchableOpacity>
          )}
          keyExtractor={(item) => item.id.toString()}
          // ItemSeparatorComponent={renderSeparator}
          renderFooter={renderFooter}
          // ListHeaderComponent={}
        />
        <LinearGradient
          colors={[COLORS.beige, "#ffffff00"]}
          style={styles.scrollGradient}
          locations={[0, 1]}
          pointerEvents={"none"}
        />
        {loading === true ? (
          <Modal statusBarTranslucent={true}>
            <View
              style={{
                backgroundColor: COLORS.beige,
                width: "100%",
                height: "100%",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <Progress.CircleSnail
                color={[COLORS.navy, COLORS.orange, COLORS.blue]}
                size={80}
                thickness={10}
                style={styles.loading}
                strokeCap={"round"}
              />
              <Text
                style={{
                  ...styles.p,
                  fontFamily: "Flame-Regular",
                  marginTop: -15,
                  left: 3,
                }}
              >
                loading...
              </Text>
            </View>
          </Modal>
        ) : null}
      </SafeAreaView>
    </View>
  );
}
Example #10
Source File: index.js    From spree-react-native with MIT License 4 votes vote down vote up
ProductDetailScreen = ({ dispatch, product, auth, saving }) => {
  const [pincode, setPincode] = useState('')

  const [isVariantSelected, setIsVariantSelected] = useState(true)
  const [activeColor, setActiveColor] = useState(product.default_variant.option_values[0].presentation)
  const [activeSize, setActiveSize] = useState('')
  const [selectedVariant, setSelectedVariant] = useState({})
  const [imageURI, setImageURI] = useState(`${HOST}/${product.variants[0].images[0].styles[3].url}`)

  const [snackbarVisible, setSnackbarVisible] = useState(false)

  const [variantDistinctColors] = useState([...new Set(product.variants.map(variant => variant.option_values[0].presentation))])

  const handleColorSelection = ({index, color}) => {
    setActiveColor(color)
    setActiveSize('')
    setSelectedVariant({})
    setIsVariantSelected(true)
    setImageURI(`${HOST}/${product.variants[index].images[0].styles[3].url}`)
  }

  const handleAddToBag = () => {
    dispatch(addItem(
      {
        variant_id: selectedVariant.id,
        quantity: 1,
      }
    ))
    // setSnackbarVisible(true)
  }

  if(saving) {
    return (
      <ActivityIndicatorCard />
    )
  } else
  return (
    <>
      <ScrollView style={globalStyles.containerFluid}>
        <MyCarousel key={imageURI} imageURI={imageURI} />
        <View style={ styles.containerFluid }>
          <View style={[ globalStyles.container, globalStyles.pb16 ]}>
            <Text style={ globalStyles.latoBold18 }>{ product.name }</Text>
            <Text style={ styles.description }>{ product.description }</Text>
            <View style={[ styles.pricingContainer, globalStyles.mt8 ]}>
              <Text style={ styles.discountedPrice }>{ product.display_price }</Text>
              <Text style={ styles.price }>$32.90</Text>
              <Text style={ styles.discountPercent }>(20% OFF)</Text>
              <Text style={[ globalStyles.latoBold14, globalStyles.textSuccess ]}>Inclusive of all taxes</Text>
            </View>
          </View>
        </View>
        <View style={[ styles.containerFluid, globalStyles.mt16 ]}>
          <View style={[ globalStyles.container, globalStyles.pv8 ]}>
            <Text style={ globalStyles.latoBold14 }>You get it for
              <Text style={[ globalStyles.prices, globalStyles.textPrimary ]}> $25.49</Text>
              <Text style={[ globalStyles.prices, globalStyles.textSuccess ]}> (Save $4.50)</Text>
            </Text>
          </View>
        </View>
        <View style={[ styles.containerFluid, globalStyles.mt8 ]}>
          <View style={[ globalStyles.container, globalStyles.pv8 ]}>
            <View style={styles.rowContainer}>
              <Button
                title="Save For Later"
                type="outline"
                disabled={isVariantSelected}
                disabledStyle={{ borderColor: colors.gray, color: colors.gray }}
                containerStyle={{ flex: 1, marginRight: 16 }}
                buttonStyle={globalStyles.btn}
                titleStyle={styles.titleStyle}
                onPress={() => dispatch(setProductFavourite(selectedVariant))}
              />
              <Button
                title="Add To Bag"
                type="solid"
                disabled={isVariantSelected}
                disabledStyle={{ backgroundColor: colors.gray }}
                disabledTitleStyle={{ color: colors.white }}
                containerStyle={{flex: 1}}
                buttonStyle={[ globalStyles.btn, globalStyles.btnSolid ]}
                onPress={handleAddToBag}
              />
            </View>
            <View style={ globalStyles.mt16 }>
              <Text style={ globalStyles.latoBold14 }>Select Color</Text>
              <ScrollView horizontal={true} style={[ styles.rowContainer, globalStyles.mt8 ]}>
                {
                  variantDistinctColors.map((color, index) => (
                    <Avatar
                      key={index}
                      size="small"
                      rounded
                      onPress={() => handleColorSelection(
                        {
                          index: index,
                          color: color
                        }
                      )}
                      containerStyle={{
                        backgroundColor: `${color}`,
                        marginRight: 16,
                        borderWidth: 1,
                        padding: 1,
                        borderColor: color !== activeColor ? colors.gray : colors.primary
                      }}
                    />
                  ))
                }
              </ScrollView>
            </View>
            <View>
              {activeColor ? <View style={[ styles.sizingTitleContainer, globalStyles.mt16 ]}>
                <Text style={[ globalStyles.latoBold14, globalStyles.textDark ]}>Select Size</Text>
                <Text style={[ globalStyles.latoBold14, globalStyles.textPrimary ]}>Size Help?</Text>
              </View> : null }
              <View style={[ styles.rowContainer, globalStyles.mt8 ]}>
                {
                  product.variants.map((variant, index) => {
                    if(variant.option_values[0].presentation === activeColor) {
                      return <Avatar
                        key={index}
                        size="small"
                        title={`${variant.option_values[1].presentation}`}
                        onPress={() => {
                            setActiveSize(variant.option_values[1].presentation)
                            setSelectedVariant(variant)
                            setIsVariantSelected(false)
                          }
                        }
                        rounded
                        activeOpacity={0.7}
                        containerStyle={{
                          backgroundColor: colors.white,
                          marginRight: 16,
                          borderColor: variant.option_values[1].presentation !== activeSize ? colors.black : colors.primary,
                          borderWidth: 1
                        }}
                        titleStyle={[globalStyles.latoBold14, 
                          variant.option_values[1].presentation !== activeSize ? globalStyles.textDark : globalStyles.textPrimary
                        ]}
                      />
                    } else { return null }
                  })
                }
              </View>
            </View>
          </View>
        </View>
        <View style={[ styles.containerFluid, globalStyles.mt8, globalStyles.pv8 ]}>
          <View style={ globalStyles.container }>
            <View>
              <Text style={ globalStyles.latoBold14 }>Product Detail & Care</Text>
              <View style={[ styles.unorderedListItem, globalStyles.mt8 ]}>
                {
                  product.product_properties.map(property => (
                    <Text key={property.id} style={globalStyles.label}>
                      {'\u2022'} {capitalizeFirstLetter(property.name)}: {property.value}
                    </Text>
                  ))
                }
              </View>
            </View>
            <View style={ globalStyles.mt16 }>
              <Text style={ globalStyles.latoBold14 }>Description</Text>
              <Text style={[ globalStyles.label, globalStyles.mt8 ]}>
                { product.description }
              </Text>
            </View>
            <View style={ globalStyles.mt16 }>
              <Text style={ globalStyles.latoBold14 }>Manufacturer</Text>
              <Text style={[ globalStyles.label, globalStyles.mt8 ]}>Freeway Clothing Co, 768/1, Vijaynagar, New Delhi 116708</Text>
            </View>
            <View style={ globalStyles.mt16 }>
              <Text style={ globalStyles.latoBold14 }>Manufacturer Country</Text>
              <Text style={[ globalStyles.label, globalStyles.mt8 ]}>India</Text>
            </View>
          </View>
        </View>
        <View style={[ styles.containerFluid, globalStyles.mt8, globalStyles.pv8 ]}>
          <View style={ globalStyles.container }>
            <Text style={ globalStyles.latoBold14 }>Customer Reviews (309)</Text>
            {
              [{
                id: 0,
                review: 'Purchasing the dress online was super easy and they were delivered quick. My partner absolutely loves his new dress! Perfect! All she had to do was swap them over with his old party dress.',
                reviewer: 'Devendar Rathore',
                date: 'Aug 19, 2020',
                likes: 16,
                dislikes: 7
              },
              {
                id: 1,
                review: 'My old dress was become dull and stale. But this new dress is super amazing and fits nicely to me. Thanks for super quick delivery and good service.',
                reviewer: 'Devendar Rathore',
                date: 'Aug 19, 2020',
                likes: 46,
                dislikes: 6
              }].map((item, i, arr) => (
                <View key={item.id} style={ globalStyles.pv8 }>
                  <Text style={globalStyles.latoRegular}>{ item.review }</Text>
                  <View style={styles.reviewFooter}>
                    <Text style={globalStyles.label}>{ item.reviewer }  | { item.date }</Text>
                    <View style={styles.likesDislikesContainer}>
                      <View style={styles.likesContainer}>
                        <Smile size={20} style={{color: colors.gray}}/>
                        <Text style={globalStyles.label}> { item.likes }</Text>
                      </View>
                      <View style={styles.likesContainer}>
                        <SmileSad size={20} style={{color: colors.gray}}/>
                        <Text style={globalStyles.label}> { item.dislikes }</Text>
                      </View>
                    </View>
                  </View>
                  { i !== arr.length - 1  && <Divider style={styles.reviewBorder} /> }
                </View>
              ))
            }
            <TouchableOpacity>
              <Text style={styles.reviewFooterAction}>View All (309)</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View style={[ styles.containerFluid, globalStyles.mt8, globalStyles.pv8 ]}>
          <View style={ globalStyles.container }>
            <Text style={[ globalStyles.latoBold14, globalStyles.mb8 ]}>Check Delivery</Text>
            <TextField
              placeholder=" Enter PIN Code"
              containerStyle={styles.inputWrapperStyle}
              rightElement={<Text style={styles.inputRight}>Check</Text>}
              onChangeText={setPincode}
              value={pincode}
            />
            <View style={ styles.deliveryOffersContainer }>
              <ShoppingCart size={18} style={[styles.deliveryOffersIcon, {transform: [{ rotateY: '180deg' }]} ]}/>
              <Text style={ globalStyles.latoBold14 }>Delivery by Thursday, Sep 05</Text>
            </View>
            <View style={ styles.deliveryOffersContainer }>
              <Dollar size={18} style={ styles.deliveryOffersIcon }/>
              <Text style={ globalStyles.latoBold14 }>Cash on delivery available</Text>
            </View>
            <View style={ styles.deliveryOffersContainer }>
              <Repeat size={18} style={ styles.deliveryOffersIcon }/>
              <Text style={ globalStyles.latoBold14 }>Return & exchange available within 10 days</Text>
            </View>
          </View>
        </View>
        <View style={[ styles.containerFluid, globalStyles.mt8, globalStyles.pv16 ]}>
          <View style={globalStyles.container}>
            <View style={styles.alikeProductsHeader}>
              <Text style={[ globalStyles.latoBold14, globalStyles.mb16 ]}>Your might also like</Text>
              <Text style={[ globalStyles.label, globalStyles.latoBold14 ]}>12 more</Text>
            </View>
          </View>
          <ScrollView horizontal={true} style={styles.carouselProductsContainer}>
            <CarouselProductCard imageURI={imageURI} />
            <CarouselProductCard imageURI={imageURI} />
            <CarouselProductCard imageURI={imageURI} />
          </ScrollView>
        </View>
        <View style={styles.footerContainer}>
          <View style={styles.footerItemListContainer}>
            <View style={styles.footerItemContainer}>
              <CustomIconTruck size={32} style={styles.footerIcon} />
              <Text style={styles.footerText}>Fastest Delivery</Text>
            </View>
            <View style={styles.footerItemContainer}>
              <CustomIconOriginal size={32} style={styles.footerIcon} />
              <Text style={styles.footerText}>100% Original</Text>
            </View>
            <View style={styles.footerItemContainer}>
              <IcOutlineAssignmentReturn size={32} style={styles.footerIcon} />
              <Text style={styles.footerText}>Easy Returns</Text>
            </View>
            <View style={styles.footerItemContainer}>
              <RiSecurePaymentFill size={32} style={styles.footerIcon} />
              <Text style={styles.footerText}>Secure Payment</Text>
            </View>
          </View>
        </View>
      </ScrollView>
      <Snackbar
        visible={snackbarVisible}
        duration={2000}
        >
        Added to Bag !
      </Snackbar>
    </>
  )
}
Example #11
Source File: avatar.playground.jsx    From playground with MIT License 4 votes vote down vote up
AvatarPlay = () => {
  const params = useView({
    componentName: "Avatar",
    props: {
      activeOpacity: {
        value: 0.2,
        type: PropTypes.Number,
      },
      avatarStyle: {
        value: `{}`,
        type: PropTypes.Object,
      },
      containerStyle: {
        value: `{ backgroundColor: '#BDBDBD' }`,
        type: PropTypes.Object,
      },
      icon: {
        value: `{}`,
        type: PropTypes.Object,
      },
      iconStyle: {
        value: `{}`,
        type: PropTypes.Object,
      },
      imageProps: {
        value: `{}`,
        type: PropTypes.Object,
      },
      onLongPress: {
        value: `()=>alert('onLongPress')`,
        type: PropTypes.Function,
      },
      onPress: {
        value: `()=>alert('onPress')`,
        type: PropTypes.Function,
      },

      overlayContainerStyle: {
        value: `{}`,
        type: PropTypes.Object,
      },
      placeholderStyle: {
        value: `{}`,
        type: PropTypes.Object,
      },
      rounded: {
        value: true,
        type: PropTypes.Boolean,
        description: "Indicates that the button is disabled",
      },
      size: {
        value: "large",
        options: {
          small: "small",
          medium: "medium",
          large: "large",
          xlarge: "xlarge",
        },
        type: PropTypes.Enum,
        description: "Defines the size of the Avatar",
      },

      source: {
        value: `{uri:""}`,
        type: PropTypes.Object,
      },
      title: {
        value: "P",
        type: PropTypes.String,
        description: "Visible label.",
      },
      titleStyle: {
        value: `{}`,
        type: PropTypes.Object,
      },
      renderPlaceholderContent: {
        type: PropTypes.ReactNode,
      },
      Component: {
        type: PropTypes.ReactNode,
      },
      ImageComponent: {
        type: PropTypes.ReactNode,
      },
      // titleProps: {
      //   value: `{}`,
      //   type: PropTypes.Object,
      // },
      // titleStyle: {
      //   value: `{marginHorizontal: 5}`,
      //   type: PropTypes.Object,
      // },
      // type: {
      //   value: "solid",
      //   defaultValue: "solid",
      //   options: { solid: "Solid", clear: "Clear", outline: "Outline" },
      //   type: PropTypes.Enum,
      //   description: "Defines the type of the button.",
      // },
    },
    scope: {
      Avatar,
    },
    imports: {
      "react-native-elements": {
        named: ["Avatar"],
      },
    },
  });

  return (
    <React.Fragment>
      <Playground params={params} />
    </React.Fragment>
  );
}
Example #12
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
LeftMenu = ({ navigation }) => {
    const {
        user,
        avatar,
        households,
        householdAvatars,
        signOut,
        setGroup,
    } = useUser()

    const [hasSurveillance, setHasSurveillance] = useState(false)
    let index = households.length

    const getActiveSurveillance = async () => {
        if (user.group_id) {
            const response = await getAppGroup(user.group_id)

            if (response.status === 200) {
                const { group } = response.data
                setGroup(group)

                if (group.group_manager.vigilance_email) {
                    setHasSurveillance(true)
                } else {
                    setHasSurveillance(false)
                }
            }
        } else {
            setHasSurveillance(false)
        }
    }

    useEffect(() => {
        getActiveSurveillance()
    }, [user.group_id])

    return (
        <ScrollViewStyled>
            <AvatarContainer>
                <Avatar
                    containerStyle={[styles.avatar, { zIndex: index-- }]}
                    size={scale(60)}
                    source={handleAvatar(avatar)}
                    title={getInitials(user.user_name)}
                    rounded
                />
                {households.map((household) => (
                    <Avatar
                        key={household.id}
                        containerStyle={[styles.avatars, { zIndex: index-- }]}
                        size={scale(60)}
                        source={handleAvatar(householdAvatars[household.id])}
                        title={getInitials(household.description)}
                        rounded
                    />
                ))}
            </AvatarContainer>

            {user.is_professional === true ? (
                <Button onPress={() => navigation.navigate('Rumor')}>
                    <UserOptionBlue>
                        <Feather
                            name='info'
                            size={scale(26)}
                            color='#ffffff'
                            style={styles.iconStyle}
                        />
                        <TextOption>
                            {translate('drawer.reportRumor')}
                        </TextOption>
                    </UserOptionBlue>
                </Button>
            ) : null}
            <Button onPress={() => navigation.navigate('Perfis')}>
                <UserOptionBlue>
                    <Feather
                        name='settings'
                        size={scale(26)}
                        color='#ffffff'
                        style={styles.iconStyle}
                    />
                    <TextOption>{translate('drawer.toEdit')}</TextOption>
                </UserOptionBlue>
            </Button>
            <Button onPress={() => signOut()}>
                <UserOptionBlue>
                    <Feather
                        name='log-out'
                        size={scale(26)}
                        color='#ffffff'
                        style={styles.iconStyle}
                    />
                    <TextOption>{translate('drawer.logOut')}</TextOption>
                </UserOptionBlue>
            </Button>

            <Aplicativo>{translate('drawer.app')}</Aplicativo>

            {hasSurveillance ? (
                <Button onPress={() => navigation.navigate('Vigilancia')}>
                    <UserOptionGreen>
                        <Feather
                            name='shield'
                            size={scale(26)}
                            color='#ffffff'
                            style={styles.iconStyle}
                        />
                        <TextOption>
                            {translate('drawer.toSurveillance')}
                        </TextOption>
                    </UserOptionGreen>
                </Button>
            ) : null}
            <Button onPress={() => navigation.navigate('Vacinacao')}>
                <UserOptionGreen>
                    <FontAwesome5
                        name='syringe'
                        size={scale(26)}
                        color='#ffffff'
                        style={styles.iconStyle}
                    />
                    <TextOption>{translate('drawer.toVaccination')}</TextOption>
                </UserOptionGreen>
            </Button>
            <Button onPress={() => navigation.navigate('Ajuda')}>
                <UserOptionGreen>
                    <Feather
                        name='help-circle'
                        size={scale(26)}
                        color='#ffffff'
                        style={styles.iconStyle}
                    />
                    <TextOption>{translate('drawer.toHelp')}</TextOption>
                </UserOptionGreen>
            </Button>
            <Button
                onPress={() => {
                    Share.open(shareOptions)
                        .then((res) => {
                            console.log(res)
                        })
                        .catch((err) => {
                            console.log(err)
                        })
                }}
            >
                <UserOptionGreen>
                    <Feather
                        name='share-2'
                        size={scale(26)}
                        color='#ffffff'
                        style={styles.iconStyle}
                    />
                    <TextOption>{translate('drawer.share')}</TextOption>
                </UserOptionGreen>
            </Button>

            <SocialContainer>
                <Button
                    onPress={() =>
                        Linking.openURL('https://twitter.com/proepi_')
                    }
                >
                    <RedeSocial>
                        <SimpleLineIcons
                            name='social-twitter'
                            size={scale(28)}
                            color='#ffffff'
                            style={styles.iconRedeSocial}
                        />
                    </RedeSocial>
                </Button>
                <Button
                    onPress={() =>
                        Linking.openURL('https://www.instagram.com/redeproepi')
                    }
                >
                    <RedeSocial>
                        <SimpleLineIcons
                            name='social-instagram'
                            size={scale(28)}
                            color='#ffffff'
                            style={styles.iconRedeSocial}
                        />
                    </RedeSocial>
                </Button>
            </SocialContainer>
        </ScrollViewStyled>
    )
}
Example #13
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
Vacinacao = () => {
    const { token, user } = useUser()

    const [isLoading, setIsLoading] = useState(true)

    const [vaccines, setVaccines] = useState([])
    const [vaccineInfo, setVaccineInfo] = useState({})
    const [vaccineSelected, setVaccineSelected] = useState({})

    const [doses, setDoses] = useState([])
    const [doseSelected, setDoseSelected] = useState({})
    const [newDoseDate, setNewDoseDate] = useState('')

    const [modalVaccine, setModalVaccine] = useState(false)
    const [modalDose, setModalDose] = useState(false)
    const [loadingAlert, setLoadingAlert] = useState(false)

    const getUserDoses = async () => {
        const response = await getDoses(token)

        if (response.status === 200) {
            const { doses } = response.data
            setDoses(doses)
        }
    }

    const getAppVaccines = async () => {
        const response = await getVaccines(token)

        if (response.status === 200) {
            const { vaccines } = response.data
            setVaccines(vaccines)
            setIsLoading(false)
        }
    }

    const fetchData = async () => {
        await getUserDoses()
        await getAppVaccines()
    }

    const vaccineSelector = () => {
        return (
            <FormInline>
                {vaccines.map((vaccine) => (
                    <FormInlineCheck key={vaccine.id}>
                        <CheckBoxStyled
                            title={vaccine.name}
                            checked={vaccine.id === vaccineSelected.id}
                            onPress={() => setVaccineSelected(vaccine)}
                        />
                        <CheckLabel
                            onPress={() => {
                                setVaccineInfo(vaccine)
                                setModalDose(false)
                                setModalVaccine(true)
                            }}
                        >
                            <Feather
                                name='help-circle'
                                size={scale(25)}
                                color='#348EAC'
                            />
                        </CheckLabel>
                    </FormInlineCheck>
                ))}
            </FormInline>
        )
    }

    const resetModalDose = () => {
        setModalDose(false)
        setDoseSelected({})
        setNewDoseDate('')
        setVaccineSelected({})
    }

    const editDose = async () => {
        const doseDate = moment(newDoseDate, 'DD-MM-YYYY').toISOString()

        const doseInfo = checkDose(vaccineSelected, doses, doseDate, doseSelected)
        const newDose = {
            id: doseSelected.id,
            date: doseDate,
            dose: doseInfo.position,
            user_id: user.id,
            vaccine_id: vaccineSelected.id,
        }

        if (!validVaccination(vaccineSelected, doseDate, doseInfo)) return
        setLoadingAlert(true)

        const response = await updateDose(newDose, token)

        if (response.status === 200) {
            const newDoses = doses.filter((d) => d.id !== doseSelected.id)
            newDoses.push(response.data.dose)
            setDoses(newDoses)

            resetModalDose()
            setLoadingAlert(false)
        } else {
            Alert.alert(translate('register.geralError'))
            setLoadingAlert(false)
        }
    }

    const createDose = async () => {
        const doseDate = moment(newDoseDate, 'DD-MM-YYYY').toISOString()

        const doseInfo = checkDose(vaccineSelected, doses, doseDate, {})
        const newDose = {
            date: doseDate,
            dose: doseInfo.position,
            user_id: user.id,
            vaccine_id: vaccineSelected.id,
        }

        if (!validVaccination(vaccineSelected, doseDate, doseInfo)) return
        setLoadingAlert(true)

        const response = await sendDose(newDose, token)

        if (response.status === 200) {
            const newDoses = [...doses, response.data.dose]
            setDoses(newDoses)

            resetModalDose()
            setLoadingAlert(false)
        } else {
            Alert.alert(translate('register.geralError'))
            setLoadingAlert(false)
        }
    }

    const removeDose = async () => {
        const dose = {
            id: doseSelected.id,
        }

        setLoadingAlert(true)

        const response = await deleteDose(dose, token)

        if (response.status === 204) {
            const newDoses = doses.filter((d) => d.id !== dose.id)
            setDoses(newDoses)

            resetModalDose()
            setLoadingAlert(false)
        } else {
            Alert.alert(translate('register.geralError'))
            setLoadingAlert(false)
        }
    }

    const handleSave = () => {
        if (doseSelected.id) {
            editDose()
        } else {
            createDose()
        }
    }

    const handleDelete = () => {
        Alert.alert(
            translate('vaccination.confirmDeleteDose'),
            translate('vaccination.confirmDeleteDose2'),
            [
                {
                    text: 'Cancel',
                    onPress: () => console.log('Cancel Pressed'),
                    style: 'cancel',
                },
                { text: 'OK', onPress: () => removeDose() },
            ],
            { cancelable: false }
        )
    }

    useEffect(() => {
        fetchData()
    }, [])

    if (isLoading) {
        return <ScreenLoader />
    }

    return (
        <Container>
            <Modal // Vaccine
                animationType='fade'
                transparent
                visible={modalVaccine}
                onRequestClose={() => {
                    setModalVaccine(!modalVaccine)
                    setModalDose(true)
                }}
            >
                <ModalContainer>
                    <ModalBox>
                        <ModalTitle>
                            {translate('vaccination.titleModal')}
                        </ModalTitle>

                        <ModalText>
                            {translate('vaccination.nameVaccine')}
                            {vaccineInfo.name}
                            {'\n'}
                            {translate('vaccination.laboratoryVaccine')}
                            {vaccineInfo.laboratory}
                            {'\n'}
                            {translate('vaccination.countryVaccine')}
                            {vaccineInfo.country_origin}
                            {'\n'}
                            {translate('vaccination.dosesVaccine')}
                            {vaccineInfo.doses}
                            {'\n'}
                            {translate('vaccination.minIntervalVaccine')}
                            {vaccineInfo.min_dose_interval}
                            {translate('vaccination.intervalVaccinePeriod')}
                        </ModalText>

                        <ButtonClose
                            onPress={() => {
                                setModalVaccine(false)
                                setModalDose(true)
                            }}
                        >
                            <ModalClose>
                                <Feather
                                    name='x'
                                    size={scale(24)}
                                    color='#ffffff'
                                />
                            </ModalClose>
                        </ButtonClose>
                    </ModalBox>
                </ModalContainer>
            </Modal>

            <ScrollViewStyled>
                <CardWrapper>
                    <CardTitle>
                        {doses.length > 0
                            ? translate('vaccination.doses')
                            : translate('vaccination.noDoses')}
                    </CardTitle>
                </CardWrapper>

                {doses.map((dose) => (
                    <CardWhite key={dose.id}>
                        <AvatarWrapper>
                            <Avatar
                                size={scale(58)}
                                source={null}
                                title={getInitials(`Dose ${dose.dose}`)}
                                rounded
                            />
                        </AvatarWrapper>
                        <InfoContainer>
                            <InfoWrapper>
                                <CardNameWhite>
                                    {dose.vaccine.name}
                                </CardNameWhite>
                                <CardDetailsWhite>
                                    {moment(new Date(dose.date)).format(
                                        'DD/MM/YYYY'
                                    )}
                                </CardDetailsWhite>
                            </InfoWrapper>
                            <ButtonsWrapper>
                                <Button
                                    onPress={() => {
                                        setDoseSelected(dose)
                                        setNewDoseDate(
                                            moment(new Date(dose.date)).format(
                                                'DD-MM-YYYY'
                                            )
                                        )
                                        setVaccineSelected(dose.vaccine)
                                        setModalDose(!modalDose)
                                    }}
                                >
                                    <Feather
                                        name='edit'
                                        size={scale(25)}
                                        color='#348EAC'
                                    />
                                </Button>
                            </ButtonsWrapper>
                        </InfoContainer>
                    </CardWhite>
                ))}

                <Modal // Dose
                    animationType='fade'
                    transparent
                    visible={modalDose}
                    onRequestClose={() => {
                        resetModalDose()
                    }}
                >
                    <ModalContainer>
                        <ModalBox>
                            <ModalTitle>
                                {doseSelected.id
                                    ? translate('vaccination.titleEditDose')
                                    : translate('vaccination.titleAddDose')}
                            </ModalTitle>

                            <VaccineScroll>
                                <FormInline>
                                    <DateSelector
                                        placeholder={translate(
                                            'vaccination.dateField'
                                        )}
                                        date={newDoseDate}
                                        format='DD-MM-YYYY'
                                        minDate='01-01-1918'
                                        maxDate={moment()
                                            .local()
                                            .format('DD-MM-YYYY')}
                                        locale='pt-BR'
                                        confirmBtnText={translate(
                                            'birthDetails.confirmButton'
                                        )}
                                        cancelBtnText={translate(
                                            'birthDetails.cancelButton'
                                        )}
                                        onDateChange={(date) =>
                                            setNewDoseDate(date)
                                        }
                                    />
                                </FormInline>

                                {vaccineSelector()}
                            </VaccineScroll>

                            {doseSelected.id ? (
                                <Button onPress={() => handleDelete()}>
                                    <ModalButton>
                                        <ModalButtonText>
                                            {translate('vaccination.delete')}
                                        </ModalButtonText>
                                    </ModalButton>
                                </Button>
                            ) : null}

                            <Button onPress={() => handleSave()}>
                                <ModalButton>
                                    <ModalButtonText>
                                        {translate('vaccination.save')}
                                    </ModalButtonText>
                                </ModalButton>
                            </Button>

                            <ButtonClose onPress={() => resetModalDose()}>
                                <ModalClose>
                                    <Feather
                                        name='x'
                                        size={scale(24)}
                                        color='#ffffff'
                                    />
                                </ModalClose>
                            </ButtonClose>
                        </ModalBox>
                    </ModalContainer>
                </Modal>

                <Button onPress={() => setModalDose(!modalDose)}>
                    <SendContainer>
                        <SendText>{translate('vaccination.add')}</SendText>
                    </SendContainer>
                </Button>
            </ScrollViewStyled>

            <LoadingModal show={loadingAlert} />
        </Container>
    )
}
Example #14
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
Perfis = ({ navigation }) => {
    const {
        token,
        user,
        storeUser,
        avatar,
        households,
        storeHouseholds,
        householdAvatars,
    } = useUser()

    const [isLoading, setIsLoading] = useState(true)

    const getFullUser = async () => {
        const response = await getUser(user.id, token)

        if (response.status === 200) {
            storeHouseholds(response.data.user.households)
            storeUser(response.data.user)

            setIsLoading(false)
        }
    }

    const getUserInfo = () => {
        const bornDate = new Date()
        let birthDate = ''

        if (!user.birthdate) {
            bornDate.setFullYear(bornDate.getFullYear() - 13)
            birthDate = moment(new Date(bornDate)).format('DD-MM-YYYY')
        } else {
            birthDate = moment(new Date(user.birthdate)).format('DD-MM-YYYY')
        }

        return {
            ...user,
            is_household: false,
            name: user.user_name ? user.user_name : '',
            avatar,
            birthdate: birthDate,
            category: {
                key: user.category ? user.category.id : null,
                label: user.category ? user.category.name : null,
            },
        }
    }

    const getHouseholdInfo = (household) => {
        const bornDate = new Date()
        let birthDate = ''

        if (!household.birthdate) {
            bornDate.setFullYear(bornDate.getFullYear() - 13)
            birthDate = moment(new Date(bornDate)).format('DD-MM-YYYY')
        } else {
            birthDate = moment(new Date(household.birthdate)).format(
                'DD-MM-YYYY'
            )
        }

        return {
            ...household,
            is_household: true,
            name: household.description ? household.description : '',
            avatar: householdAvatars[household.id],
            birthdate: birthDate,
            category: {
                key: household.category ? household.category.id : null,
                label: household.category ? household.category.name : null,
            },
        }
    }

    useEffect(() => {
        getFullUser()
    }, [])

    if (isLoading) {
        return <ScreenLoader />
    }

    return (
        <ScrollViewStyled>
            <CardBlue>
                <AvatarWrapper>
                    <Avatar
                        containerStyle={styles.Avatar}
                        size={scale(58)}
                        source={handleAvatar(avatar)}
                        title={getInitials(user.user_name)}
                        rounded
                    />
                </AvatarWrapper>
                <InfoContainer>
                    <InfoWrapper>
                        <CardNameBlue>{user.user_name}</CardNameBlue>
                        <CardDetailsBlue>
                            {translate('profiles.owner')}
                        </CardDetailsBlue>
                    </InfoWrapper>
                    <ButtonsWrapper>
                        <Button
                            onPress={() => {
                                navigation.navigate('EditarPerfil', {
                                    person: getUserInfo(),
                                })
                            }}
                        >
                            <Feather
                                name='edit'
                                size={scale(25)}
                                color='#ffffff'
                            />
                        </Button>
                    </ButtonsWrapper>
                </InfoContainer>
            </CardBlue>

            {households.length > 0 ? (
                <CardWrapper>
                    <CardTitle>{translate('profiles.households')}</CardTitle>
                </CardWrapper>
            ) : null}

            {households.map((household) => {
                return (
                    <CardWhite key={household.id}>
                        <AvatarWrapper>
                            <Avatar
                                size={scale(58)}
                                source={handleAvatar(
                                    householdAvatars[household.id]
                                )}
                                title={getInitials(household.description)}
                                rounded
                            />
                        </AvatarWrapper>
                        <InfoContainer>
                            <InfoWrapper>
                                <CardNameWhite>
                                    {household.description}
                                </CardNameWhite>
                                <CardDetailsWhite>
                                    {household.kinship}
                                </CardDetailsWhite>
                            </InfoWrapper>
                            <ButtonsWrapper>
                                <Button
                                    onPress={() => {
                                        navigation.navigate('EditarPerfil', {
                                            person: getHouseholdInfo(household),
                                        })
                                    }}
                                >
                                    <Feather
                                        name='edit'
                                        size={scale(25)}
                                        color='#348EAC'
                                    />
                                </Button>
                            </ButtonsWrapper>
                        </InfoContainer>
                    </CardWhite>
                )
            })}
        </ScrollViewStyled>
    )
}
Example #15
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
Home = ({ navigation }) => {
    const {
        isLoading,
        isOffline,
        signOut,
        token,
        user,
        storeUser,
        avatar,
        location,
        getCurrentLocation,
        group,
        households,
        storeHouseholds,
        householdAvatars,
        surveys,
        storeSurveys,
        getAppTip,
        hideAppTip,
        lastForm,
        getCacheData,
        storeCacheData,
        updateUserScore,
        loadSecondaryData,
        selectUser,
        getCurrentUserInfo,
    } = useUser()

    const [showTermsConsent, setShowTermsConsent] = useState(false)
    const [hasForm, setHasForm] = useState(false)
    const [hasBadReports, setHasBadReports] = useState(false)
    const [modalVisible, setModalVisible] = useState(false)
    const [showAlert, setShowAlert] = useState(false)
    const [showProgressBar, setShowProgressBar] = useState(false)
    const [alertTitle, setAlertTitle] = useState(null)
    const [alertMessage, setAlertMessage] = useState(null)
    const [inviteSurveillance, setInviteSurveillance] = useState(false)

    const person = getCurrentUserInfo()

    useFocusEffect(
        useCallback(() => {
            getUserAlerts()
        }, [surveys, lastForm])
    )

    useEffect(() => {
        if (!isLoading) {
            fetchData()
        }
    }, [isLoading])

    useEffect(() => {
        showOfflineAlert(isOffline)
    }, [isOffline])

    useEffect(() => {
        if (
            !user.is_vigilance &&
            group.group_manager &&
            group.group_manager.vigilance_email
        ) {
            setInviteSurveillance(true)
        }
    }, [group])

    const fetchData = async () => {
        await loadSecondaryData()

        verifyUserTermsConsent()
        getCurrentLocation()
        getCacheSurveys()
    }

    const verifyUserTermsConsent = () => {
        const currentPolicyTerms = terms.version
        const userPolicyTerms = user.policy_version

        if (userPolicyTerms < currentPolicyTerms) {
            setShowTermsConsent(true)
        }
    }

    const updateUserTermsConsent = async () => {
        setShowTermsConsent(false)

        const policy = {
            policy_version: terms.version,
        }

        const response = await updateUser({ user: policy }, user.id, token)

        if (response.status === 200) {
            console.warn(response.status)
            storeUser(response.data.user)
        }
    }

    const getCacheSurveys = async () => {
        const surveysCache = await getCacheData('surveysData', false)

        if (surveysCache) {
            storeSurveys(surveysCache)
        }
    }

    const getUserAlerts = () => {
        const todayDate = new Date()
        const lastWeek = new Date()

        lastWeek.setDate(todayDate.getDate() - 7)
        lastWeek.setHours(0, 0, 0, 0)

        const lastFormDate = new Date(lastForm)

        if (!lastForm || lastFormDate.getTime() < lastWeek.getTime()) {
            setHasForm(true)
        } else {
            setHasForm(false)
        }

        const userLastSurveys = surveys.filter(
            (survey) =>
                survey &&
                new Date(survey.created_at).getTime() >= lastWeek.getTime()
        )

        let badReports = 0

        if (userLastSurveys.length > 0) {
            userLastSurveys.forEach((survey) => {
                if (person.is_household) {
                    if (
                        survey.symptom.length > 0 &&
                        survey.household &&
                        survey.household.id === person.id
                    ) {
                        badReports += 1
                    }
                } else if (survey.symptom.length > 0 && !survey.household) {
                    badReports += 1
                }
            })
        }

        setHasBadReports(badReports > 2)
    }

    const getHouseholds = async () => {
        const response = await getUserHouseholds(user.id, token)

        if (response.status === 200) {
            storeHouseholds(response.data.households)
        }
    }

    const showTermsPolicy = () => {
        Alert.alert(
            terms.title,
            terms.text,
            [
                {
                    text: terms.disagree,
                    onPress: () => signOut(),
                    style: 'cancel',
                },
                {
                    text: terms.agree,
                    onPress: () => updateUserTermsConsent(),
                },
            ],
            { cancelable: false }
        )
    }

    const showOfflineAlert = (show) => {
        if (show) {
            setAlertTitle(
                <Text>
                    {translate('home.offlineTitle')} {Emojis.cloud}
                </Text>
            )
            setAlertMessage(
                `${translate('home.offlineMessage')}\n${translate(
                    'home.offlineMessage2'
                )}`
            )
            setShowAlert(true)
        } else {
            setShowAlert(false)
        }
    }

    const showLoadingAlert = () => {
        setAlertMessage(null)
        setShowAlert(true)
        setShowProgressBar(true)
    }

    const showConfirmation = (status, body) => {
        const message = getSurveyConfirmation(status, body)

        setAlertTitle(
            <Text>
                {message.alertTitle} {message.emojiTitle}
            </Text>
        )
        setAlertMessage(
            <Text>
                {message.alertMessage} {message.emojiMessage}
            </Text>
        )

        setShowProgressBar(false)
        console.log(message.alertMessage)
    }

    const sendSurvey = async () => {
        // Send Survey GOOD CHOICE
        showLoadingAlert()

        let local = {}
        if (location.error !== 0) {
            local = await getCurrentLocation()
        } else {
            local = location
        }

        const householdID = person.is_household ? person.id : null
        const survey = {
            household_id: householdID,
            latitude: local.latitude,
            longitude: local.longitude,
            symptom: [],
            created_at: moment().local().toISOString(),
        }

        const response = await createSurvey({ survey }, user.id, token)
        showConfirmation(response.status, response.data)

        updateUserScore()
        if (response.status === 201) {
            if (inviteSurveillance) {
                showSurveillanceInvite(
                    person.name,
                    { status: response.status, body: response.data },
                    showConfirmation,
                    navigation
                )
            }

            await storeCacheData('localPin', survey)

            const newSurveys = surveys.slice()
            newSurveys.push(response.data.survey)
            storeSurveys(newSurveys)
        }
    }

    if (isLoading) {
        return <ScreenLoader />
    }

    return (
        <>
            <SafeAreaView style={{ flex: 0, backgroundColor: '#348EAC' }} />
            <StatusBar backgroundColor='#348EAC' barStyle='light-content' />
            <Container>
                <ScrollViewStyled>
                    <Background>
                        <UserView>
                            <MenuBars onPress={() => navigation.openDrawer()}>
                                <SimpleLineIcons
                                    name='menu'
                                    size={26}
                                    color='#ffffff'
                                />
                            </MenuBars>
                            <NamesContainer>
                                <TextName>
                                    {translate('home.hello') +
                                        getNameParts(person.name)}
                                </TextName>
                                <AppName>
                                    {translate('home.nowAGuardian')}
                                </AppName>
                            </NamesContainer>
                            <Avatar
                                containerStyle={styles.avatar}
                                size={scale(58)}
                                source={handleAvatar(person.avatar)}
                                title={getInitials(person.name)}
                                editButton={{
                                    name: null,
                                    type: 'feather',
                                    style: styles.avatarDot,
                                }}
                                showEditButton
                                activeOpacity={0.5}
                                rounded
                                onPress={() => {
                                    getHouseholds()
                                    setModalVisible(true)
                                }}
                            />
                        </UserView>
                    </Background>

                    <StatusContainer>
                        <TextStyle>
                            {translate('home.userHowYouFelling')}
                        </TextStyle>
                        <StatusBemMal>
                            <Bem
                                disabled={isOffline}
                                onPress={() => sendSurvey()}
                            >
                                <StatusText>
                                    {translate('report.goodChoice')}
                                </StatusText>
                            </Bem>
                            <Mal
                                disabled={isOffline}
                                onPress={() => navigation.navigate('BadReport')}
                            >
                                <StatusText>
                                    {translate('report.badChoice')}
                                </StatusText>
                            </Mal>
                        </StatusBemMal>
                    </StatusContainer>

                    <Tips>{translate('home.alerts')}</Tips>

                    {user.doses < 3 && getAppTip('vaccination') ? (
                        <TipButton
                            onPress={() => navigation.navigate('Vacinacao')}
                        >
                            <UserTip
                                icon={
                                    <FontAwesome5
                                        name='syringe'
                                        size={scale(46)}
                                        color='#ffffff'
                                    />
                                }
                                title={translate('home.vaccination')}
                                message={translate('home.vaccinationData')}
                                onClose={() => hideAppTip('vaccination')}
                                isCloseable
                            />
                        </TipButton>
                    ) : null}

                    {group.form_id && hasForm ? (
                        <TipButton
                            onPress={() => navigation.navigate('BioSeguranca')}
                        >
                            <UserTip
                                icon={
                                    <SimpleLineIcons
                                        name='bubble'
                                        size={scale(46)}
                                        color='#ffffff'
                                    />
                                }
                                title={translate('home.bioSecurity')}
                                message={translate('home.bioSecurityQuestions')}
                                alert
                            />
                        </TipButton>
                    ) : null}

                    <TipButton>
                        <UserTip
                            icon={
                                <SimpleLineIcons
                                    name={
                                        hasBadReports ? 'exclamation' : 'check'
                                    }
                                    size={scale(46)}
                                    color='#ffffff'
                                />
                            }
                            title={translate('home.statusLast7Days')}
                            message={
                                hasBadReports
                                    ? translate('home.statusLast7DaysBad')
                                    : translate('home.statusLast7DaysGood')
                            }
                            alert={hasBadReports}
                        />
                    </TipButton>
                </ScrollViewStyled>

                <Modal
                    animationType='fade'
                    transparent
                    visible={modalVisible}
                    onRequestClose={() => {
                        setModalVisible(!modalVisible)
                    }}
                >
                    <Users>
                        <UserSelector>
                            <UserScroll>
                                <UserWrapper>
                                    <Button
                                        onPress={async () => {
                                            setModalVisible(!modalVisible)
                                            await selectUser(user)
                                            getUserAlerts()
                                        }}
                                    >
                                        <Avatar
                                            size={scale(60)}
                                            source={handleAvatar(avatar)}
                                            title={getInitials(user.user_name)}
                                            rounded
                                        />
                                        <UserName>
                                            {getNameParts(user.user_name, true)}
                                        </UserName>
                                    </Button>
                                </UserWrapper>
                                {households.map((household) => (
                                    <UserWrapper key={household.id}>
                                        <Button
                                            onPress={async () => {
                                                setModalVisible(!modalVisible)
                                                await selectUser(household)
                                                getUserAlerts()
                                            }}
                                        >
                                            <Avatar
                                                size={scale(60)}
                                                source={handleAvatar(
                                                    householdAvatars[
                                                        household.id
                                                    ]
                                                )}
                                                title={getInitials(
                                                    household.description
                                                )}
                                                rounded
                                            />
                                            <UserName>
                                                {getNameParts(
                                                    household.description,
                                                    true
                                                )}
                                            </UserName>
                                        </Button>
                                    </UserWrapper>
                                ))}
                                <UserWrapper>
                                    <Button
                                        onPress={() => {
                                            setModalVisible(!modalVisible)
                                            navigation.navigate('NovoPerfil')
                                        }}
                                    >
                                        <Feather
                                            name='plus'
                                            size={scale(60)}
                                            color='#c4c4c4'
                                        />
                                        <UserName>
                                            {translate('home.addProfile')}
                                        </UserName>
                                    </Button>
                                </UserWrapper>
                            </UserScroll>
                        </UserSelector>
                    </Users>
                </Modal>

                <CoolAlert
                    show={showTermsConsent}
                    title={translate('useTerms.consentTitle')}
                    message={translate('useTerms.consentMessage')}
                    closeOnTouchOutside={false}
                    closeOnHardwareBackPress={false}
                    showConfirmButton
                    confirmText={translate('useTerms.seeTerms')}
                    onConfirmPressed={() => showTermsPolicy()}
                />
                <CoolAlert
                    show={showAlert}
                    showProgress={showProgressBar}
                    title={
                        showProgressBar
                            ? translate('badReport.messages.sending')
                            : alertTitle
                    }
                    message={alertMessage}
                    closeOnTouchOutside={!showProgressBar}
                    closeOnHardwareBackPress={false}
                    showConfirmButton={!showProgressBar}
                    confirmText={translate('badReport.messages.confirmText')}
                    onConfirmPressed={() => setShowAlert(false)}
                    onDismiss={() => setShowAlert(false)}
                />
            </Container>
        </>
    )
}
Example #16
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
EditarPerfil = ({ navigation, route }) => {
    const {
        token,
        user,
        storeUser,
        updateUserAvatar,
        households,
        storeHouseholds,
        updateHouseholdAvatars,
    } = useUser()
    const { person } = route.params

    const isHousehold = person.is_household
    const { id } = person
    const [avatar, setAvatar] = useState(person.avatar)
    const [name, setName] = useState(person.name)
    const [email, setEmail] = useState(person.email)
    const [gender, setGender] = useState(person.gender)
    const [country, setCountry] = useState(person.country)
    const [state, setState] = useState(person.state)
    const [city, setCity] = useState(person.city)
    const [race, setRace] = useState(person.race)
    const [birth, setBirth] = useState(person.birthdate)
    const [kinship, setKinship] = useState(person.kinship)
    const [groupId, setGroupId] = useState(person.group_id)
    const [idCode, setIdCode] = useState(person.identification_code)
    const [riskGroup, setRiskGroup] = useState(person.risk_group)
    const [isVigilance, setIsVigilance] = useState(person.is_vigilance)
    const [category, setCategory] = useState(person.category)
    const [allCategories, setAllCategories] = useState(null)

    const [modalRiskGroup, setModalRiskGroup] = useState(false)
    const [institutionError, setInstituitionError] = useState(null)
    const [loadingAlert, setLoadingAlert] = useState(false)

    const getAppCategories = async () => {
        const response = await getCategories()

        if (response.status === 200) {
            const { categories } = response.data

            const auxCategories = categories.map(({ id, name }) => {
                return {
                    key: id,
                    label: name,
                }
            })
            setAllCategories(auxCategories)
        }
    }

    useEffect(() => {
        getAppCategories()
    }, [])

    useEffect(() => {
        checkIfIsVigilance(groupId)
    }, [groupId])

    const removeHousehold = async () => {
        const household = {
            id,
        }

        setLoadingAlert(true)

        const response = await deleteHousehold(household, user.id, token)

        if (response.status === 204) {
            const newHouseholds = households.filter((h) => h.id !== id)
            storeHouseholds(newHouseholds)

            setLoadingAlert(false)
            navigation.goBack()
        } else {
            console.warn(response.status)
            setLoadingAlert(false)
            Alert.alert(translate('register.geralError'))
        }
    }

    const editHousehold = async () => {
        const birthDate = moment(birth, 'DD-MM-YYYY').toISOString()

        const newHousehold = {
            id,
            description: name,
            birthdate: birthDate,
            country,
            gender,
            race,
            kinship,
            group_id: groupId,
            identification_code: idCode,
            risk_group: riskGroup,
            category_id: category.key,
            category_required: !!allCategories,
        }

        if (!validPerson(newHousehold, institutionError)) return
        setLoadingAlert(true)

        const response = await updateHousehold(newHousehold, user.id, token)

        if (response.status === 200) {
            const { household } = response.data
            const newHouseholds = households.filter((h) => h.id !== id)

            newHouseholds.push({
                ...newHousehold,
                ...household,
            })
            storeHouseholds(newHouseholds)

            setLoadingAlert(false)
            navigation.goBack()
        } else {
            console.warn(response.status)
            setLoadingAlert(false)
            Alert.alert(translate('register.geralError'))
        }
    }

    const checkIfIsVigilance = async (groupId) => {
        if (groupId) {
            const response = await getAppGroup(groupId)
            if (response.status === 200) {
                const { group } = response.data

                if (
                    group.group_manager &&
                    !group.group_manager.vigilance_email
                ) {
                    setIsVigilance(false)
                }
            }
        } else {
            setIsVigilance(false)
        }
    }

    const editUser = async () => {
        const birthDate = moment(birth, 'DD-MM-YYYY').toISOString()
        const isBrazil = country === 'Brazil'

        const newUser = {
            user_name: name,
            birthdate: birthDate,
            gender,
            race,
            country,
            state: isBrazil ? state : null,
            city: isBrazil ? city : null,
            group_id: groupId,
            identification_code: idCode,
            risk_group: riskGroup,
            is_vigilance: isVigilance,
            category_id: category.key,
            category_required: !!allCategories,
        }

        if (!validPerson(newUser, institutionError)) return
        setLoadingAlert(true)

        const response = await updateUser({ user: newUser }, user.id, token)

        if (response.status === 200) {
            const { user } = response.data

            storeUser({
                ...newUser,
                ...user,
            })

            setLoadingAlert(false)
            navigation.goBack()
        } else {
            console.warn(response.status)
            setLoadingAlert(false)
            Alert.alert(translate('register.geralError'))
        }
    }

    const changeAvatar = () => {
        ImagePicker.showImagePicker(imageOptions, (response) => {
            if (response.didCancel) {
                console.log('User cancelled image picker')
            } else if (response.error) {
                console.log('ImagePicker Error: ', response.error)
            } else if (response.customButton === 'remove') {
                if (isHousehold) {
                    updateHouseholdAvatars(id, undefined)
                } else {
                    updateUserAvatar(undefined)
                }

                setAvatar(null)
                Alert.alert(translate('register.removedPhoto'))
            } else {
                let source = response.uri
                if (Platform.OS === 'android') {
                    source = `content://com.guardioesapp.provider/root${response.path}`
                }

                if (isHousehold) {
                    updateHouseholdAvatars(id, source)
                } else {
                    updateUserAvatar(source)
                }

                setAvatar(source)
                Alert.alert(translate('register.updatedPhoto'))
            }
        })
    }

    const handleEdit = () => {
        if (isHousehold) {
            editHousehold()
        } else {
            editUser()
        }
    }

    const handleDelete = () => {
        Alert.alert(
            translate('register.confirmDeleteUser'),
            translate('register.confirmDeleteUser2'),
            [
                {
                    text: 'Cancel',
                    onPress: () => console.log('Cancel Pressed'),
                    style: 'cancel',
                },
                { text: 'OK', onPress: () => removeHousehold() },
            ],
            { cancelable: false }
        )
    }

    const setUserInstitutionCallback = (idCode, groupId) => {
        setIdCode(idCode)
        setGroupId(groupId)
    }

    const setInstituitionComponentError = (error) => {
        setInstituitionError(error)
    }

    return (
        <Container>
            <Modal // Modal View for Risk Group Message
                animationType='fade'
                transparent
                visible={modalRiskGroup}
                onRequestClose={() => {
                    setModalRiskGroup(!modalRiskGroup)
                }}
            >
                <ModalContainer>
                    <ModalBox>
                        <ModalTitle>
                            {translate('register.riskGroupTitle')}
                        </ModalTitle>

                        <ModalText>
                            {translate('register.riskGroupMessage')}
                        </ModalText>

                        <ButtonClose onPress={() => setModalRiskGroup(false)}>
                            <ModalClose>
                                <Feather
                                    name='x'
                                    size={scale(24)}
                                    color='#ffffff'
                                />
                            </ModalClose>
                        </ButtonClose>
                    </ModalBox>
                </ModalContainer>
            </Modal>
            <KeyboardScrollView>
                <FormInline>
                    <Avatar
                        size={scale(110)}
                        source={handleAvatar(avatar)}
                        title={getInitials(name)}
                        activeOpacity={0.5}
                        showEditButton
                        rounded
                        editButton={{
                            name: 'camera',
                            type: 'feather',
                            color: '#ffffff',
                            underlayColor: '#000000',
                        }}
                        onEditPress={() => changeAvatar()}
                    />
                    {isHousehold && (
                        <Delete onPress={() => handleDelete()}>
                            <Feather
                                name='trash-2'
                                size={scale(25)}
                                color='#ffffff'
                            />
                        </Delete>
                    )}
                </FormInline>

                {!isHousehold ? (
                    <FormInline>
                        <FormLabel>{translate('register.email')}</FormLabel>
                        <ReadOnlyInput>{email}</ReadOnlyInput>
                    </FormInline>
                ) : null}

                <FormInline>
                    <FormLabel>{translate('register.name')}</FormLabel>
                    <NormalInput
                        value={name}
                        onChangeText={(text) => setName(text)}
                    />
                </FormInline>

                <FormGroup>
                    <FormGroupChild>
                        <FormLabel>{translate('register.gender')}</FormLabel>
                        <Selector
                            data={genderChoices}
                            initValue={gender}
                            cancelText={translate('selector.cancelButton')}
                            onChange={(option) => setGender(option.key)}
                        />
                    </FormGroupChild>

                    <FormGroupChild>
                        <FormLabel>{translate('register.race')}</FormLabel>
                        <Selector
                            data={raceChoices}
                            initValue={race}
                            cancelText={translate('selector.cancelButton')}
                            onChange={(option) => setRace(option.key)}
                        />
                    </FormGroupChild>
                </FormGroup>

                <FormGroup>
                    <FormGroupChild>
                        <FormLabel>{translate('register.birth')}</FormLabel>
                        <DateSelector
                            placeholder={translate('birthDetails.format')}
                            date={birth}
                            format='DD-MM-YYYY'
                            minDate='01-01-1918'
                            maxDate={moment().local().format('DD-MM-YYYY')}
                            locale='pt-BR'
                            confirmBtnText={translate(
                                'birthDetails.confirmButton'
                            )}
                            cancelBtnText={translate(
                                'birthDetails.cancelButton'
                            )}
                            onDateChange={(date) => setBirth(date)}
                        />
                    </FormGroupChild>

                    <FormGroupChild>
                        <FormLabel>{translate('register.country')}</FormLabel>
                        <Autocomplete
                            data={countryChoices}
                            value={country}
                            onChange={(option) => setCountry(option.key)}
                        />
                    </FormGroupChild>
                </FormGroup>

                {country === 'Brazil' && !isHousehold ? (
                    <FormGroup>
                        <FormGroupChild>
                            <FormLabel>Estado:</FormLabel>
                            <Autocomplete
                                data={stateOptions}
                                value={state}
                                onChange={(option) => setState(option.key)}
                            />
                        </FormGroupChild>

                        <FormGroupChild>
                            <FormLabel>Município:</FormLabel>
                            <Autocomplete
                                data={getCity(state)}
                                value={city}
                                onChange={(option) => setCity(option.key)}
                            />
                        </FormGroupChild>
                    </FormGroup>
                ) : null}

                {isHousehold ? (
                    <FormInline>
                        <FormLabel>Parentesco:</FormLabel>
                        <Selector
                            data={householdChoices}
                            initValue={kinship}
                            cancelText={translate('selector.cancelButton')}
                            onChange={(option) => setKinship(option.key)}
                        />
                    </FormInline>
                ) : null}

                <FormInlineCheck>
                    <CheckBoxStyled
                        title={translate('register.riskGroupLabel')}
                        checked={riskGroup}
                        onPress={() => setRiskGroup(!riskGroup)}
                    />
                    <CheckLabel
                        onPress={() => {
                            setModalRiskGroup(true)
                        }}
                    >
                        <Feather
                            name='help-circle'
                            size={scale(25)}
                            color='#348EAC'
                        />
                    </CheckLabel>
                </FormInlineCheck>

                <InstitutionSelector
                    setUserInstitutionCallback={setUserInstitutionCallback}
                    setAlert={setLoadingAlert}
                    userGroup={groupId}
                    userIdCode={idCode}
                    setErrorCallback={setInstituitionComponentError}
                />

                {allCategories ? (
                    <FormInline>
                        <FormLabel>Categoria:</FormLabel>
                        <Selector
                            data={allCategories}
                            initValue={
                                category.key
                                    ? category.label
                                    : translate('selector.label')
                            }
                            cancelText={translate('selector.cancelButton')}
                            onChange={(option) => setCategory(option)}
                        />
                    </FormInline>
                ) : null}

                <Button onPress={() => handleEdit()}>
                    <SendContainer>
                        <SendText>Salvar</SendText>
                    </SendContainer>
                </Button>
            </KeyboardScrollView>

            <LoadingModal show={loadingAlert} />
        </Container>
    )
}
Example #17
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
Diario = () => {
    const {
        isOffline,
        token,
        user,
        surveys,
        storeSurveys,
        getCacheData,
        getCurrentUserInfo,
    } = useUser()

    const [isLoading, setIsLoading] = useState(true)
    const [personAge, setPersonAge] = useState(13)
    const [allDatesMarked, setAllDatesMarked] = useState([])
    const [datesMarked, setDatesMarked] = useState([])
    const [daysMarked, setDaysMarked] = useState(0)
    const [daysMissing, setDaysMissing] = useState(0)
    const [daysGood, setDaysGood] = useState(0)
    const [daysBad, setDaysBad] = useState(0)
    const [percentGood, setPercentGood] = useState(0)
    const [percentBad, setPercentBad] = useState(0)
    const [percentMissing, setPercentMissing] = useState(100)

    const person = getCurrentUserInfo()

    useFocusEffect(
        useCallback(() => {
            getSurveys()
            getPersonAge()
        }, [isOffline])
    )

    useEffect(() => {
        defineMarkedDates()
    }, [surveys])

    useEffect(() => {
        getUserParticipation()
    }, [daysMarked])

    const getSurveys = async () => {
        if (!isOffline) {
            const response = await getUserSurveys(user.id, token)

            if (response.status === 200) {
                storeSurveys(response.data.surveys)
                setIsLoading(false)
            }
        } else {
            const surveysCache = await getCacheData('surveysData', false)

            if (surveysCache) {
                storeSurveys(surveysCache)
            }
            setIsLoading(false)
        }
    }

    const getPersonAge = () => {
        const todayDate = new Date()
        const birthDate = new Date(person.birthdate)

        birthDate.setHours(0, 0, 0, 0)

        const diff = todayDate.getTime() - birthDate.getTime()
        const personAge = Math.floor(diff / (1000 * 60 * 60 * 24 * 365))

        setPersonAge(personAge)
    }

    const defineMarkedDates = () => {
        const markedDatesGood = []
        const markedDatesBad = []
        const markedDatesAll = []

        surveys.forEach((survey) => {
            if (!person.is_household) {
                if (!survey.household) {
                    if (survey.symptom && survey.symptom.length) {
                        // BadReport
                        markedDatesBad.push(
                            survey.created_at.split('T', 1).toString()
                        )
                        markedDatesAll.push(survey)
                    } else {
                        // GoodReport
                        markedDatesGood.push(
                            survey.created_at.split('T', 1).toString()
                        )
                    }
                }
            } else if (survey.household && survey.household.id === person.id) {
                if (survey.symptom && survey.symptom.length) {
                    // Household BadReport
                    markedDatesBad.push(
                        survey.created_at.split('T', 1).toString()
                    )
                    markedDatesAll.push(survey)
                } else {
                    // Household GoodReport
                    markedDatesGood.push(
                        survey.created_at.split('T', 1).toString()
                    )
                }
            }
        })

        setAllDatesMarked(markedDatesAll)

        const BadReports = markedDatesBad.reduce(
            (c, v) =>
                Object.assign(c, {
                    [v]: { selected: true, selectedColor: '#F18F01' },
                }),
            {}
        )
        const GoodReports = markedDatesGood.reduce(
            (c, v) =>
                Object.assign(c, {
                    [v]: { selected: true, selectedColor: '#5DD39E' },
                }),
            {}
        )

        Object.assign(GoodReports, BadReports)

        const daysMarked = Object.keys(GoodReports).length
        const daysBad = Object.keys(BadReports).length
        const daysGood = daysMarked - daysBad

        setDatesMarked(GoodReports)
        setDaysMarked(daysMarked)
        setDaysGood(daysGood)
        setDaysBad(daysBad)
    }

    const getUserParticipation = () => {
        const todayDate = new Date()
        const createdDate = new Date(person.created_at)

        createdDate.setHours(0, 0, 0, 0)

        const diff = todayDate.getTime() - createdDate.getTime()
        const daysTotal = Math.ceil(diff / (1000 * 60 * 60 * 24))
        const daysMissing = daysTotal - daysMarked

        const percentGood = ((daysGood / daysTotal) * 100).toFixed(0)
        const percentBad = ((daysBad / daysTotal) * 100).toFixed(0)
        const percentMissing = ((daysMissing / daysTotal) * 100).toFixed(0)

        setDaysMissing(daysMissing)
        setPercentGood(percentGood)
        setPercentBad(percentBad)
        setPercentMissing(percentMissing)
    }

    const handleCalendarArrows = (direction) => {
        if (direction === 'left') {
            return (
                <Feather name='chevron-left' size={scale(25)} color='#c4c4c4' />
            )
        }
        return <Feather name='chevron-right' size={scale(25)} color='#c4c4c4' />
    }

    if (isLoading) {
        return <ScreenLoader />
    }

    const chartData = [
        {
            key: 1,
            value: daysGood,
            svg: { fill: '#5DD39E' },
            arc: { cornerRadius: 8 },
        },
        {
            key: 2,
            value: daysBad,
            svg: { fill: '#F18F01' },
            arc: { cornerRadius: 8 },
        },
        {
            key: 3,
            value: daysMissing,
            svg: { fill: '#c4c4c4' },
            arc: { cornerRadius: 8 },
        },
    ]

    return (
        <>
            <SafeAreaView style={{ flex: 0, backgroundColor: '#348EAC' }} />
            <Container>
                <ScrollViewStyled>
                    <UserData>
                        <AvatarContainer>
                            <Avatar
                                containerStyle={{
                                    borderColor: '#ffffff',
                                    borderWidth: 3,
                                }}
                                size={scale(50)}
                                source={handleAvatar(person.avatar)}
                                title={getInitials(person.name)}
                                rounded
                            />
                        </AvatarContainer>
                        <UserInfo>
                            <UserName>
                                {getNameParts(person.name, true)}
                            </UserName>
                            <UserDetails>
                                {personAge === 1
                                    ? personAge + translate('diary.year')
                                    : personAge + translate('diary.years')}
                            </UserDetails>
                        </UserInfo>
                    </UserData>
                    <UserDash>
                        <SliderContainer>
                            <SwiperStyled showPagination disableGesture={false}>
                                <ChartContainer>
                                    <UserChart>
                                        <CalendarStyled
                                            current={moment().format(
                                                'YYYY-MM-DD'
                                            )}
                                            markedDates={datesMarked}
                                            onDayPress={(day) => {
                                                allDatesMarked.map(
                                                    (symptomMarker) => {
                                                        if (
                                                            symptomMarker.bad_since ===
                                                            day.dateString
                                                        ) {
                                                            console.warn(
                                                                symptomMarker.symptom
                                                            )
                                                        }
                                                    }
                                                )
                                            }}
                                            renderArrow={(direction) =>
                                                handleCalendarArrows(direction)
                                            }
                                        />
                                    </UserChart>
                                </ChartContainer>
                                <ChartContainer>
                                    <UserChart>
                                        <ChartTitle>
                                            {translate('diary.statisticsTitle')}
                                        </ChartTitle>
                                        <Chart>
                                            <PieChart
                                                style={{
                                                    height: 170,
                                                    marginBottom: scale(12),
                                                }}
                                                outerRadius='100%'
                                                innerRadius='15%'
                                                data={chartData}
                                            />
                                        </Chart>
                                        <LabelContainer>
                                            <View>
                                                <LabelWrapper>
                                                    <ChartLabelGreen />
                                                    <ChartLabel>
                                                        {percentGood}
                                                        {translate(
                                                            'diary.goodPercent'
                                                        )}
                                                    </ChartLabel>
                                                </LabelWrapper>
                                                <LabelWrapper>
                                                    <ChartLabelOrange />
                                                    <ChartLabel>
                                                        {percentBad}
                                                        {translate(
                                                            'diary.badPercent'
                                                        )}
                                                    </ChartLabel>
                                                </LabelWrapper>
                                                <LabelWrapper>
                                                    <ChartLabelGray />
                                                    <ChartLabel>
                                                        {percentMissing}
                                                        {translate(
                                                            'diary.notInformed'
                                                        )}
                                                    </ChartLabel>
                                                </LabelWrapper>
                                            </View>
                                        </LabelContainer>
                                    </UserChart>
                                </ChartContainer>
                            </SwiperStyled>
                        </SliderContainer>

                        <UserReports>
                            <ReportsTitleWrapper>
                                <ReportsTitle>
                                    {translate('diary.participations')}
                                </ReportsTitle>
                                <ReportsSubtitle>
                                    Total: {daysMarked}
                                </ReportsSubtitle>
                            </ReportsTitleWrapper>

                            <ReportsAll>
                                <ReportsWell>
                                    <HappyIcon
                                        height={scale(45)}
                                        width={scale(45)}
                                        fill='#ffffff'
                                    />
                                    <ReportData>
                                        <ReportDataTitle>
                                            {translate('diary.good')}
                                        </ReportDataTitle>
                                        <ReportDataInfo>
                                            {daysGood === 1
                                                ? daysGood +
                                                  translate('diary.report')
                                                : daysGood +
                                                  translate('diary.reports')}
                                        </ReportDataInfo>
                                    </ReportData>
                                </ReportsWell>

                                <ReportsIll>
                                    <SadIcon
                                        height={scale(45)}
                                        width={scale(45)}
                                        fill='#ffffff'
                                    />
                                    <ReportData>
                                        <ReportDataTitle>
                                            {translate('diary.bad')}
                                        </ReportDataTitle>
                                        <ReportDataInfo>
                                            {daysBad === 1
                                                ? daysBad +
                                                  translate('diary.report')
                                                : daysBad +
                                                  translate('diary.reports')}
                                        </ReportDataInfo>
                                    </ReportData>
                                </ReportsIll>
                            </ReportsAll>
                        </UserReports>
                    </UserDash>
                </ScrollViewStyled>
            </Container>
        </>
    )
}
Example #18
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
BadReport = ({ navigation }) => {
    const {
        token,
        user,
        group,
        location,
        getCurrentLocation,
        updateUserScore,
        surveys,
        storeSurveys,
        getCurrentUserInfo,
        storeCacheData,
    } = useUser()

    const [isLoading, setIsLoading] = useState(true)
    const [symptoms, setSymptoms] = useState([])

    const [badSince, setBadSince] = useState(today)
    const [personSymptoms, setPersonSymptoms] = useState([])
    const [hasContactWithSymptoms, setHasContactWithSymptoms] = useState(false)
    const [contactWithSymptom, setContactWithSymptom] = useState(null)
    const [hasTraveled, setHasTraveled] = useState(false)
    const [traveledTo, setTraveledTo] = useState('Brazil')
    const [wentToHospital, setWentToHospital] = useState(false)

    const [showAlert, setShowAlert] = useState(false)
    const [showProgressBar, setShowProgressBar] = useState(false)
    const [alertTitle, setAlertTitle] = useState(null)
    const [alertMessage, setAlertMessage] = useState(null)

    const [inviteSurveillance, setInviteSurveillance] = useState(false)
    const [instituition, setInstituition] = useState('')

    const person = getCurrentUserInfo()

    useEffect(() => {
        getSymptoms()
        getGroupName()
    }, [])

    useEffect(() => {
        if (
            !user.is_vigilance &&
            group.group_manager &&
            group.group_manager.vigilance_email
        ) {
            setInviteSurveillance(true)
        }
    }, [])

    const getGroupName = () => {
        const groupName = person.group ? person.group.split('/')[3] : null
        setInstituition(groupName)
    }

    const showConfirmation = (status, data) => {
        const message = getSurveyConfirmation(status, data)

        setAlertTitle(
            <Text>
                {message.alertTitle} {message.emojiTitle}
            </Text>
        )
        setAlertMessage(
            <Text>
                {message.alertMessage} {message.emojiMessage} {'\n'}
                {translate('badReport.messages.seeADoctor')}
            </Text>
        )

        setShowAlert(true)
        console.log(message.alertMessage)
    }

    const showWhatsappAlert = (status, body) => {
        Alert.alert(
            translate('map.alert'),
            translate('map.share'),
            [
                {
                    text: translate('map.noAlert'),
                    onPress: () => showConfirmation(status, body),
                },
                {
                    text: translate('badReport.yes'),
                    onPress: () => {
                        Share.open(shareOptions)
                            .then((res) => {
                                console.log(res)
                            })
                            .catch((err) => {
                                console.log(err)
                            })
                        showConfirmation(status, body)
                    },
                },
            ],
            { cancelable: false }
        )
    }

    const showSyndromeAlert = (status, body) => {
        let alert = []

        if (body.messages.top_3[0].name === 'Síndrome Gripal') {
            alert = [
                {
                    text: translate('advices.moreInformations'),
                    onPress: () => {
                        redirectAlert(
                            'Ministerio da Saúde',
                            'Deseja ser redirecionado para o website do Ministério da Saúde?',
                            'https://coronavirus.saude.gov.br/sobre-a-doenca#se-eu-ficar-doente'
                        )
                    },
                },
                {
                    text: 'Ok',
                    onPress: () => {
                        if (!inviteSurveillance) {
                            showWhatsappAlert(status, body)
                        } else {
                            showSurveillanceInvite(
                                person.name,
                                { status, body },
                                showWhatsappAlert,
                                navigation
                            )
                        }
                    },
                },
            ]
        } else {
            alert = [
                {
                    text: 'Ok',
                    onPress: () => {
                        if (!inviteSurveillance) {
                            showConfirmation(status, body)
                        } else {
                            showSurveillanceInvite(
                                person.name,
                                { status, body },
                                showConfirmation,
                                navigation
                            )
                        }
                    },
                },
            ]
        }

        Alert.alert(
            body.messages.top_syndrome_message?.title,
            body.messages.top_syndrome_message.warning_message,
            alert,
            { cancelable: false }
        )
    }

    const sortSymptoms = (symptoms = []) => {
        // Sort in alphabetical order
        symptoms.sort((a, b) => {
            if (a.description !== b.description) {
                if (a.description < b.description) return -1
                return 1
            }
            return 0
        })
        return symptoms
    }

    const getSymptoms = async () => {
        const response = await getAppSymptoms(token)

        if (response.status === 200) {
            const sortedSymptoms = sortSymptoms(response.data.symptoms)
            setSymptoms(sortedSymptoms)
            setIsLoading(false)
        }
    }

    const sendSurvey = async () => {
        // Send Survey BAD CHOICE
        setShowProgressBar(true)

        let local = {}
        if (location.error !== 0) {
            local = await getCurrentLocation()
        } else {
            local = location
        }

        if (personSymptoms.length === 0) {
            Alert.alert(
                translate('badReport.reportWithoutSymptom.title'),
                translate('badReport.reportWithoutSymptom.message')
            )
            setShowProgressBar(false)
            setShowAlert(false)

            return
        }

        const householdID = person.is_household ? person.id : null
        const badSinceDate = moment(badSince, 'DD-MM-YYYY').toISOString()
        const survey = {
            household_id: householdID,
            latitude: local.latitude,
            longitude: local.longitude,
            bad_since: badSinceDate,
            traveled_to: hasTraveled,
            went_to_hospital: wentToHospital,
            contact_with_symptom: contactWithSymptom,
            symptom: personSymptoms,
            created_at: moment().local().toISOString(),
        }

        const response = await createSurvey({ survey }, user.id, token)
        setShowProgressBar(false)

        // Wait page re-render
        const delay = (ms) => new Promise((res) => setTimeout(res, ms))
        await delay(50)

        updateUserScore()
        if (response.status === 201) {
            if (!response.data.errors && response.data.messages.top_3) {
                if (response.data.messages.top_3[0]) {
                    showSyndromeAlert(response.status, response.data)
                } else {
                    showConfirmation(response.status, response.data)
                }
            } else {
                showConfirmation(response.status, response.data)
            }

            // Save only important data for Map
            const localPin = {
                ...survey,
                bad_since: undefined,
                traveled_to: undefined,
                went_to_hospital: undefined,
                contact_with_symptom: undefined,
                symptom: ['symptom'],
            }
            await storeCacheData('localPin', localPin)

            const newSurveys = surveys.slice()
            newSurveys.push(response.data.survey)
            storeSurveys(newSurveys)
        } else {
            showConfirmation(response.status, response.data)
        }
    }

    if (isLoading) {
        return <ScreenLoader />
    }

    return (
        <Container>
            <ScrollViewStyled>
                <User>
                    <IconWrapper>
                        <Avatar
                            size={scale(58)}
                            source={handleAvatar(person.avatar)}
                            title={getInitials(person.name)}
                            rounded
                        />
                    </IconWrapper>
                    <InfoWrapper>
                        <Name>{getNameParts(person.name, true)}</Name>
                    </InfoWrapper>
                </User>

                <DateSince>
                    <DateText>{translate('badReport.sickAge')}</DateText>
                    <DateSelector
                        placeholder={translate('birthDetails.format')}
                        date={badSince}
                        format='DD-MM-YYYY'
                        minDate='01-01-2018'
                        maxDate={moment().local().format('DD-MM-YYYY')}
                        locale='pt-BR'
                        confirmBtnText={translate('birthDetails.confirmButton')}
                        cancelBtnText={translate('birthDetails.cancelButton')}
                        onDateChange={(date) => setBadSince(date)}
                    />
                </DateSince>

                <FormTitleWrapper>
                    <FormTitle>{translate('badReport.symptoms')}</FormTitle>
                </FormTitleWrapper>

                {symptoms.map((symptom) => (
                    <CheckBoxStyled
                        key={symptom.id}
                        title={symptom.description}
                        checked={personSymptoms.includes(symptom.code)}
                        onPress={() => {
                            if (personSymptoms.includes(symptom.code)) {
                                const newSymptoms = personSymptoms.filter(
                                    (code) => code !== symptom.code
                                )

                                setPersonSymptoms(newSymptoms)
                            } else {
                                const newSymptoms = personSymptoms.slice()
                                newSymptoms.push(symptom.code)

                                setPersonSymptoms(newSymptoms)
                            }
                        }}
                    />
                ))}

                <FormTitleWrapper>
                    <FormTitle>
                        {translate('badReport.answerQuestions')}
                    </FormTitle>
                </FormTitleWrapper>

                {user.group_id ? (
                    <CheckBoxStyled
                        title={
                            translate('badReport.checkboxes.third') +
                            instituition +
                            translate('badReport.checkboxes.thirdContinuation')
                        }
                        checked={hasTraveled}
                        onPress={() => setHasTraveled(!hasTraveled)}
                    />
                ) : null}

                {/*
                {hasTraveled ? (
                    <FormInline>
                        <FormLabel>{translate('badReport.checkboxes.fourth')}</FormLabel>
                        <Selector
                            initValue={translate('selector.label')}
                            cancelText={translate('selector.cancelButton')}
                            data={countryChoices}
                            onChange={(option) => setTraveledTo(option.key)}
                        />
                    </FormInline>
                ) : null}
                */}

                <CheckBoxStyled
                    title={translate('badReport.checkboxes.first')}
                    checked={hasContactWithSymptoms}
                    onPress={() =>
                        setHasContactWithSymptoms(!hasContactWithSymptoms)
                    }
                />
                {hasContactWithSymptoms ? (
                    <FormInline>
                        <FormLabel>Local onde ocorreu o contato:</FormLabel>
                        <Selector
                            initValue={translate('selector.label')}
                            cancelText={translate('selector.cancelButton')}
                            data={localSymptom}
                            onChange={(option) =>
                                setContactWithSymptom(option.key)
                            }
                        />
                    </FormInline>
                ) : null}

                <CheckBoxStyled
                    title={translate('badReport.checkboxes.second')}
                    checked={wentToHospital}
                    onPress={() => setWentToHospital(!wentToHospital)}
                />
                <Button onPress={() => sendSurvey()}>
                    <SendContainer>
                        <SendText>
                            {translate('badReport.checkboxConfirm')}
                        </SendText>
                    </SendContainer>
                </Button>
            </ScrollViewStyled>

            <CoolAlert
                show={showProgressBar}
                showProgress
                title={translate('badReport.messages.sending')}
            />
            <CoolAlert
                show={showAlert}
                title={alertTitle}
                message={alertMessage}
                closeOnTouchOutside
                closeOnHardwareBackPress={false}
                showConfirmButton
                confirmText={translate('badReport.messages.button')}
                onConfirmPressed={() => navigation.navigate('Mapa')}
                onDismiss={() => navigation.navigate('Mapa')}
            />
        </Container>
    )
}