Skip to content

Instantly share code, notes, and snippets.

@brunoksato
Created September 15, 2017 19:22
Show Gist options
  • Select an option

  • Save brunoksato/a630118a243c346129feb76bad73154d to your computer and use it in GitHub Desktop.

Select an option

Save brunoksato/a630118a243c346129feb76bad73154d to your computer and use it in GitHub Desktop.
Scandit barcode
import React from 'react';
import {
Image,
Platform,
ScrollView,
StyleSheet,
TouchableOpacity,
ListView,
View,
PermissionsAndroid,
Alert,
BackHandler,
} from 'react-native';
import {
Container,
Header,
Title,
Content,
Button,
Icon,
List,
ListItem,
Text,
Thumbnail,
Left,
Body,
Right,
H1,
} from "native-base";
import _ from 'lodash';
import MainService from '../api/main';
import Cache from '../api/cache';
import {ReplacePetmondo,Replace} from '../navigation/Navigation';
import {
BarcodePicker,
ScanditModule,
ScanSession,
Barcode,
SymbologySettings,
ScanSettings
} from 'react-native-scandit';
ScanditModule.setAppKey('KEY HERE');
let back = <View />;
if (Platform.OS !== 'ios') {
back = <View />
} else {
back = <Text style={{color: '#333'}}>Voltar</Text>
}
export default class ScanBatchScreen extends React.Component {
constructor(props){
super(props);
this.scanner = null;
const { state } = this.props.navigation;
this.state = {
userId: state.params.userId,
    dataSource: [],
hasCameraPermission: null,
alreadyRead: false,
exist: false,
byCamera: state.params.byCamera,
actual: 1,
};
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
handleBackButtonClick() {
const { navigation } = this.props;
navigation.dispatch(ReplacePetmondo(1, 'Batch', {
userId: navigation.state.params.userId,
byCamera: false
}));
return true;
}
static navigationOptions = ({ navigation }) => {
return {
title: "Produto atual: " + navigation.state.params.actual,
headerTintColor: '#333',
headerLeft: (
<Button style={styles.btnBack} transparent
onPress={() => {
navigation.dispatch(ReplacePetmondo(1, 'Batch', {
userId: navigation.state.params.userId,
byCamera: false
}));
}}>
<Icon name='arrow-back' style={{color: '#333'}}/>
{back}
</Button>
)
}
};
async componentDidMount() {
if (this.state.byCamera !== true) {
await Cache.clearProducts(this.state.userId);
}
this.scanner.startScanning();
}
async componentWillMount() {
if (Platform.OS !== 'ios') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
'title': 'Permissão para acessar camera',
'message': 'Para usar scanner precisa de permissão da camera'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.setState({hasCameraPermission: true});
} else {
this.setState({hasCameraPermission: false});
}
} else {
this.setState({hasCameraPermission: true});
}
this.settings = new ScanSettings();
this.settings.setSymbologyEnabled(Barcode.Symbology.EAN13, true);
this.settings.setSymbologyEnabled(Barcode.Symbology.EAN8, true);
this.settings.setSymbologyEnabled(Barcode.Symbology.UPCA, true);
this.settings.setSymbologyEnabled(Barcode.Symbology.UPCE, true);
this.settings.setSymbologyEnabled(Barcode.Symbology.CODE39, true);
this.settings.setSymbologyEnabled(Barcode.Symbology.ITF, true);
this.settings.setSymbologyEnabled(Barcode.Symbology.QR, true);
this.settings.setSymbologyEnabled(Barcode.Symbology.DATA_MATRIX, true);
this.settings.setSymbologyEnabled(Barcode.Symbology.CODE128, true);
this.settings.getSymbologySettings(Barcode.Symbology.CODE39)
.activeSymbolCounts = [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
this.setState({ alreadyRead: false, exist: false });
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
async onScan(session) {
const { navigation } = this.props;
const barcode = session.newlyRecognizedCodes[0].data;
// const { data } = session;
const { alreadyRead, userId, exist, actual } = this.state;
if (alreadyRead) {
return;
}
if (barcode === '') return;
let result = await MainService.getProductBarcode(barcode);
if (result.status === "Produto não existente") {
if (exist) {
return;
}
this.setState({ exist: true });
this.scanner.pauseScanning();
Alert.alert(
'Atenção',
'Produto não existente',
[
{text: 'Continuar', onPress: async() => {
this.scanner.resumeScanning();
this.setState({ exist: false });
}, style: 'cancel'},
{text: 'Tirar foto', onPress: async() => {
this.setState({ exist: false, alreadyRead: false });
this.scanner = null;
setTimeout(() => {
navigation.dispatch(Replace(0, 'Camera', {
userId: navigation.state.params.userId,
barcode: barcode,
actual: navigation.state.params.actual,
}));
}, 450);
}},
],
{ cancelable: false }
)
return;
}
let resultProduct = await Cache.listProducts(userId);
let newArray = [];
if (resultProduct !== null) {
if (resultProduct.length >= 10) {
Alert.alert('Atenção','Quantidade máxima atinginda salve os produtos para continuar');
this.setState({ alreadyRead: true });
navigation.dispatch(ReplacePetmondo(1, 'Batch', {
userId: navigation.state.params.userId,
byCamera: false
}));
return;
}
newArray = _.uniqBy(resultProduct, 'id');
await Cache.saveProduct(userId, newArray);
}
result.results._ref = resultProduct === null ? 1 : navigation.state.params.actual + 1;
await Cache.addProduct(userId, result.results);
newArray.push(result.results);
let newArray2 = _.uniqBy(newArray, 'id');
await Cache.saveProduct(userId, newArray2);
navigation.setParams({ actual: newArray2.length });
}
render() {
const { hasCameraPermission } = this.state;
let permissionText = <View />;
if (hasCameraPermission === null) {
permissionText = <Text style={styles.title}>Não tem permissão para acessar a camera</Text>;
} else if (hasCameraPermission === false) {
permissionText = <Text style={styles.title}>Não tem permissão para acessar a camera</Text>;
}
return (
<View style={{ flex: 1 }}>
{permissionText}
<BarcodePicker
onScan={(session) => { this.onScan(session) }}
scanSettings= { this.settings }
ref={(scan) => { this.scanner = scan }}
style={{ flex: 1 }}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
title: {
marginLeft: 20,
marginTop:20,
marginBottom:15,
},
touchable: {
height: 44,
marginTop: 20,
},
text: {
color: '#000',
fontSize: 17,
backgroundColor: 'transparent',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment