build_app

This commit is contained in:
risadmin_prod 2025-04-14 04:13:25 +00:00
parent 1c59ad9fa8
commit 5c9f425dd5
13 changed files with 5068 additions and 68 deletions

View File

@ -69,6 +69,9 @@ public class BuilderService {
executeDump(true);
// ADD OTHER SERVICE
addCustomMenu( "Emp_details", "Transcations");
System.out.println("dashboard and menu inserted...");

View File

@ -0,0 +1,259 @@
package com.realnet.vpspack.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.realnet.config.EmailService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.domain.*;
import com.realnet.fnd.response.EntityResponse;
import org.springframework.http.*;
import org.springframework.beans.factory.annotation.*;
import com.realnet.vpspack.Entity.Emp_details;
import com.realnet.vpspack.Services.Emp_detailsService ;
@RequestMapping(value = "/Emp_details")
@CrossOrigin("*")
@RestController
public class Emp_detailsController {
@Autowired
private Emp_detailsService Service;
@Value("${projectPath}")
private String projectPath;
@PostMapping("/Emp_details")
public Emp_details Savedata(@RequestBody Emp_details data) {
Emp_details save = Service.Savedata(data) ;
System.out.println("data saved..." + save);
return save;
}
@PutMapping("/Emp_details/{id}")
public Emp_details update(@RequestBody Emp_details data,@PathVariable Integer id ) {
Emp_details update = Service.update(data,id);
System.out.println("data update..." + update);
return update;
}
// get all with pagination
@GetMapping("/Emp_details/getall/page")
public Page<Emp_details> getall(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "size", required = false) Integer size) {
Pageable paging = PageRequest.of(page, size);
Page<Emp_details> get = Service.getAllWithPagination(paging);
return get;
}
@GetMapping("/Emp_details")
public List<Emp_details> getdetails() {
List<Emp_details> get = Service.getdetails();
return get;
}
// get all without authentication
@GetMapping("/token/Emp_details")
public List<Emp_details> getallwioutsec() {
List<Emp_details> get = Service.getdetails();
return get;
}
@GetMapping("/Emp_details/{id}")
public Emp_details getdetailsbyId(@PathVariable Integer id ) {
Emp_details get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Emp_details/{id}")
public ResponseEntity<?> delete_by_id(@PathVariable Integer id ) {
Service.delete_by_id(id);
return new ResponseEntity<>(new EntityResponse("Deleted"), HttpStatus.OK);
}
}

View File

@ -0,0 +1,129 @@
package com.realnet.vpspack.Entity;
import lombok.*;
import com.realnet.WhoColumn.Entity.Extension;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
@Entity
@Data
public class Emp_details extends Extension {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String text_field;
private int numbera;
private String phone_number;
@Column(length = 2000)
private String paragraph_field;
private String password_field;
@Transient
private String confirmpassword_field;
@Column(length = 2000)
private String textarea_field;
private String date_field;
private String datetime_field;
private String email_field;
private boolean toggle_switch;
private String url_field;
private int decimal_field;
private int percentage_field;
private String recaptcha;
private String document_sequence;
private boolean qr_code;
private boolean bar_code;
private String fileupload_testname;
private String fileupload_testpath ;
private String imageupload_testname;
private String imageupload_testpath ;
private String audio_testname;
private String audio_testpath ;
private String currencys;
private String barcode_test;
private int numberb;
private String calculatedadd;
}

View File

@ -0,0 +1,70 @@
package com.realnet.vpspack.Repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.*;
import com.realnet.vpspack.Entity.Emp_details;
@Repository
public interface Emp_detailsRepository extends JpaRepository<Emp_details, Integer> {
@Query(value = "select * from emp_details where created_by=?1", nativeQuery = true)
List<Emp_details> findAll(Long creayedBy);
@Query(value = "select * from emp_details where created_by=?1", nativeQuery = true)
Page<Emp_details> findAll(Pageable page, Long creayedBy);
}

View File

@ -0,0 +1,304 @@
package com.realnet.vpspack.Services;
import com.realnet.vpspack.Repository.Emp_detailsRepository;
import com.realnet.vpspack.Entity.Emp_details
;import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.realnet.SequenceGenerator.Service.SequenceService;
import org.springframework.data.domain.Page;
import com.realnet.realm.Entity.Realm;
import com.realnet.realm.Services.RealmService;
import org.springframework.data.domain.Pageable;
import org.springframework.http.*;
import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.users.entity1.AppUser;
import org.springframework.stereotype.Service;
@Service
public class Emp_detailsService {
@Autowired
private Emp_detailsRepository Repository;
@Autowired
private AppUserServiceImpl userService;
@Autowired
private RealmService realmService;
@Autowired
private SequenceService document_sequencesequenceService;
public Emp_details Savedata(Emp_details data) {
data.setDocument_sequence (document_sequencesequenceService.GenerateSequence(""));
data.setUpdatedBy(getUser().getUserId());
data.setCreatedBy(getUser().getUserId());
data.setAccountId(getUser().getAccount().getAccount_id());
Emp_details save = Repository.save(data);
return save;
}
// get all with pagination
public Page<Emp_details> getAllWithPagination(Pageable page) {
return Repository.findAll(page, getUser().getUserId());
}
public List<Emp_details> getdetails() {
List<Realm> realm = realmService.findByUserId(getUser().getUserId());
List<Emp_details> all = Repository.findAll(getUser().getUserId());
return all ; }
public Emp_details getdetailsbyId(Integer id) {
return Repository.findById(id).get();
}
public void delete_by_id(Integer id) {
Repository.deleteById(id);
}
public Emp_details update(Emp_details data,Integer id) {
Emp_details old = Repository.findById(id).get();
old.setText_field(data.getText_field());
old.setNumbera(data.getNumbera());
old.setPhone_number(data.getPhone_number());
old.setParagraph_field(data.getParagraph_field());
old.setPassword_field(data.getPassword_field());
old.setTextarea_field(data.getTextarea_field());
old.setDate_field(data.getDate_field());
old.setDatetime_field(data.getDatetime_field());
old.setEmail_field(data.getEmail_field());
old.setToggle_switch (data.isToggle_switch());
old.setUrl_field(data.getUrl_field());
old.setDecimal_field(data.getDecimal_field());
old.setPercentage_field(data.getPercentage_field());
old.setRecaptcha(data.getRecaptcha());
old.setDocument_sequence(data.getDocument_sequence());
old.setQr_code(data.isQr_code());
old.setBar_code(data.isBar_code());
old.setCurrencys(data.getCurrencys());
old.setBarcode_test(data.getBarcode_test());
old.setNumberb(data.getNumberb());
old.setCalculatedadd(data.getCalculatedadd());
final Emp_details test = Repository.save(old);
data.setUpdatedBy(getUser().getUserId());
return test;}
public AppUser getUser() {
AppUser user = userService.getLoggedInUser();
return user;
}}

View File

@ -0,0 +1,2 @@
CREATE TABLE db.Emp_details(id BIGINT NOT NULL AUTO_INCREMENT, audio_test VARCHAR(400), numberb int, numbera int, imageupload_test VARCHAR(400), currencys VARCHAR(400), text_field VARCHAR(400), datetime_field VARCHAR(400), toggle_switch VARCHAR(400), percentage_field int, phone_number VARCHAR(400), barcode_test VARCHAR(400), qr_code bit(1), email_field VARCHAR(400), calculatedadd VARCHAR(400), url_field VARCHAR(400), textarea_field VARCHAR(400), paragraph_field VARCHAR(400), bar_code bit(1), document_sequence VARCHAR(400), recaptcha VARCHAR(400), fileupload_test VARCHAR(400), password_field VARCHAR(400), date_field Date, decimal_field int, PRIMARY KEY (id));

View File

@ -0,0 +1,164 @@
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
import '../../../../resources/api_constants.dart';
import '../../../../data/network/base_network_service.dart';
import '../../../../data/network/network_api_service.dart';
class emp_detailsApiService {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<List<Map<String, dynamic>>> getEntities() async {
try {
final response = await _helper.getGetApiResponse('$baseUrl/Emp_details/Emp_details');
final entities = (response as List).cast<Map<String, dynamic>>();
return entities;
} catch (e) {
throw Exception('Failed to get all entities: $e');
}
}
Future<List<Map<String, dynamic>>> getAllWithPagination(
int page, int size) async {
try {
final response =
await _helper.getGetApiResponse('$baseUrl/Emp_details/Emp_details/getall/page?page=$page&size=$size');
final entities =
(response['content'] as List).cast<Map<String, dynamic>>();
return entities;
} catch (e) {
throw Exception('Failed to get all without pagination: $e');
}
}
Future<Map<String, dynamic>> createEntity(
Map<String, dynamic> entity) async {
try {
print("in post api$entity");
final response =
await _helper.getPostApiResponse('$baseUrl/Emp_details/Emp_details', entity);
print(entity);
// Assuming the response is a Map<String, dynamic>
Map<String, dynamic> responseData = response;
return responseData;
} catch (e) {
throw Exception('Failed to create entity: $e');
}
}
Future<void> updateEntity( int entityId, Map<String, dynamic> entity) async {
try {
await _helper.getPutApiResponse('$baseUrl/Emp_details/Emp_details/$entityId',
entity); print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity( int entityId) async {
try {
await _helper.getDeleteApiResponse('$baseUrl/Emp_details/Emp_details/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
}

View File

@ -0,0 +1,869 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Emp_details_viewModel/Emp_details_view_model_screen.dart';
import '../../../../utils/image_constant.dart';
import '../../../../utils/size_utils.dart';
import '../../../../theme/app_style.dart';
import '../../../../widgets/app_bar/appbar_image.dart';
import '../../../../widgets/app_bar/appbar_title.dart';
import '../../../../widgets/app_bar/custom_app_bar.dart';
import 'package:barcode_widget/barcode_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:intl/intl.dart';
import 'dart:math';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';
import 'package:flutter/services.dart';
class emp_detailsUpdateEntityScreen extends StatefulWidget {
final Map<String, dynamic> entity;
emp_detailsUpdateEntityScreen({required this.entity});
@override
_emp_detailsUpdateEntityScreenState createState() => _emp_detailsUpdateEntityScreenState();
}
class _emp_detailsUpdateEntityScreenState extends State<emp_detailsUpdateEntityScreen> {
final _formKey = GlobalKey<FormState>();
bool _passwordVisiblepassword_field = false;
bool _isPasswordValidpassword_field = true;
bool _doPasswordsMatchpassword_field = true;
String _passwordpassword_field = ''; // To store the first password
void _validatePasswordpassword_field(String password) {
setState(() {
_isPasswordValidpassword_field = password.isNotEmpty;
_passwordpassword_field = password; // Store the password for later comparison
_doPasswordsMatchpassword_field = true; // Reset match flag on new input
});
}
void _validateConfirmPasswordpassword_field(String confirmPassword) {
setState(() {
_doPasswordsMatchpassword_field = confirmPassword == _passwordpassword_field;
});
}
TextEditingController date_field = TextEditingController();
DateTime selectedDatedate_field = DateTime.now();
Future<void> _selectDatedate_field(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDatedate_field,
firstDate: DateTime(2000),
lastDate: DateTime(2101),
);
print(picked);
if (picked != null && picked != selectedDatedate_field) {
setState(() {
selectedDatedate_field = picked;
});
}
}
bool _isemail_fieldEmailValid = true;
void _validateemail_fieldEmail(String email) {
setState(() {
_isemail_fieldEmailValid = RegExp(r'^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$').hasMatch(email);
});
}
bool istoggle_switch = false;
bool _isUrlValidurl_field = true;
void _validateUrlurl_field(String url) {
setState(() {
_isUrlValidurl_field= Uri.parse(url).isAbsolute;
});
}
bool qr_codecBox = false;
bool bar_codecBox = false;
final TextEditingController _inputcurrencysController = TextEditingController();
double editedcurrencysValue = 0.0;
late String inputDatabarcode_test; // By default barcode
TextEditingController controllerInputbarcode_test = TextEditingController();
@override
void initState() {
super.initState();
final provider = Provider.of<Emp_detailsViewModelScreen>(context, listen: false);
istoggle_switch = widget.entity['toggle_switch'] ?? false; // Set initial value
qr_codecBox = widget.entity['qr_code'] ?? false;
bar_codecBox = widget.entity['bar_code'] ?? false;
// Convert the currency value to double if it's not already
if (widget.entity['currency'] is String) {
widget.entity['currency'] =
double.tryParse(widget.entity['currency']) ?? 0.0;
}
// Initially set the controller text without formatting
_inputcurrencysController.text = widget.entity['currency'].toString();
editedcurrencysValue = widget.entity['currency'];
inputDatabarcode_test = widget.entity['barcode_test'] ?? "Hello";
controllerInputbarcode_test.text = inputDatabarcode_test;
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<Emp_detailsViewModelScreen>(context, listen: false);
return Scaffold(
appBar: CustomAppBar(
height: getVerticalSize(49),
leadingWidth: 40,
leading: AppbarImage(
height: getSize(24),
width: getSize(24),
svgPath: ImageConstant.imgArrowleftBlueGray900,
margin: getMargin(left: 16, top: 12, bottom: 13),
onTap: () {
Navigator.pop(context);
}),
centerTitle: true,
title: AppbarTitle(text: "Update Emp_details"), actions: [
],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
ReusableTextField(
label: "Please Enter Text Field",
initialValue: widget.entity['text_field'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['text_field'] = value,
),
SizedBox(height: 16),
ReusableTextField(
initialValue: widget.entity['numbera'].toString(),
onSaved: (value) => widget.entity['numbera']= value,
label: "Enter Numbera",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a number';
}
return null;
},
),
ReusableTextField(
initialValue: widget.entity['phone_number'],
onSaved: (value) => widget.entity['phone_number'] = value,
label: "Enter Phone Number",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(
10), // Limit input to 10 digits
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Phone Number';
}
if (value.length != 10) {
return 'Phone number must be exactly 10 digits';
}
return null;
},
),
// }),
ReusableTextField(
initialValue: widget.entity['paragraph_field'],
onSaved: (value) => widget.entity['paragraph_field']= value,
label: "Enter Paragraph Field",
maxLines: 5,
),
TextFormField(
initialValue: widget.entity['password_field'],
obscureText: !_passwordVisiblepassword_field,
decoration: InputDecoration(
labelText: 'Password Field',
suffixIcon: IconButton(
icon: Icon(
_passwordVisiblepassword_field
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
setState(() {
_passwordVisiblepassword_field = !_passwordVisiblepassword_field;
});
},
),
errorText:
_isPasswordValidpassword_field ? null : 'Please enter a password',
border: OutlineInputBorder(),
),
onSaved: (value) => widget.entity['password_field'] = value,
onChanged: _validatePasswordpassword_field,
),
const SizedBox(height: 16),
TextFormField(
obscureText: !_passwordVisiblepassword_field,
decoration: InputDecoration(
labelText: 'Confirm Password Field',
suffixIcon: IconButton(
icon: Icon(
_passwordVisiblepassword_field
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
setState(() {
_passwordVisiblepassword_field = !_passwordVisiblepassword_field;
});
},
),
errorText:
_doPasswordsMatchpassword_field ? null : 'Passwords do not match',
border: OutlineInputBorder(),
),
onChanged: _validateConfirmPasswordpassword_field,
),
ReusableTextField(
initialValue: widget.entity['textarea_field'],
onSaved: (value) => widget.entity['textarea_field']= value,
label: "Enter Textarea Field",
maxLines: 5,
),
ReusableDatePickerField(label: 'Date Field', controller: date_field, initialDate: widget.entity['date_field'],
onSaved: (value) => widget.entity['date_field'] = value,),
ReusableTextField(
label: "Please Enter Datetime Field",
initialValue: widget.entity['datetime_field'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['datetime_field'] = value,
),
SizedBox(height: 16),
Padding(
padding: getPadding(top: 19),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text("Email Field",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle
.txtGilroyMedium16Bluegray900),
CustomTextFormField(
hintText: "Enter Email Field",
initialValue: widget.entity['email_field'],
keyboardType: TextInputType.url,
errorText: _isemail_fieldEmailValid ? null : 'Please enter a valid URL',
onChanged: _validateemail_fieldEmail,
// ValidationProperties
onsaved: (value) {
widget.entity['email_field'] = value;
},
margin: getMargin(top: 6))
])),
SizedBox(height: 16),
Row(
children: [
Switch(
value: istoggle_switch,
onChanged: (newValue) {
setState(() {
istoggle_switch = newValue;
});
},
activeColor: Colors.white,
activeTrackColor: Colors.green,
inactiveThumbColor: Colors.white,
inactiveTrackColor: Colors.red,
),
const SizedBox(width: 8),
const Text('toggle switch'),
],
),
Padding(
padding: getPadding(top: 19),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text("Url Field",
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: AppStyle
.txtGilroyMedium16Bluegray900),
CustomTextFormField(
hintText: "Enter Url Field",
initialValue: widget.entity['url_field'],
keyboardType: TextInputType.url,
errorText: _isUrlValidurl_field ? null : 'Please enter a valid URL',
onChanged: _validateUrlurl_field,
// ValidationProperties
onsaved: (value) {
widget.entity['url_field'] = value;
},
margin: getMargin(top: 6))
])),
SizedBox(height: 16),
ReusableTextField(
initialValue: widget.entity['decimal_field'].toString(),
onSaved: (value) => widget.entity['decimal_field']= value,
label: "Enter Decimal Field",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a number';
}
return null;
},
),
ReusableTextField(
initialValue: widget.entity['percentage_field'].toString(),
onSaved: (value) => widget.entity['percentage_field']= value,
label: "Enter Percentage Field",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a number';
}
return null;
},
),
ReusableTextField(
label: "Please Enter recaptcha",
initialValue: widget.entity['recaptcha'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['recaptcha'] = value,
),
SizedBox(height: 16),
ReusableTextField(
label: "Please Enter document sequence",
initialValue: widget.entity['document_sequence'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['document_sequence'] = value,
),
SizedBox(height: 16),
Row(
children: [
Checkbox(
value: qr_codecBox,
onChanged: (newValue) {
setState(() {
qr_codecBox = newValue!;
});
},
),
const SizedBox(width: 8),
Text('Qr_code'),
Checkbox(
value: bar_codecBox,
onChanged: (newValue) {
setState(() {
bar_codecBox = newValue!;
});
},
),
const SizedBox(width: 8),
Text('Bar_code'),
],
),
SizedBox(height: 16),
ReusableTextField(
label: "Please Enter audio test",
initialValue: widget.entity['audio_test'] ?? '',
// ValidationProperties
onSaved: (value) => widget.entity['audio_test'] = value,
),
SizedBox(height: 16),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: _inputcurrencysController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Edit Currency Value',
prefixIcon: Icon(Icons.money),
border: OutlineInputBorder(),
),
onChanged: (text) {
setState(() {
try {
String currencyString = text;
currencyString = currencyString.replaceAll(',', ''); // Remove commas
currencyString = currencyString.replaceAll('', ''); // Remove currency symbol
editedcurrencysValue = double.parse(currencyString);
print("Parsed double value: $editedcurrencysValue");
} catch (e) {
print("Invalid input: $text");
editedcurrencysValue = 0.0; // Set to a default value or handle the error accordingly
}
});
},
onSaved: (value) {
widget.entity['currencys'] = editedcurrencysValue;
},
),
SizedBox(height: 16),
Text(
'Edited Currency Value: ${editedcurrencysValue.toStringAsFixed(2)}', // Display formatted currency value
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 16),
// Add other form fields here
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'Generate Barcode',
style: TextStyle(fontSize: 18),
),
const SizedBox(height: 16),
if (inputDatabarcode_test.isNotEmpty)
BarcodeWidget(
barcode: Barcode.code128(), // Choose the type of barcode
data: inputDatabarcode_test,
width: 200,
height: 80,
),
const SizedBox(height: 16),
TextField(
controller: controllerInputbarcode_test,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter data for barcode',
),
onChanged: (value) {
setState(() {
inputDatabarcode_test = value;
widget.entity['barcode_test'] = inputDatabarcode_test;
});
},
),
const SizedBox(height: 16),
// ElevatedButton(
// onPressed: () {
// setState(() {
// inputData = controllerInput.text;
// });
// },
// child: const Text('Generate Barcode'),
// ),
],
),
const SizedBox(height: 16),
ReusableTextField(
initialValue: widget.entity['numberb'].toString(),
onSaved: (value) => widget.entity['numberb']= value,
label: "Enter Numberb",
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a number';
}
return null;
},
),
CustomButton(
height: getVerticalSize(50),
text: "Update",
margin: getMargin(top: 24, bottom: 5),
onTap: () async {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
widget.entity['toggle_switch'] = istoggle_switch;
widget.entity['qr_code'] = qr_codecBox;
widget.entity['bar_code'] = bar_codecBox;
try {
await provider.updateEntity(
widget.entity[
'id'], // Assuming 'id' is the key in your entity map
widget.entity);
Navigator.pop(context);
} catch (e) {
// ignore: use_build_context_synchronously
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content:
Text('Failed to update Emp_details: $e'),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
},
),
],
),
),
),
),
);
}
}

View File

@ -0,0 +1,135 @@
import 'package:dio/dio.dart';
import '../../../../data/network/base_network_service.dart';
import '../../../../data/network/network_api_service.dart';
import '../../../../resources/api_constants.dart';
class Emp_detailsRepoScreen {
final String baseUrl = ApiConstants.baseUrl;
final BaseNetworkService _helper = NetworkApiService();
Future<dynamic> getEntities() async {
try {
final response =
await _helper.getGetApiResponse('$baseUrl/Emp_details/Emp_details');
return response;
} catch (e) {
throw Exception('Failed to get all entities: $e');
}
}
Future<dynamic> getAllWithPagination(int page, int size) async {
try {
final response = await _helper.getGetApiResponse(
'$baseUrl/Emp_details/Emp_details/getall/page?page=$page&size=$size');
return response;
} catch (e) {
throw Exception('Failed to get all without pagination: $e');
}
}
Future<dynamic> createEntity(Map<String, dynamic> entity) async {
try {
print("in post api$entity");
final response = await _helper.getPostApiResponse(
'$baseUrl/Emp_details/Emp_details', entity);
print(entity);
return response;
} catch (e) {
throw Exception('Failed to create entity: $e');
}
}
Future<void> updateEntity(int entityId, Map<String, dynamic> entity) async {
try {
await _helper.getPutApiResponse(
'$baseUrl/Emp_details/Emp_details/$entityId', entity);
print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity(int entityId) async {
try {
await _helper
.getDeleteApiResponse('$baseUrl/Emp_details/Emp_details/$entityId');
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
Future<dynamic> fileupload_testUpload(
String ref, String refTableNmae, FormData entity) async {
try {
String apiUrl = "$baseUrl/FileUpload/Uploadeddocs/$ref/$refTableNmae";
final response = await _helper.getPostApiResponse(apiUrl, entity);
return response;
} catch (e) {
throw Exception('Failed to Upload File: $e');
}
}
Future<dynamic> imageupload_testUpload(
String ref, String refTableNmae, FormData entity) async {
try {
String apiUrl = "$baseUrl/FileUpload/Uploadeddocs/$ref/$refTableNmae";
final response = await _helper.getPostApiResponse(apiUrl, entity);
return response;
} catch (e) {
throw Exception('Failed to Upload Imageupload test: $e');
}
}
Future<dynamic> audio_testUpload(
String ref, String refTableNmae, FormData entity) async {
try {
String apiUrl = "$baseUrl/FileUpload/Uploadeddocs/$ref/$refTableNmae";
final response = await _helper.getPostApiResponse(apiUrl, entity);
return response;
} catch (e) {
throw Exception('Failed to Upload File: $e');
}
}
}

View File

@ -0,0 +1,299 @@
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
import '../../../../utils/toast_messages/toast_message_util.dart';
import 'package:flutter/material.dart';
import '../Emp_details_Repo/Emp_details_repo_screen.dart';
class Emp_detailsViewModelScreen extends ChangeNotifier{
final Emp_detailsRepoScreen repo = Emp_detailsRepoScreen();
Future<List<Map<String, dynamic>>> getEntities() async {
try {
final response = await repo.getEntities();
final entities = (response as List).cast<Map<String, dynamic>>();
return entities;
} catch (e) {
throw Exception('Failed to get all entities: $e');
}
}
Future<List<Map<String, dynamic>>> getAllWithPagination(
int page, int size) async {
try {
final response =
await repo.getAllWithPagination(page, size); // Use await
print('with pagination res - $response');
// Ensure response is a Map<String, dynamic>
if (response is! Map<String, dynamic>) {
throw Exception('Unexpected response format: $response');
}
// Extract 'content' and ensure it's a list
final entities = (response['content'] as List)
.cast<Map<String, dynamic>>() // Ensure list of maps
.toList();
return entities;
} catch (e) {
print(e);
throw Exception('Failed to get all without pagination :- $e');
}
}
Future<Map<String, dynamic>> createEntity(Map<String, dynamic> entity) async {
try {
print("in post api - $entity");
// Wait for API response
final responseData =
await repo.createEntity(entity) as Map<String, dynamic>;
print('after value - $responseData');
ToastMessageUtil.showToast(
message: "Added Successfully", toastType: ToastType.success);
return responseData; // Return the data AFTER it is received
} catch (error) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Got Error", toastType: ToastType.error);
throw Exception(
'Failed to Create Entity: $error'); // Properly rethrow the error
}
}
Future<void> updateEntity(int entityId, Map<String, dynamic> entity) async {
try {
repo.updateEntity(entityId, entity).then((value) {
ToastMessageUtil.showToast(
message: "Updated Successfully", toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Got Error", toastType: ToastType.error);
},
);
print(entity);
} catch (e) {
throw Exception('Failed to update entity: $e');
}
}
Future<void> deleteEntity(int entityId) async {
try {
repo.deleteEntity(entityId).then((value) {
ToastMessageUtil.showToast(
message: "Deleted Successfully", toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Got Error", toastType: ToastType.error);
},
);
} catch (e) {
throw Exception('Failed to delete entity: $e');
}
}
// Modify the uploadfileupload_testimage function
Future<void> uploadfileupload_test(String ref, String refTableNmae,
String selectedFilePath, Uint8List imageTimageBytes) async {
try {
final Uint8List fileBytes = imageTimageBytes!;
final mimeType = fileupload_testlookupMimeType(selectedFilePath);
FormData formData = FormData.fromMap({
'file': MultipartFile.fromBytes(
fileBytes,
filename: selectedFilePath
.split('/')
.last, // Get the file name from the path
contentType: MediaType.parse(mimeType!),
),
});
await repo.fileupload_testUpload(ref, refTableNmae, formData).then((value) {
ToastMessageUtil.showToast(
message: "File uploaded successfully",
toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Failed to upload file", toastType: ToastType.error);
},
);
} catch (error) {
print('Error occurred during form submission: $error');
}
}
// Modify the lookupMimeType function if needed
String fileupload_testlookupMimeType(String filePath) {
final ext = filePath.split('.').last;
switch (ext) {
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'pdf':
return 'application/pdf';
// Add more cases for other file types as needed
default:
return 'application/octet-stream'; // Default MIME type
}
}
// Modify the uploadimageupload_testimage function
Future<void> uploadimageupload_test(String ref, String refTableNmae,
String selectedFilePath, Uint8List image_timageBytes) async {
try {
final Uint8List fileBytes = image_timageBytes!;
final mimeType = imageupload_testlookupMimeType(selectedFilePath);
FormData formData = FormData.fromMap({
'file': MultipartFile.fromBytes(
fileBytes,
filename: selectedFilePath
.split('/')
.last, // Get the file name from the path
contentType: MediaType.parse(mimeType!),
),
});
await repo.imageupload_testUpload(ref, refTableNmae, formData).then((value) {
ToastMessageUtil.showToast(
message: "File uploaded successfully",
toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Failed to upload file", toastType: ToastType.error);
},
);
} catch (error) {
print('Error occurred during form submission: $error');
}
}
// Modify the lookupMimeType function if needed
String imageupload_testlookupMimeType(String filePath) {
final ext = filePath.split('.').last;
switch (ext) {
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'pdf':
return 'application/pdf';
// Add more cases for other file types as needed
default:
return 'application/octet-stream'; // Default MIME type
}
}
// Modify the uploadaudio_testimage function
Future<void> uploadaudio_test(String ref, String refTableNmae,
String selectedFilePath, Uint8List image_timageBytes) async {
try {
final Uint8List fileBytes = image_timageBytes!;
final mimeType = audio_testlookupMimeType(selectedFilePath);
FormData formData = FormData.fromMap({
'file': MultipartFile.fromBytes(
fileBytes,
filename: selectedFilePath
.split('/')
.last, // Get the file name from the path
contentType: MediaType.parse(mimeType!),
),
});
await repo.audio_testUpload(ref, refTableNmae, formData).then((value) {
ToastMessageUtil.showToast(
message: "File uploaded successfully",
toastType: ToastType.success);
}).onError(
(error, stackTrace) {
print("error--$error");
ToastMessageUtil.showToast(
message: "Failed to upload file", toastType: ToastType.error);
},
);
} catch (error) {
print('Error occurred during form submission: $error');
}
}
// Modify the lookupMimeType function if needed
String audio_testlookupMimeType(String filePath) {
final ext = filePath.split('.').last.toLowerCase();
switch (ext) {
case 'mp3':
return 'audio/mpeg';
case 'wav':
return 'audio/wav';
case 'm4a':
return 'audio/mp4';
case 'flac':
return 'audio/flac';
// Add more cases for other audio formats as needed
default:
return 'application/octet-stream'; // Default MIME type
}
}
}

View File

@ -1,3 +1,6 @@
import '../../Entity/vpspack/Emp_details/Emp_detailsView/Emp_details_entity_list_screen.dart';
import '../../Entity/vpspack/Emp_details/Emp_details_viewModel/Emp_details_view_model_screen.dart';
import 'package:base_project/utils/image_constant.dart';
import 'package:base_project/commans/widgets/custome_drawe_item.dart';
import 'package:base_project/resources/app_colors.dart';
@ -9,79 +12,96 @@ import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
class MyCustomDrawer extends StatelessWidget {
const MyCustomDrawer({super.key});
const MyCustomDrawer({super.key});
@override
Widget build(BuildContext context) {
final email = UserManager().email;
final userName = UserManager().userName;
final provider = Provider.of<ProfileViewModel>(context, listen: false);
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
decoration: const BoxDecoration(
color: AppColors.primary,
),
currentAccountPicture: CircleAvatar(
radius: 60,
backgroundColor: AppColors.primary.withOpacity(0.3),
backgroundImage: provider.profileImageBytes != null
? MemoryImage(provider.profileImageBytes!)
: null,
child: provider.profileImageBytes != null
? null // Use backgroundImage for the actual image, so child should be null
: SvgPicture.asset(
ImageConstant.userProfileImg, // Placeholder SVG asset
@override
Widget build(BuildContext context) {
final email = UserManager().email;
final userName = UserManager().userName;
final provider = Provider.of<ProfileViewModel>(context, listen: false);
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
decoration: const BoxDecoration(
color: AppColors.primary,
),
currentAccountPicture: CircleAvatar(
radius: 60,
backgroundColor: AppColors.primary.withOpacity(0.3),
backgroundImage: provider.profileImageBytes != null
? MemoryImage(provider.profileImageBytes!)
: null,
child: provider.profileImageBytes != null
? null // Use backgroundImage for the actual image, so child should be null
: SvgPicture.asset(
ImageConstant.userProfileImg, // Placeholder SVG asset
// AppImages.userProfileImg, // Placeholder SVG asset
width: 60, // Adjust to fit the CircleAvatar
height: 60,
),
),
accountName: Text("Hello, $userName"),
accountEmail: Text(email.toString()),
),
DrawerItem(
color: AppColors.primary,
icon: Icons.person,
title: 'Profile',
onTap: () {
Navigator.pushNamed(context, RouteNames.profileView);
},
),
DrawerItem(
color: AppColors.primary,
icon: Icons.system_security_update,
title: 'System Parameters',
onTap: () {
width: 60, // Adjust to fit the CircleAvatar
height: 60,
),
),
accountName: Text("Hello, $userName"),
accountEmail: Text(email.toString()),
),
DrawerItem(
color: AppColors.primary,
icon: Icons.person,
title: 'Profile',
onTap: () {
Navigator.pushNamed(context, RouteNames.profileView);
},
),
DrawerItem(
color: AppColors.primary,
icon: Icons.system_security_update,
title: 'System Parameters',
onTap: () {
// Add navigation or other logic here
Navigator.pushNamed(context, RouteNames.systemParamsView);
},
),
DrawerItem(
color: AppColors.primary,
icon: Icons.password,
title: 'change password',
onTap: () {
Navigator.pushNamed(context, RouteNames.changePasswordView);
},
),
Navigator.pushNamed(context, RouteNames.systemParamsView);
},
),
DrawerItem(
color: AppColors.primary,
icon: Icons.password,
title: 'change password',
onTap: () {
Navigator.pushNamed(context, RouteNames.changePasswordView);
},
),
// NEW MENU
DrawerItem(
icon: Icons.logout,
color: Colors.red,
title: 'Logout',
onTap: () async {
await UserManager().clearUser();
Navigator.pushReplacementNamed(context, RouteNames.splashView);
},
DrawerItem(
color: AppColors.primary,
icon: Icons.chat_bubble,
title: 'Emp_details',
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => Emp_detailsViewModelScreen(),
child: emp_details_entity_list_screen(),
),
),
);
},
),
],
),
);
}
DrawerItem(
icon: Icons.logout,
color: Colors.red,
title: 'Logout',
onTap: () async {
await UserManager().clearUser();
Navigator.pushReplacementNamed(context, RouteNames.splashView);
},
),
],
),
);
}
}