PostMoney.js 7.07 KB
Newer Older
1
import React, { useState, useEffect } from 'react';
2
import { View, Text, StyleSheet, Button } from 'react-native';
3
import { DEBUG, enablePromise, openDatabase } from 'react-native-sqlite-storage';
4
5
6
7
import InputBox from './components/InputBox';
import ButtonsForm from './components/ButtonsForm';
import SelectForm from './components/SelectForm';
import StyledButton from './components/StyledButton';
8
9
import DatePicker from './components/DatePicker';
import moneyApi from './MoneyDB';
10

11
12
13
14
DEBUG(true);
enablePromise(true);

const db = openDatabase({
15
16
17
    name: 'MyMoney',
    location: 'default',
    createFromLocation: '~MyMoney.db', // android/src/main/assets/TestDB.db 파일을 위치 시킴
18
19
});

20
21
22
23
24
25
26

const getDate = () => {
    var date = new Date();
    return (String(date.toJSON()).split(/T/)[0])
}

const INIT_SUBCATEGORIES = [
27
    {
28
29
30
        id: 1,
        value: '간식',
        foreign_id: 1
31
32
    },
    {
33
34
35
        id: 2,
        value: '외식',
        foreign_id: 1
36
37
    },
    {
38
39
40
        id: 3,
        value: '배달',
        foreign_id: 1
41
42
    },
    {
43
44
45
        id: 4,
        value: '택시',
        foreign_id: 2
46
47
    },
    {
48
49
50
        id: 5,
        value: '영화',
        foreign_id: 3
51
52
    },
    {
53
54
55
        id: 6,
        value: '뮤지컬',
        foreign_id: 3
56
57
58
59
60
    },
]

const PostMoney = () => {
    const [selectedIndex, setSelectedIndex] = useState(0)
61
    const [date, setDate] = useState(getDate())
62
63
    const [contents, setContents] = useState('')
    const [price, setPrice] = useState(0)
64
65
66
67
68
69
    const [asset_type, setAsset_type] = useState([])
    const [selected_asset_type, setSelected_asset_type] = useState(0)
    const [categories, setCategories] = useState([])
    const [selected_cat, setSelected_cat] = useState(0)
    const [subcategories, setSubcategories] = useState(INIT_SUBCATEGORIES)
    const [selected_subcat, setSelected_subcat] = useState(0)
70

71
    console.log('type: ', selectedIndex, '| date: ', date, '| contents: ', contents, '| price: ', price, '| selected_asset_type: ', selected_asset_type, '| selected_cat: ', selected_cat, '| selected_subcat: ', selected_subcat)
72

73
74
    const insertData = async () => {
        try {
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
            let type = ''
            if (selectedIndex === 0) { type = '수입' }
            else if (selectedIndex === 1) { type = '지출' }
            else { type = '이동' }

            (await db).transaction((tx) => {
                console.log("데이터 삽입하기");
                tx.executeSql('INSERT INTO Money (type, date, contents, price, asset_type, category, subcategory) VALUES (?,?,?,?,?,?,?);',
                    [type, date, contents, price, selected_asset_type, selected_cat, selected_subcat],
                    () => { console.log("삽입 성공"); },
                    (error) => console.log(error))
            })
        } catch (error) {
            console.log('error in insert data', error)
        }
    }

    const loadCat = async () => {
        try {
            await moneyApi.QueryFunc(async (tx) => {
                console.log("카테고리 부르기");
                const [txn, results] = await tx.executeSql('SELECT * FROM categories');
                console.log('item length', results.rows.length);
                const temp = [];
                for (let i = 0; i < results.rows.length; i++) {
                    const tempId = results.rows.item(i).category_id;
                    const tempName = results.rows.item(i).category_name;
                    temp.push({ id: tempId, value: tempName });
                }
                setCategories(temp);
            })
        } catch (error) {
            console.log('error in load data ( postMoney.js )', error)
        }
    }
110

111
112
113
114
115
116
117
118
119
120
121
122
123
124
    const loadAssetType = async () => {
        try {
            (await db).transaction(async (tx) => {
                console.log("자산 유형 부르기");
                const [txn, results] = await tx.executeSql('SELECT * FROM assets_type');
                console.log('item length', results.rows.length);
                const temp = [];
                for (let i = 0; i < results.rows.length; i++) {
                    const tempId = results.rows.item(i).assets_id;
                    const tempName = results.rows.item(i).assets_name;
                    temp.push({ id: tempId, value: tempName });
                }
                setAsset_type(temp);
            })
125
        } catch (error) {
126
            console.log('error in insert data', error)
127
        }
128
129
130
131
132
133
    }

    useEffect(() => {
        loadCat()
        loadAssetType()
    }, [])
134

135
136
137
138
139
140
141
    return (
        <View>
            <View>
                <ButtonsForm
                    onPress={(index) => setSelectedIndex(index)}
                    selectedIndex={selectedIndex}
                    group={["수입", "지출", "이동"]} />
142
143
144
145
146
                <DatePicker
                    inputTitle="날짜"
                    date={date}
                    setDate={setDate}
                />
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
                <InputBox
                    inputTitle="내용"
                    placeholder="내용을 입력하세요"
                    onChangeText={
                        (contents) => setContents(contents)
                    }
                    maxLength={30}
                />
                <InputBox
                    inputTitle="금액"
                    placeholder="금액을 입력하세요"
                    onChangeText={
                        (price) => setPrice(price)
                    }
                    keyboardType="numeric"
                    maxLength={30}
                />
                <SelectForm
                    inputTitle="자산"
166
167
168
169
                    placeholder="자산 선택"
                    data={asset_type}
                    selectedData={selected_asset_type}
                    onValueChange={(assetId) => setSelected_asset_type(assetId)}
170
171
172
                />
                <SelectForm
                    inputTitle="구분"
173
174
175
176
177
178
179
                    placeholder="카테고리 선택"
                    data={categories}
                    selectedData={selected_cat}
                    onValueChange={(catId) => setSelected_cat(catId)}
                    subData={subcategories}
                    selectedSubData={selected_subcat}
                    onSubValueChange={(subcatId) => setSelected_subcat(subcatId)}
180
181
182
183
184
                />
            </View>
            <View style={style.buttonRow}>
                <StyledButton
                    name="저장하기"
185
                    onPress={insertData}
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
                    style={style.submitButton}
                />
                <StyledButton
                    name="취소"
                    onPress={() => console.log('취소버튼')}
                    style={style.cancelButton}
                />
            </View>
        </View>
    )
}

const style = StyleSheet.create({
    Font: {
        fontSize: 24
    },
    buttonRow: {
        flexDirection: 'row',
        alignItems: "center",
        marginHorizontal: 10,
        marginVertical: 3,
    },
    submitButton: {
        flex: 3,
        height: 50,
    },
    cancelButton: {
        flex: 1,
        height: 50,
    }
});

export default PostMoney;