· 5 years ago · Jul 27, 2020, 12:48 PM
1import 'package:erg_app/Anchors.dart';
2import 'package:erg_app/StartScan.dart';
3import 'package:flutter/material.dart';
4import 'dart:convert';
5import 'package:shared_preferences/shared_preferences.dart';
6import 'package:http/http.dart' as http;
7
8class StockInventoryPage extends StatefulWidget {
9 String userid;
10 String oid;
11 String dcOid;
12 String stockoid;
13
14 StockInventoryPage(this.userid, this.oid, this.dcOid, this.stockoid);
15
16 @override
17 _StockInventoryPageState createState() => _StockInventoryPageState();
18}
19
20class _StockInventoryPageState extends State<StockInventoryPage> {
21 List<Products> products = new List();
22 List<Products> selectedProducts;
23 GlobalKey<ScaffoldState> _scaffoldKey;
24 TextEditingController quantity = new TextEditingController();
25
26 bool _isUpdate = false;
27
28 var userData;
29 var user;
30
31 String mainStockid = '';
32
33 // _showSnackBar(context, message) {
34 // _scaffoldKey.currentState.showSnackBar(
35 // SnackBar(
36 // content: Text(message),
37 // ),
38 // );
39 // }
40
41 @override
42 void initState() {
43 _getUserInfo();
44 GeneratekDailyStock();
45 selectedProducts = [];
46 _scaffoldKey = GlobalKey(); // key to get the context to show a SnackBar
47 super.initState();
48 }
49
50 void _getUserInfo() async {
51 SharedPreferences localStorage = await SharedPreferences.getInstance();
52 var userJson = localStorage.getString('loginRes');
53 user = json.decode(userJson);
54 setState(() {
55 userData = user;
56 });
57 }
58
59 void GeneratekDailyStock() async {
60 //http: //api.ergagro.com:112/GenerateDailyStockTaking?userId=b6caf34c-a425-4710-a3ee-aa22a382882a&agentOid=57&dcOid=11
61 final response = await http.get(
62 'http://api.ergagro.com:112/GenerateDailyStockTaking?userId=${widget.userid}&agentOid=${widget.oid}&dcOid=${widget.dcOid}');
63 print('${response.statusCode} Generated');
64 if (response.statusCode == 200) {
65 final jsonStatus = jsonDecode(response.body);
66 var stock = jsonStatus['Stock'];
67 // You can call the id of your own stock here.
68 mainStockid = stock['Oid'].toString();
69
70 List<dynamic> StockItems = stock['StockItems'];
71 for (var i in StockItems) {
72 print('${i['Oid'].toString()} iodd');
73 setState(() {
74 products.add(Products(
75
76 oid: i['Oid'], //this is the Id I am looking for
77 count: i['ItemType'].toString(),
78 name: i['ItemName'],
79 itemqty: i['Stock'].toString(),
80 measuringunit: i['Unit'],
81 ));
82 });
83 }
84 } else {
85 throw Exception();
86 }
87 }
88
89 final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
90
91 @override
92 Widget build(BuildContext context) {
93 return Scaffold(
94 appBar: AppBar(
95 automaticallyImplyLeading: true,
96 title: Text('Take Inventory'),
97 iconTheme: IconThemeData(color: Colors.white),
98 backgroundColor: Colors.green,
99 ),
100 body: Container(
101 padding: const EdgeInsets.fromLTRB(10, 30, 10, 10),
102 child: ListView(
103 children: <Widget>[
104 Row(
105 // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
106 children: <Widget>[
107 SizedBox(width: 15),
108 Icon(Icons.timelapse, size: 30, color: Colors.green[400]),
109 SizedBox(width: 15),
110 Text(
111 'Summary of Inventory',
112 style: TextStyle(color: Colors.green[400], fontSize: 20),
113 ),
114 ],
115 ),
116
117 ////////// Stock Summary//////////////
118
119 Padding(
120 padding: const EdgeInsets.all(5.0),
121 ////////////// 1st card///////////
122 child: Container(
123 width: 400,
124 height: 300,
125 child: Card(
126 elevation: 4.0,
127 color: Colors.grey[100],
128 margin:
129 EdgeInsets.only(left: 10, right: 10, top: 20, bottom: 10),
130 shape: RoundedRectangleBorder(
131 borderRadius: BorderRadius.circular(10)),
132 child: Container(
133 padding: EdgeInsets.only(left: 15, top: 20, bottom: 10),
134 width: 350,
135 child: ListView(
136 children: products.map((e) {
137 return ListTile(
138 onTap: () {
139 showDialog(
140 context: context,
141 builder: (context) {
142 return AlertDialog(
143 shape: RoundedRectangleBorder(
144 borderRadius:
145 BorderRadius.circular(20)),
146 title: Text(e.name),
147 content: TextField(
148 controller: quantity,
149 decoration: InputDecoration(
150 border: OutlineInputBorder(
151 borderRadius:
152 BorderRadius.circular(7),
153 ),
154 labelText: 'Quantity',
155 hintText: 'Input Amount to take'),
156 ),
157 actions: <Widget>[
158 FlatButton(
159 child: Text('Reset'),
160 onPressed: () {
161 setState(() {
162 quantity.text = '';
163 });
164 },
165 ),
166 FlatButton(
167 child: Text('Save'),
168 onPressed: () {
169 bool neww = true;
170 for (Products n in selectedProducts) {
171 // if the product in the model is equal to the selected product in the list
172 if (n.oid == e.oid) {
173 setState(() {
174 //then update the quantity of the product in the model
175 n.itemqty = quantity.text;
176 });
177 neww = false;
178 break;
179 }
180 }
181 if (neww == true) {
182 setState(() {
183 selectedProducts.add(Products(
184 count: e.count,
185 oid: e.oid,
186 name: e.name,
187 itemqty: quantity.text,
188 measuringunit: e.measuringunit,
189 ));
190 });
191 neww = false;
192 }
193 Navigator.pop(context);
194 },
195 ),
196 ],
197 );
198 });
199 },
200 title: Text(e.name),
201 // change it to quantity
202 trailing: Text('${e.itemqty}'),
203 );
204 }).toList(),
205 ),
206 ),
207 ),
208 ),
209 ),
210 ////////// End of Stock Summary//////////////
211
212 Divider(),
213 SizedBox(height: 20),
214 Row(
215 // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
216 children: <Widget>[
217 SizedBox(width: 35),
218 Icon(Icons.category, size: 30, color: Colors.green[400]),
219 SizedBox(width: 15),
220 Text(
221 'Take Inventory',
222 style: TextStyle(color: Colors.green[400], fontSize: 20),
223 ),
224 ],
225 ),
226
227 // Form widget initialization
228 Container(
229 margin: EdgeInsets.all(24),
230 child: Form(
231 key: _formKey,
232 child: Column(
233 mainAxisAlignment: MainAxisAlignment.center,
234 children: <Widget>[
235 // form was here
236 Divider(),
237 SizedBox(height: 20),
238 SingleChildScrollView(
239 scrollDirection: Axis.vertical,
240 child: SingleChildScrollView(
241 scrollDirection: Axis.horizontal,
242 child: DataTable(
243 columns: [
244 DataColumn(
245 label: Text('ID'),
246 ),
247 DataColumn(
248 label: Text('Items'),
249 ),
250 DataColumn(
251 label: Text('Quantities'),
252 ),
253 // Lets add one more column to show a delete button
254 DataColumn(
255 label: Text('Update'),
256 )
257 ],
258 rows: selectedProducts
259 .map(
260 (product) => DataRow(
261 selected:
262 selectedProducts.contains(product),
263 cells: [
264 DataCell(
265 Text(product.count),
266 onTap: () {
267 print('Selected ${product.count}');
268 },
269 ),
270 DataCell(
271 Text(product.name),
272 onTap: () {
273 print('Selected ${product.name}');
274 },
275 ),
276 DataCell(
277 Text(product.itemqty),
278 onTap: () {
279 print('Selected ${product.itemqty}');
280 },
281 ),
282 DataCell(
283 Text('Edit'),
284 onTap: () {
285 setState(() {
286 _isUpdate = true;
287 });
288 },
289 showEditIcon: true,
290 ),
291 ]),
292 )
293 .toList(),
294 ),
295 ),
296 ),
297 SizedBox(height: 20),
298 Container(
299 child: Row(
300 children: <Widget>[
301 RaisedButton(
302 padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
303 color: Colors.green,
304 child: Text(
305 "Submit and Validate",
306 style: TextStyle(
307 color: Colors.white,
308 fontWeight: FontWeight.bold,
309 fontSize: 12),
310 ),
311 onPressed: () async {
312 // widget.stockoid
313 var jsonbody = {
314 "oid": mainStockid,
315 "modifiedBy": userData['UserName'],
316 "modifiedOn": DateTime.now().toString(),
317 "submitted": true,
318 "submittedOn": DateTime.now().toString(),
319 "submittedBy": userData['UserName'].toString(),
320 };
321 for (Products i in selectedProducts) {
322 print('${i.oid.toString()} itemid');
323 //i.oid.toString(),
324 var stockupdate = {
325 "oid": i.oid,
326 "unitInStock": i.itemqty,
327 "modifiedBy": userData['UserName'].toString(),
328 "modifiedOn": DateTime.now().toString(),
329 };
330 print(
331 '${i.oid}, ${i.itemqty.toString()},${userData['UserName']}, ${DateTime.now().toString()} ploo');
332 await http
333 .put(
334 "http://api.ergagro.com:112/StockItem/UpdateStockItem",
335 headers: {
336 'Content-Type': 'application/json'
337 },
338 body: jsonEncode(stockupdate))
339 .then((value) {
340 print(value.statusCode);
341 });
342 }
343 await http
344 .put(
345 'http://api.ergagro.com:112/SubmitDailyStockTaking',
346 headers: {
347 'Content-Type': 'application/json'
348 },
349 body: jsonEncode(jsonbody))
350 .then((value) {
351 print('${value.statusCode} subb');
352 });
353 Navigator.push(
354 context,
355 new MaterialPageRoute(
356 builder: (context) =>
357 StartScanPage(widget.dcOid)));
358 //Send to API
359 },
360 shape: RoundedRectangleBorder(
361 borderRadius: BorderRadius.circular(300),
362 ),
363 ),
364 SizedBox(width: 10),
365
366 RaisedButton(
367 padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
368 color: Colors.orangeAccent,
369 child: Text(
370 "Submit and Close",
371 style: TextStyle(
372 color: Colors.white,
373 fontWeight: FontWeight.bold,
374 fontSize: 12),
375 ),
376 onPressed: () async {
377 var jsonbody = {
378 "oid": mainStockid,
379 "modifiedBy": userData['UserName'],
380 "modifiedOn": DateTime.now().toString(),
381 "submitted": false.toString(),
382 "submittedOn": DateTime.now().toString(),
383 "submittedBy": userData['UserName']
384 };
385 for (Products i in selectedProducts) {
386 var stockupdate = {
387 "oid": i.oid,
388 "unitInStock": i.itemqty,
389 "modifiedBy": userData['UserName'].toString(),
390 "modifiedOn": DateTime.now().toString(),
391 };
392 // widget.stockoid
393 print(
394 '${i.oid}, ${i.itemqty.toString()},${userData['UserName']},2020-07-06T07:19:01.492Z ploo');
395 await http
396 .put(
397 "http://api.ergagro.com:112/StockItem/UpdateStockItem",
398 headers: {
399 'Content-Type': 'application/json',
400
401 },
402 body: utf8.encode(json.encode(stockupdate))
403 )
404 .then((value) {
405 print(value.statusCode);
406 });
407 }
408 await http
409 .put(
410 'http://api.ergagro.com:112/SubmitDailyStockTaking',
411 headers: {
412 'Content-Type': 'application/json'
413 },
414 body: jsonEncode(jsonbody))
415 .then((value) {
416 print('${value.statusCode} submitted');
417 });
418 Navigator.push(
419 context,
420 new MaterialPageRoute(
421 builder: (context) => AnchorsPage()));
422 },
423 shape: RoundedRectangleBorder(
424 borderRadius: BorderRadius.circular(50),
425 ),
426 )
427 ],
428 ),
429 ),
430 SizedBox(height: 30),
431 ],
432 ),
433 ),
434 ),
435 // End of form widget Initialization
436
437 Divider(),
438 ],
439 ),
440 ),
441 );
442 }
443}
444
445//Product Model
446class Products {
447 var oid;
448 String count;
449 String name;
450 String measuringunit;
451 String itemqty;
452 Products({this.oid, this.count, this.name, this.itemqty, this.measuringunit});
453
454 // static List<Products> getProducts() {
455 // return <Products>[
456 // Products(
457 // count: "1",
458 // name: "NPK Fertilizer",
459 // itemqty: "50",
460 // measuringunit: "bag",
461 // ),
462 // Products(
463 // count: "2",
464 // name: "Urea Fertilizer",
465 // itemqty: "560",
466 // measuringunit: "bag",
467 // ),
468 // Products(
469 // count: "3",
470 // name: "Spray",
471 // itemqty: "150",
472 // measuringunit: "bottles",
473 // ),
474 // ];
475 // }
476}
477